I want to write bean-friendly classes. I have observed a tendency (mostly with beans) to move required parameters to setters from the constructor (and use an init()
method when done setting up the initial state).
This method concerns me because I want my classes to be usable without a bean infrastructure, just as Java objects. As I imagine I'd have to check for the proper state of the object in every method assert style.
Quick demo for the above:
class A {
public int x;
public int y;
private int sum;
private boolean initialized = false;
public void init() {
sum = x + y;
initialized = true;
}
private void initCheck() {
if (!initialized) {
throw new IllegalStateException("Uninitialized object.");
}
}
public int getXMulSum() {
initCheck();
return x * sum;
}
public int getYMulSum() {
initCheck();
return y * sum;
}
}
Is there a better practice?