Setters idiom in Java is an evil and I hate it. And I don't hate it because you have to invoke
Maybe I can suggest this idea as a JSR-666 (there are two links :)? I'm curious what is your opinion about this idea. Please share your thoughts in the comments zone.
setXXX
methods multiple times when you have to set many fields. The most annoying thing for me is that you can only set one field in a line. This is because setter method return this stupid void
. Here is the example:so my code using the Car class will look like this:
public class Car {
private int maxSpeed;
// remainder omitted
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
// remainder omitted
}
I have an idea how the life of the developers can be made easier using builder-style setters "pattern". Here is the new BETTER Car class:
Car car = new Car();
car.setMaxSpeed(210);
car.setSpeedUnit("km/h");
car.setLength(5);
// remainder omitted
I could instantiate and initialize my Car object in one line (maybe wrapped but still one line of code):
public class Car {
private int maxSpeed;
private String speedUnit;
// remainder omitted
public Car setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
return this;
}
public Car setSpeedUnit(String speedUnit) {
this.speedUnit = speedUnit;
return this;
}
// remainder omitted
}
What do you think? Isn't it much easier? Of course if you extend Car class it becomes more tricky as you have to repeat all the setter methods like this:
Car car = new Car()
.setMaxSpeed(210)
.setSpeedUnit("km/h")
.setLength(5)
...
But hey - who extends simple JavaBeans?
public class Truck extends Car {
private int capacity;
private String capacityUnit;
// remainder omitted
@Override
public Truck setMaxSpeed(int maxSpeed) {
super.setMaxSpeed(maxSpeed);
return this;
}
@Override
public Truck setSpeedUnit(String speedUnit) {
super.setSpeedUnit(speedUnit);
return this;
}
// remainder omitted
}
Maybe I can suggest this idea as a JSR-666 (there are two links :)? I'm curious what is your opinion about this idea. Please share your thoughts in the comments zone.