Wednesday, April 9, 2008

Encapsulation and Information Hiding

Encapsulation means hiding the implementation details of the class from other objects and separating the class's implementation from it's interface.


A class's interface is the parts of the class which is exposed to other classes. It's related to but not the same as interfaces like IEnumerable. It's the way an object of the class is exposed to other objects and which members are public, protected or private.


There are two kind of object's interfaces; the parts of the object that is exposed to every other object is called "public interface", and the parts of the object which is only exposed to derived object via inheritance is called "protected interface".


Creating a well defined interface is an essential step in a good object oriented design.


Why encapsulate?


  • Hide implementation details.

  • Maintain the same object's interface while the inner implementation can change without forcing the clients of the object to change the way they consume it.

  • Encapsulation helps abstraction so you will deal with object at a high level of details, so that you use objects like a Button or data Connection as a "black box" and build more complex software with it.

Example; The interface of a  Stack class is that it has "Push", "Pop" and "Peek" method. Other object don't care how the Stack class is implemented, all they care is its interface.
If the stack was implemented using an ArrayList and the developer wants to change it to use a LinkedList instead, all he has to do is to change the inner implementation and leave the interface unchanged, so that all the code outside of the class will continue to work unchanged.


Another example; you may want to write a log file, you write a class to handle logging to the file. The Log class would have a method public void Log(string message) that will handle writing to the log file, take care of the file structure, add date and time to the log entry ...etc.


One more example; You would use Enums to hide the underlying datatype of a type. Let's see this code snippet.


public enum AccountType : byte // define a new type called AccountType with underlying type byte. by default, the underlying type is integer.
{
    Administrator = 0,
    Limited = 1,
    Guest = 2
}


So, you now have a new data type the AccountType type which is actually a byte. The AccountType enum has 3 constants Administrator, Limited and Guest with values 0, 1 and 2 respectively.


AccountType type = AccountType.Administrator; // type = 0 since Administrator = 0 in the enumeration

type = (AccountType)2; // explicit type cast from int (which will be converted implicitly to byte) to AccountType

byte b = (byte)type; // explicit type cast from AccountType to byte



http://en.wikipedia.org/wiki/Information_hiding
Code Complete 2nd Edition by Steve McConnell

No comments: