Ben Collins-Sussman <firstname.lastname@example.org> writes:
> Even though I'm only 28 years old, I feel like an ancient curmudgeon.
> I learned C++ ten years ago, and in those days we thought of instance
> objects as "structures with methods". But a class instance is still a
> *structure*. Why can't you look at the structure's fields?
The primary reason not to do things this way is because it constrains your
To use a constructed example, suppose that you have an object that
represents a file. Among the information that it stores is an offset into
the file, stored as the appropriate integer type.
All good. Clients can access it directly. No need for those annoying
But wait... you then port the object to an operating system that doesn't
use flat offsets. It instead represents file positions by a struct that
contains a "page" number and an offset into that page. Aaaa!
After a lot of work, you manage to hide that complexity from your clients
by assembling and disassembling flat offsets from the native offset
struct... except that all your clients are directly reading your object
data and expect to see an integer there. So you now have to add another
field to your object called real_offset containing a struct with the page
and offset, the field that all the clients are using becomes a computed
field, and now you have to keep both of them in sync whenever they change
just in case something directly reads the pure integer offset. Ick.
Now suppose you'd used an accessor function. All you have to do is modify
the accessor function to compute the integer value rather than just
returning the field of the object, and all of the clients behave the same.
You can then safely change the object field to store the native offset in
whatever way is most convenient for portable coding. No need to store the
same data twice, no need to do extra work (you only have to do the
computation when something actually asks for the flat offset).
Basically, accessor functions let you isolate clients of your object from
data type changes and algorithm changes that cause things that used to be
static information to become computed information.
Russ Allbery (rra_at_stanford.edu) <http://www.eyrie.org/~eagle/>
To unsubscribe, e-mail: email@example.com
For additional commands, e-mail: firstname.lastname@example.org
Received on Sat Oct 21 14:36:50 2006