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.