|
The key benefits of encapsulating class internals and exposing only its services is that -
Robust and bug free code
Encapsulation enforces the other classes to use your class correctly. We saw earlier in figure 11.1 how encapsulation mandates the user classes of Elephant to access the age variable appropriately. Since the implementation-details of you class are hidden from outside classes, they are well protected. Other classes cannot break it by sending invalid inputs or calling its internal methods.
Maintainability
You can change the class internals any time without affecting or breaking the code of other classes that are using your class. These classes are not affected because they are not allowed to use the internal details in the first place. For example you can modify the setColor() method to change color only if its is one of the predefined colors. You may write a private method validateColors() for that. Any changes in color validation criterion does not affect the classes accessing color variable. Because they doing so via accessors. As long as accessors are same, user classes are not affected by any changes validateColor() method. Thus tight encapsulation makes the code flexible and very adaptive for modifications. Consequently it is easier to maintain.
Ease of use
Usually, the user-classes of you code are interested only in the services your class provide. They are not interested in the guts of your class. A tightly encapsulated class is self-documenting, as a quick look at its public methods can tell what services it provides.