Re: Another controversial question
Re: Another controversial question
- Subject: Re: Another controversial question
- From: Chris Gehlker <email@hidden>
- Date: Sun, 02 Sep 2001 22:19:28 -0700
On 9/2/01 1:33 PM, "Drew McCormack" <email@hidden> wrote:
>
I hadn't realized that key-value coding would actually call the accessor
>
method if it were present. This changes things dramatically. It actually
>
isn't really a serious violation of encapsulation, just a means of
>
automatically writing accessor methods.
I don't think this is a valid conclusion. Since an accessor can itself
violate encapsulation, any means of automatically generating accessors can
clearly do so as well.
The essence of encapsulation is that the object is always in a consistent
state after any method completes. Consider, for example, a simple class that
calculates the arithmetic mean of some floats. It could have methods like
mean, a getter, and addFloat: and removeFloat:, setters. Instance variables
could be an NSSet to hold the floats and mean, count and sum to do the math.
Clients don9t care whether the class is aggressive or lazy, they can count
on mean always returning the right answer. Indeed, in the lazy
implementation, mean, count and sum can be dispensed with entirely as
instance variables.
But now if a create a setter for mean, encapsulation for the class is
broken. If the implementation is aggressive, mean can return the wrong
answer. Someone may have called setMean since the last time they called
oddFloat or removeFloat. I'm also no longer free to change to the lazy
implementation because mean has to exist.
I have to conclude that takeValueForKey may violate encapsulation and that
providing an accessor may just formalize the violation.
This is not to say that I think KeyValue coding is a bad thing. It can be
very powerful. It's just that when you use it you have to recognize that the
contract is different and you have fewer guarantees. You as the programmer
are saying "Trust me, I know what I'm doing." In this way it's a lot like
casting in plain old C.
--
In the midst of great joy, do not promise anyone anything. In the midst of
great anger, do not answer anyone's letter. -Chinese proverb