6 Encapsulate, to localize invariants
This chapter covers:
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.