chapter six

6 Encapsulate, to localize invariants

 

This chapter covers:

  • Enforcing encapsulation with Do not use getters and setters [R6.1.1]
  • Eliminating getters with Eliminate getter or setter [P6.1.3]
  • Using Encapsulate data [P6.2.3] to Never have common affixes [R6.2.1]
  • Eliminating an invariant with Enforce sequence [P6.4.1]

In chapter 2, we discussed the advantage of localizing invariants. We have already done that when introducing classes because they pull together functionality concerning the same data, and thereby also pulling the invariants closer and localizing them. In this chapter, we focus on encapsulation — limiting access to data and functionality — such that invariants can only be broken locally and therefore are much easier to prevent.

6.1. Encapsulating without getters

At this point, the code follows our rules and is already much more readable and extendable. However, we can do even better by introducing another rule: Do not use getters and setters [R6.1.1].

6.1.1. Rule: Do not use getters and setters

Statement

Do not use setters or getters for non-boolean fields.

Explanation

When we say setters and getters, we mean methods that directly assign or return a non-boolean field, respectively. We also include C#'s properties. Notice that this has nothing to do with a method’s name — it may or may not be called getX.

6.1.2. Applying it

6.1.3. Refactoring: Eliminate getter or setter

6.1.4. The final getter

6.2. Encapsulating simple data

6.2.1. Rule: Never have common affixes

6.2.2. Applying it

6.2.3. Refactoring: Encapsulate data

6.3. Encapsulating complex data

6.4. Eliminating a sequence invariant

6.4.1. Refactoring: Enforce sequence

6.5. Dealing with enums

6.5.1. Enumeration through private constructors

6.5.2. Remapping numbers to classes

6.6. Summary