Paul Clapham wrote:Don't confuse a formatted version of an object with the contents of the object; there are often many ways to format one set of data.
Indeed, and what's actually inside an object may change from one version of the object's class to another, even if the formatted version of an object's contents remains the same from one version of the object's class to another. That's yet another reason why it is better to use getters and setters than it is to make class member variables directly accessible.
For example:
You can see how the
area method returns a value it computes, rather than stores. But a later implementation of that class might look like this:
While the usefulness of this class might be slight, you can see how, if the only attribute of a Rectangle object your code needs to obtain is its area, then either implementation works. The first one, however, calls for a computation on each query (the compiler might be smart enough to notice that the calculation is computed entirely from final member variables, and only do it once, but it might not, and it might not behave the same way on all platforms). The second one only does the computation once, when the object is constructed. That might be a worthwhile performance enhancement.
But, the point is, code that creates Rectangle objects and that queries them for their area neither knows nor cares how those objects store their values internally. That's as it should be. Your code should only rely on the interface available through a class's methods, and remain blissfully unaware of any internal details.
For C/C++ programmers, that can take a little getting used to, but I have found it's worth it.