5 Hide class implementations

 

This chapter covers

  • The importance of hiding the implementation of a class
  • The Principle of Least Knowledge
  • Lazy evaluation
  • Getter and setter methods and immutable objects
  • Rules of the Law of Demeter
  • The Open-Closed Principle

Well-designed applications incorporate proven design principles. Chapter 4 discussed the importance of loose coupling in class design. Two loosely coupled classes have minimal dependencies on each other, which helps ensure that changes in one class don’t cause changes in another class.

We can certainly be proud when other programmers admire and use the classes we wrote. But well-designed classes hide their implementations by making their instance variables and methods private. A class should expose by making public only those members that other programmers need to access.

This chapter covers design principles that support a strategy to minimize the dependencies among classes. Implementation hiding is an important part of encapsulation. If we hide the implementation of a class, other classes can’t depend on what they can’t access. Therefore, we can make changes to the implementation without forcing other classes to change in response.

5.1 The Principle of Least Knowledge and hidden implementations

5.2 Public getter and setter methods access hidden implementation selectively

5.3 Class Date: A case study of implementation hiding

5.3.1 Iteration 1: Date arithmetic with loops

5.3.2 Iteration 2: Julian day numbers simplify date arithmetic

5.3.3 Iteration 3: A hybrid approach with lazy evaluation

5.4 Public setter methods carefully modify hidden implementation

5.5 Beware of dangerous setter methods

5.6 Rules from the Law of Demeter

5.7 But is the implementation really hidden?

5.8 The Open-Closed Principle supports code stability

5.9 Summary