Billworth Vandory Billworth Vandory - 1 month ago 6
Java Question

calling setters from a constructor

What are the pro's and con's of calling out to a mutator from a constructor (if any)

i.e.:

public MyConstructor(int x) {
this.x = x;
}


versus:

public MyConstructor(int x) {
setX(x);
}

public void setX(int x) {
this.x = x;
}


Do you have a preference? (This is not homework, just looking at our coding standards doc where it says to always call out to mutators when setting instance var's in the constructor and I don't always to this)

Answer

Personally, I would set the variable directly in most cases.

Methods usually expect that the instance is fully-formed by the time they're called. In particular, calling an overridden method from a constructor is a recipe for hard-to-understand code and hard-to-spot bugs.

Having said that, I often try to make classes immutable anyway, in which case not only is there no setter, but you have to set the final variable from the constructor (or a variable initializer) anyway :)

Where properties have logic, setter logic is usually validation and sometimes change propagation to observers. I'd usually expect the constructor parameters to be checked explicitly at the start of the method, and you wouldn't want any change propagation to occur before an instance is fully created anyway.

Comments