Suppose you have a class with this constructor:
public SomeObj(int x, int y) {
this.x = x;
this.y = y;
}
All good. But now if you want to clone the object, I want a constructor to accept one argument with an object from that type, so inside the constructor all (necessary) fields can be copied.
public SomeObj(SomeObj objectToClone) { ... }
But now which of the following two ways is better? What are the advantages and disadvantages (performance (byte code), readability…)?
// 1
public SomeObj(SomeObj objectToClone) {
this.x = objectToClone.x;
this.y = objectToClone.y;
}
// 2
public SomeObj(SomeObj objectToClone) {
this(objectToClone.x, objectToClone.y);
}
I would go with the latter, personally.
Where possible, I try to make exactly one constructor have a “real” body, and make all others delegate to it. That’s not always possible – in particular, different constructors may need to delegate to different superconstructors – but it’s nice knowing there’s one place you can put extra initialization, logging, breakpoints etc which will always get hit.