Encapsulation is hierarchical

From CSSEMediaWiki
Jump to: navigation, search

When people are talking about object oriented designs, one common problem they are facing is deciding if a member of a class should be open to everyone outside or should just kept known by the class itself. The answer for this fundamental question is never to be simple and never to be unique. The best answer for this problem probably should be “don’t make primitive things globally public”.

Public members of a class should only be those ones which are necessary for other classes to make use of the class. Other details which are not directly relevant or necessary for other class to use should be kept private. And this rule should be further extended to other program units, i.e. might not always be talking about class, the boundary of the encapsulation could be of method, class, package/modules.

Some classes should have many public members, because these members are fundamental for making use of the class. In this case, it is important that this class with many public members is nested within another class which keeps them private. This is the notion if hierarchical encapsulation. So, any class which uses another class with many public members, should keep those members private.

Some of the benefits include:

  • It keeps a cleaner “interface” for others to use, all the detail is kept private so it does not interfere with making use of the class.
  • Avoid the danger of people making use of the parts which you are not planning to support (in such a way a user of your class might assume)
  • As results, a clean interface can be provided while allowing the freedom of changing details internal to the class.

External Links

More interesting comments can be found at https://c2.com/cgi/wiki?EncapsulationIsHierarchical

Personal tools