posted 11 years ago
In order to see how one can implement encapsulation in Java, let us see design smells associated with encapsulation. We identified three smells associated with encapsulation:
1. Lenient Encapsulation
This smell occurs when the declared accessibility of one or more members of an abstraction is more permissive than actually required.
For example, Rectangle class exposes its data members and hence Rectangle class from JDK suffers from Lenient encapsulation smell.
2. Missing Encapsulation
This smell occurs when there exists global state (in the form of global variables, global data-structures, etc.) accessible to all abstractions in the software system.
For example, consider the following members defined in java.lang.System class:
Since they are declared coderanch, any code (i.e., other classes in JDK as well as application code) can access these members directly. Hence, these members are effectively global variables!
3. Unexploited Encapsulation
This smell arises when client code uses explicit type checks (using chained if-else or switch statements) instead of exploiting the variation in types encapsulated within a hierarchy.