Thursday, 21 November 2013

Understanding the impact of Encapsulation in Programming

I have been learning about OOP principles for a long time now and Encapsulation or Data Hiding interested me most. This is because, at the face of it, it sounds and appears most simple. But, for a fact, I always knew given my little practical experience that I understood very little about it and as to why it even mattered. 
I had been reading all along about it in different books on Java and thereafter online. Some of them helped me attain an insight while the others were more like text book material. I finally happened to read "Effective Java" by Joshua Bloch and I can see things getting better already.
The most interesting idea underlying the declaration of data member variables of a class as "Private" or in a more relaxed environment, "Default" (commonly referred to as Package-Private) is to mitigate effects due to coupling between different modules of a program or the application itself in a broader sense. Such a careful design ensures that the different modules are developed, tested and maintained as independently from one another as possible. This ensures that any holes or bugs present in one module do not seriously impair another module and thus preventing the effects of one or two holes in one or two isolated modules from hampering the entire system itself. This is in keeping with maintainability, of course.
Just to give you a simple example, consider the following classes, Square and AreaOfSquare:
class Square {
public int side;
}// end of class Square

class AreaOfSquare {
private int area;
public int getArea (Square s) {
area = s.side*s.side;
return area;
}
}// end of class AreaOfSquare
Well, while it is a rather funny thing to declare "side" as "int", it is still a possibility especially if the designer never anticipated the need for a more precise definition of this parameter. Now, say tomorrow. this designer felt like going back on his design and getting the declaration changed to "double" instead, he would have to also change the declaration of "area" inside the AreaOfSquare class to "double". It is reasonably simple for such one-one dependency between two classes, but if we had a few more classes that were dependent on Square, it would be a fairly complex undertaking from the testing and maintenance perspective. In fact, it would even be reasonable to make an assumption that the designer would himself be unable to recollect all such dependencies and do the repairs accordingly.

No comments:

Post a Comment