Mutability vs. Immutability (was Re: lists v. tuples)
![](https://secure.gravatar.com/avatar/a30cf62a3c51d93816000f76d3e7dc12.jpg?s=120&d=mm&r=g)
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 pattern.... b.bum
participants (1)
-
Bill Bumgarner