Encapsulation, It Isn’t Just For Your Public Interface
Tuesday, March 23rd, 2010Encapsulation, one of Object Orientation’s (OO) “Big Three” (or four if you include composition), is the concept most often forgotten when I ask an interview candidate to define the key tenants of OO. Giving the benefit of the doubt, perhaps it is considered “obvious” and hence not necessarily related to OO design in the person’s mind. Once I bring it up though, there is usually agreement that it is an important aspect to achieving significant value from OO design.
Classically, encapsulation, also called information hiding, “serves to separate the contractual interface of an abstraction and its implementation.”1 The idea is that the user of the functionality only knows about the public interface (contractual interface) and has no knowledge, nor any ability to tie itself, to the implementation. The implementation includes both data representation and, effectively, algorithm.
Many times I’ll get an alternate definition; essentially the respondent will define encapsulation as, “as an approach which allows an object’s behavior to be called without the caller having knowledge of how the behavior is implemented.” This seems very close to the classical definition but misses the key point of “contractual interface.”
I could argue that when any method is called the caller doesn’t have knowledge of how the method is implemented; it just gets a value back. The missing aspect, the key aspect, is the constraint regarding which methods the caller may call, e.g. the public interface.
What started me on this topic was a recent conversation with a peer regarding read-only objects. Before I get into specifics, let me baseline the traditional encapsulation approach in a typical object.