Friday, June 25, 2010

Be careful when using access modifier

When working with frameworks provided by others, I sometimes get a little bit frustrated. Using the "normal" features provided by a framework in general is no problem. But when I have to access more information and go deeper into the code, I often find package-private and private modifiers protecting the code I like to reuse. Most often the problem is not at the method level, the method needed to call is public. In many cases even the constructor of the class is public, the problem begins with the arguments of the constructor or the method.

Oft one of the arguments is a class declared package-private or is public but has a package-private constructor. This forces me to search for a factory-method, which is often hidden deep by other such constructs. Meaning the code is strongly coupled to the framework.

Here is a small example:



I hate such code, especially if there is no special reason why the factory has a package-private constructor. Maybe there is an misunderstanding between information hiding and class design.

In cases where the code doesn't access any data from the framework there is no need to make the constructor package-private. It doesn't matter, if there is a second factory used by someone else. If you really need to have to use package-private, please make use of interfaces. This way it remains still possible to reuse the class by creating a new factory implementation:



I always wonder how the test code for such strong coupled code looks like. If you use interfaces unit testing is an easy task. You might use a mock framework like easymock. Using interfaces your class can be tested independent from the factory implementation and without creating an instance of the framework class.

For easier testing and better reusability, I suggest to use public-interfaces for a reasonable decoupling whenever possible.

No comments:

Post a Comment