Wednesday, January 30, 2008

Idle curiosity concerning empty immutable collections

Mutability is an important fundamental that is often ignored by software engineers, and much better software design is often forthcoming when immutability is enforced properly.

Cocoa, very commendably, makes a hard distinction between mutable and immutable objects: e.g. NSString, NSArray, NSDictionary etc. , and one of the things I'd expect is for the empty instances of these classes to be singletons. Indeed NSNull returns a singleton, and in a quick test [NSString string] appears to return the same instance (though this may just generally due to interning/caching: a specific feature of strings). So, I was surprised to find that [NSArray array] yields new instances of empty arrays every time.

This is really no big deal of course, and I'm sure the actual benefits of singleton empty immutable objects is vanishingly small in time or space in any real application, but I was surprised nonetheless to find that the design that led to such a good differentiation between mutable and immutable classes did not go on to include singleton empty instances for these classes.

It's possible there's some historical reason for this choice, or equally likely that it was no 'choice' at all - and the truth is merely that nobody cared enough to do this.

Anyway... back to real life...

No comments: