H
Howard
Julie said:No, you create a new or derived class.
But then you break everyone's code that uses your original object! They now
have to change their code to use your new object, whereas if you just
returned the computed value from the accessor, the user of your class never
even has to know how that value was computed, how it was stored, or
anything. They never even know the underlying accessor code was changed at
all. They get the value they want when they ask for it, and that's all they
should care about.
Experience has taught me this well. In writing database-access programs, I
often had to change something on the back end, and I was in general
*required* to not change the interface. When the user wants the trip
mileage, they never need to know if that was a stored value, or if it was
computed via a third-party mileage lookup. WIth thousands of users of our
system spread across the country, it was *very* important to make these kind
of changes as invisible to the users as possible. (It often took at least a
month to propogate changes to users when we had to make an interface change,
and we had to in effect maintain two system during such transitions...what a
pain!)
You have now just changed the behavior of the original function with respect to
performance, which is a very real and tangible change.
Only in the internal behavior of the object, not in the interface or the
contract to provide the requested value.
This is why I advocate const reference member accessors to simple data -- it
*guarantees* that access to the underlying data is immediate and absolute, and
will stay that way. It doesn't break encapsulation as some have said, but
creates an immutable contract between the class designer and class user. You
can't get that w/ functions.
I don't understand this. Why is a guarantee to "immediate and absolute"
access to the underlying data a requirement? What does the user of the
class care how the data is stored, represented, obtained or calculated? The
contract is to provide the value asked for, not (in general) a specification
of how that value is obtained or stored.
If you have some special requirement to actually see the data, as it is
stored (it that's even possible...sometimes you *have* to calculate it!),
then that's a totally separate need that's not part of the OP's question,
and only relevant to the question in that specific instance, not in general.
For "simple" data (e.g., the built-in types), it's also likely to be more
efficient to return by value than by reference. I'd personally be more
inclined to return by (const) reference something that had a significant
copy-construction overhead.
-Howard