My BigBlock class needs a few overloaded constructors. All of them need to initialize the same few fields in the same way.
What is the proper way to do this? Is it to make a function, e.g. Initialize in the example below, that does these things, and have all constructors call that function?
public class BigBlock {
private Thing parentThing;
Units lengthUnit;
LabCoordinateSystem labCoordinateSystem;
private void Initialize(){
lengthUnit = parentThing.getPreferredUnits(0);
labCoordinateSystem = parentThing.getCoordinateSystem();
}
BigBlock(Thing myThing){
parentThing= myThing;
Initialize();
}
BigBlock(Thing myThing, double x, double y, double z){
parentThing= myThing;
Initialize();
// more code involving x, y, z
}
// a few more constructors
}
Typically it’s best to make all constructors chain to a single one which contains the most information, e.g.
It becomes slightly weirder if there are different ways to call the constructor which don’t effectively represent subsets of the same information – but at that point I’d say there’s a design smell anyway.
Note that by the time you’ve got all the real logic in a single constructor, you don’t need your
Initializemethod (which should beinitializeto follow Java naming conventions, btw) at all – which may also you can make fields final which previously you couldn’t have done.