понеделник, 30 ноември 2009 г.

Quick tip to reduce hierarchical complexity.

This week it is going to be a short and simple one.

Say we build a set of classes implementing a particular interface. For the sake of example we can imagine these classes represent abstractions of test applications used in integration testing fixtures. We may have various implementers - web service provider applications, consumer ones, EJB applications, web applications, so forth.
Inevitably at one point in time we will realize there is common logic between the implementers - for example, creating some j2ee modules and assigning them to an ear module; deploying the application; cleaning up after the application on the fixture teardown, etc.
We may be tempted to remove the code duplication with polymorphism. This is a very common approach, but not a sound one in my opinion.
So, we create a base class to hold the common logic, and the implementers extend it. Why not cool? Well, the problem is that the classes extending this base class have little in common in terms of domain modeling. The only thing in common they have is code. Even the name of the base class will suck, which reveals a code smell. Such classes are usually called (in our example) "BaseApplication", "AbstractApplication" or something like that.
So, what to do? Simple, create utulity class or classes to hold the common code and refer them inside your hierarchy. Now, if certain implementers have special stuff to do to extend the common tasks logic, the utilities might also follow some hierarchy.
Some may say that utility objects are also a code smell, but this approach is cleaner in terms of Object modeling and simpler in terms of type hierarchy, than having a "BaseApplication". Also, it is more flexible, because Java does not support multiple inheritance (thank goodness), so when not extending the 'base application', you retain the option to extend some real class from your domain model.