One major advantage of using objects is that they do not need to reveal all of their attributes and behaviors. When designing a class, it is generally a good practice to only reveal the necessary interfaces needed to interact with the object, and hide the implementation details that are not precisely relevant. This hiding of details is known as encapsulation.
The concept of encapsulation is better enforced with the definitions of interfaces and implementations. An interface is defined by the services of communication between objects. Classes declare some methods and properties as visible to outside objects, and hide the other details. The visible, or public, methods and properties become the interface to the object. Interfaces typically only include methods, since any need to access an attribute should be made available through a public method. This is an important concept, especially in the realm of testing, since outside objects can only interact with the public interface methods, and not with internal operations that could inadvertently change the object’s state.
Public methods and properties comprise the interface, and the remaining methods and attributes make up the implementation. The benefit of this relationship is that the implementation can change while the interface remains constant.
An example of the interface and implementation paradigm could be described with a post-office mailbox. What the user sees is a box with an identification number, a key slot, and a door. The implementation is what is behind the scenes, and that is basically how the mail is deposited and retrieved. The user does not care how the implementation works, just as long as they can see their box number, insert their key, open the door, and deposit or retrieve mail.
Encapsulation is important because is maintains object integrity. By providing only the most necessary means of data access in the interface, we can prevent unwanted changes to the object’s state through hidden, or encapsulated, methods and properties. With well defined interfaces that rarely change, user interactions and unit testing become oblivious to changes in implementation.
In software design, encapsulation is important since is hides the functionality that is most likely to change, thus protecting other objects that reference its public interface. If encapsulation is a technique, then information hiding is its principle (EncapWiki, 2006). Two main principles of information hiding are discussed further in this article, polymorphism and separation of concerns.
References:
EncapWiki. (n.d.). Retrieve May 26, 2006, from http://en.wikipedia.org/wiki/Information_hiding
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2009 MuellerDesigns.net
Sign In