While coding, I encountered following situation:
I have a class, let's call it C
. It has an attribute A
of arbitrary type which must be calculated first:
public class C {
private int A;
public C(...) {
...
}
public void calculateA() {
A = 42;
}
public int getA() {
}
}
My question now is, how to implement the getter getA
properly. Should I check whether A is defined and throw an exception otherwise?
Or should I just call calculateA
in getA
if it is not set?
What is the best choice for that kind of problem?
Edit: OK, I gave a bad Example. A
cannot be calculated in the constructor, because the calculation method will return a new instance of the same class, which will lead to an infinite recursion.