Replace Constructor With Factory Method

This refactoring is described in MartinFowler's book, RefactoringImprovingTheDesignOfExistingCode, and is based on the FactoryMethod pattern in the book DesignPatterns.

The reason I bring it up is that I was disturbed by the suggestion at the end of the example as to how to refactor a factory based on magic type codes into a factory based on class names. His suggestion was to overload the factory method so that one version uses integers, another uses strings, and then change the callers to use the strings instead of the integer tokens.

As an alternative, I propose that the constants that describe the type codes be converted to type strings, as follows:

static final string ENGINEER = "Engineer";
// before refactoring: static final int ENGINEER = 0;
static final string SALESMAN = "Salesman";
static final string MANAGER = "Manager";

With this simple refactoring, all the source that called create(int) magically calls create(String) for the same effect -- with the added bonus that the class names are not exposed (helpful when using inner classes) and spelling errors are constrained to the constant declarations. There is the little issue of package names that needs to be faced, however.

Of course, the above refactoring breaks create(int). I suggest making the following change first to maintain operation (especially important if binary compatibility is an issue) and legibility:

static Employee create(int type) {
final static String[] typeMap {"Engineer", "Salesman", "Manager"};
return create(typeMap[type]);
}

(but remember to ConvertExceptions).

-- BillTrost


EditText of this page (last edited November 14, 1999) or FindPage with title or text search