[Python-Dev] Mutability vs. Immutability (was Re: lists v. tuples)

Bill Bumgarner bbum@codefab.com
Sat, 15 Mar 2003 08:46:19 -0500

On Saturday, Mar 15, 2003, at 01:35 US/Eastern, 
python-dev-request@python.org wrote:
> This has its downside too though.  A function designed to take an
> immutable class instance cannot rely on the class instance to remain
> unchanged, because the caller could pass it an instance of the
> corresponding mutable subclass!  (For example, the function might use
> the argument as a dict key.)  In some sense this inheritance pattern
> breaks the "Liskov substibutability" principle: if B is a base class
> of C, whenever a B instance is expected, a C instance may be used.

In practice, this isn't an issue though it does require that the 
developer follow a couple of simple patterns.   Since Objective-C is a 
C derived language, requiring the developer to follow a couple of extra 
simple patterns isn't a big deal considering that the developer already 
has to deal with all of the really fun memory management issues 
associated with a pointer based language.

Namely, if your code takes an array-- for example-- and is going to 
hang on to the reference for a while and expect immutability, simply 
copy the array when storing it away:

- (void) setSearchPath: (NSArray *) anArray
     if (searchPath != anArray) {
	    [searchPath release];
	    searchPath = [anArray copy];

If anArray is mutable, the invocation of -copy creates an immutable 
copy of the array without copying its contents.  If anArray is 
immutable, -copy simply returns the same array with the reference count 
bumped by one:

// NSArray implementation
- copy
     return [self retain];

Easy and efficient, as long as the developer remembers to follow the