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