Re: Mutability
Re: Mutability
- Subject: Re: Mutability
- From: "Erik M. Buck" <email@hidden>
- Date: Wed, 21 Nov 2001 17:05:44 -0600
If an object is advertised as immutable then that immutability should be
respected even if the object is actually mutable.
For example:
@interface MYObject : NSObject
{
NSMutableArray *_myArray;
}
- (NSArray *)myArray;
@end
The -myArray method returns an object that should be considered immutable
even if -myArray is implemented to return _myArray. The fact that _myArray
is actually mutable is both an implementation detail that is properly
encapsulated within MYObject and subject to change. Most importantly, the
implementation of MYObject may reasonably assume that the contents of
_myArray will not be modified behind its back!
If your code calls -myArray and modifies the contents of the returned array
then MYObject may break later because its private implementation specific
data that you should not disturb has been violated behind its back. That
will produce subtle and hard to debug errors. DON'T DO IT! If an object is
given an immutable type then RESPECT that regardless of the actual type!
If people insist on dangerous bad foolish inconsiderate bonehead behavior
like modifying the contents of an array that is typed immutable then the
only way to safely implement a class like MYObject is to return a copy from
the -myArray method.
- (NSArray *)myArray
{
return [myArray copy];
}
This introduces inefficiency in the common and sane case where the type is
respected in order to avoid breaking in the rare irresponsible shoddy case
when the type is disrespected.
Are we going to have to implement NSView's - (NSArray *)subviews method to
return an immutable copy of the NSView's instance variable or can we rely on
programmers to respect the type and not change the view's subview array
behind its back ?