Good design for class with similar constructors
Posted
by
RustyTheBoyRobot
on Programmers
See other posts from Programmers
or by RustyTheBoyRobot
Published on 2012-06-06T20:11:13Z
Indexed on
2012/06/06
22:47 UTC
Read the original article
Hit count: 343
design
|refactoring
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
PrimaryKeyclass and aSerialNumberclass). I like this because it seems to be a better design, but it also is a pain to refactor ifserialNumberis aStringeverywhere else.
© Programmers or respective owner