A package with dozens of similar classes that contain just one or two lines of code is a maintenance and file management problem.  Too many files can hamper refactoring attempts, and fills packages with needless clutter.  In these cases a single class may have sufficed - the variations could be managed using configuration.

For example, imagine an animal testing package exists with many classes that do pretty much the same thing.

ElephantTest.java

 public class ElephantTest extends BaseAnimalTest  
{
    public ElephantTest(String name)  
    {
        super(name, Elephant.class);
    }
}

TigerTest.java

public class TigerTest extends BaseAnimalTest  
{
    public TigerTest(String name)  
    {
        super(name, Tiger.class);
    }
}

ToucanTest.java

public class ToucanTest extends BaseAnimalTest  
{
    public ToucanTest(String name) 
    {
        super(name, Toucan.class);
    }
}

Thirty classes later, there is mindless repetition and proliferation of class files.    

Instead, how about something like this to provide the same level of test coverage?

/**
 * Tests each of the animal classes in turn.
 */
public class AnimalsTest extends BaseTest
{
    public void testAllAnimals()
    {
        // When it is easy to update junit tests, programmers are  
        // more likely to go to the trouble of updating them.
        testAnimal(Elephant.class);
        testAnimal(Tiger.class);
        testAnimal(Toucan.class);         
        :
        // if there were more than five classes or so, you might
        // consider ordering by classname so you could easily
        // see if any were missed.
    }

    :
    :
}

Exception: This example comes from actual code but in most situations it is perfectly OK to split up a concept into a set of classes that will be expanded later.  It also doesn't mean you should group dissimilar classes into a single class.  This rule is for obviously similar classes in structure only and already in the same package.

blog comments powered by Disqus