6 Defend the data

 

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 pull invariants closer and localize 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 or setters.

6.1.1 Rule: Do not use getters or setters

Statement

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

Explanation

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

6.1.2 Applying the rule

6.1.3 Refactoring pattern: Eliminate getter or setter

6.1.4 Eliminating the final getter

6.2 Encapsulating simple data

6.2.1 Rule: Never have common affixes

6.2.2 Applying the rule

6.2.3 Refactoring pattern: Encapsulate data

6.3 Encapsulating complex data

6.4 Eliminating a sequence invariant