What's the proper way to ensure a value only gets set once, although the time it will be set is unknown (ie: not in the constructor). I could do a null check or keep track of a flag and throw an exception - but what exception should I throw? It's for a small, localized library and I prefer not to create my own ValueAlreadyAssigned exception for such a seemingly generic case.
In the setter. Do it like this:
private foo bar;
public void setFoo(foo bar) {
if (this.bar == null) {
this.bar = bar;
} else {
System.out.println("Don't touch me!");
// J/K Throw an IllegalStateException as Michal Borek said in his answer.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With