Everyone has an opinion on this, but what I've seen empirically is that state is evil. State forces you to take more information into consideration when understanding how a class behaves since its behavior is now implicitly affected by the state. Avoid it as much as your performance will allow you to. I strongly endorse the second way you mention. The first way will likely cause bugs and headaches.
Generally, some of the worst methods I've seen have signatures like void DoSomething()
: it takes no parameters and returns no value. The entire point of the method lies in its side-effects, which might not be apparent if the method is poorly named.
How obvious would the first way be to someone else? Does it make sense to have something called getData
that doesn't actually return any data? Does it make sense that getData
manipulates the state of the object? Sometimes, yes, manipulating the object for the sake of caching is reasonable. But manipulating the object to store the value you should actually be returning is asking for trouble.
If you really feel like you must go with the first version, at least call it something more accurate like void calculateValue()
or even void calculateCachedValue()
which indicates that it really shouldn't be returning anything and that its entire purpose is to calculate something else.