Monday, April 16, 2007

Encapsulation and information hiding

Encapsulation and information hiding are often used interchangeably. But they are actually different. Information hiding is a design principle, whereas encapsulation is a langauge facility. Encapsulation is the process of bundling code and the data it acts on together in one entity. David Parnas describes information hiding as "hiding of critical design decisions", so that the client code does not have to understand the intricacies of the design, and is also oblivious to any changes in design. Encapsulation can happen without information hiding, but will not be effective. Encapsulation facilitates, but does not gaurantee information hiding. Following some simple guidelines will help us create better classes

Rules for encapsulation:

Rules for information hiding:

These rules have been taken from this JavaWorld article on encapsulation. It's an excellent article that explains the concepts very well with relevant and well thought of code samples.

Something on the side:

In the above article, the author explains the concept of currying functions. If you find many functions in your source code that are likely candidates for currying, then you may have a load of procedural code in an OO language. Something to be aware of and also a signal that the code warrants refactoring.