I am using GWT and am constrained to having zero argument constructors. This means that I am using a static factory method on each class in order to set member variables:
public class Point {
private final float x;
private final float y;
public static Point build(float x, float y) {
Point p = new Point();
p.x = x;
p.y = y;
return p;
}
// getters for x and y
// other methods...
}
Now the problem here is that x and y can not be final as I am setting them outside of the constructor, but ideally I want them to be immutable.
What is the best approach?
It's a good idea to have the language enforce as many properties of your program as possible, and making use of the final
keyword is certainly good practice. But this is a case where the final
keyword is just too strict to make the serialization mechanism of GWT work, at least in it's current state. Therefore you sadly can't make use of this feature.
But I think it's worth to mention that, if you don't provide setters for x and y and keep them private
, you class indeed is immutable. It's just not the language enforcing this, it's your code.