I have been writing Java for almost a year now, and I have seen 2 different conventions for how people implement their setters.
To Illustrate this, here are examples of both conventions. (I would love also to know concise names of these two patters)
Classes using first convention, return nothing from their 'set' methods. Like so:
public class Classic{
private double _x;
private double _y;
public Classic(){
x = 0;
y = 0;
}
public void setX(double d){//or boolean with a type check on input
x = d;
}
public void sety(double d){
y = d;
}
}
Classes using the alternative convention return themselves from their setter methods. Like so:
public class Alternative{
private double _x;
private double _y;
public Alternative(){
x = 0;
y = 0;
}
public Alternative setX(double d){
x = d;
return(this);
}
public Alternative sety(double d){
y = d;
return(this);
}
}
The difference being that with the alternative approach syntax such as
Alternative NewAlt(double x,double y){
return(new Alternative()
.setX(x)
.setY(y));
}
Is possible while with the classic set-up the same factory method would look like this.
Classic NewAlt(double x,double y){
Classic temp = new Classic();
temp.setX(x);
temp.setY(x);
return(temp);
}
It is debatable which of these is more readable/usable.
My question is about the performance difference between these two patterns. Does it exist? If so how big is the difference, and where does it arise from?
If there is no performance difference, which one is considered 'better practice'?
Method chaining may look nice in some situations, but I would not overuse it. It does get used a lot in the builder pattern, as mentioned in another comment. To some degree it's probably a matter of personal preference.
One disadvantage of method chaining in my opinion is with debugging and breakpoints. It may be tricky to step through code filled with chained methods - but this may also depend on the IDE. I find the ability to debug absolutely crucial, so I generally avoid patterns and snippets that could make my life harder when debugging.