5 Class implementations should be hidden

 

This chapter covers

  • The importance of hiding the implementation of a class
  • The Principle of Least Knowledge
  • Lazy evaluation
  • Getter and setter functions 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 the other class.

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

This chapter covers design principles that support a strategy to minimize the dependencies that classes have on each other. 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 functions selectively access hidden implementation

 
 
 

5.3 Class Date: An example of hiding implementation

 

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 functions carefully modify hidden implementation

 
 

5.5 Beware of dangerous setter functions

 
 
 

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

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest