Good design for class with similar constructors
- by RustyTheBoyRobot
I was reading this question and thought that good points were made, but most of the solutions involved renaming one of the methods. I am refactoring some poorly written code and I've run into this situation:
public class Entity {
public Entity(String uniqueIdentifier, boolean isSerialNumber) {
if (isSerialNumber) {
this.serialNumber = uniqueIdentifier;
//Lookup other data
} else {
this.primaryKey = uniqueIdentifier;
// Lookup other data with different query
}
}
}
The obvious design flaw is that someone needed two different ways to create the object, but couldn't overload the constructor since both identifiers were of the same type (String). Thus they added a flag to differentiate.
So, my question is this: when this situation arises, what are good designs for differentiating between these two ways of instantiating an object?
My First Thoughts
You could create two different static methods to create your object. The method names could be different. This is weak because static methods don't get inherited.
You could create different objects to force the types to be different (i.e., make a PrimaryKey class and a SerialNumber class). I like this because it seems to be a better design, but it also is a pain to refactor if serialNumber is a String everywhere else.