Why do common collection classes in Objective C like NSString, NSArray, NSDictionary etc have a mutable as well as an immutable version.
the concept is used in related langauges. the notable distinction is that the objc types are named mutable variants. similar langauges typically accomplish this via application of a keyword, such as
const. of course, other related languages also use types which are explicitly mutable or immutable.
What is the logic behind defining them separately?
objc messaging does not distinguish const and non-const, and the language does not provide builtin support for ensuring an object's state does not change (although it really would not be a difficult addition if one were really inclined to extend a compiler). so there's a little bit of history involved here too.
therefore, it's convention for the class to define immutability vs mutability, and to supply variants which distinguish mutability.
multiple abstractions also introduce type safety and intention.
yes. there are multiple optimizations an invariant object can make.
some cases include:
- it could cache values, never computing them more than once.
- it could use exact, nonresizable allocations for its data.
- it often does not need any special code for multithreaded use -- many immutable types will only mutate during construction/destruction.
- these types often use class clusters. if a class cluster is implemented, then specialized implementations can provide significant differences in memory, implementation, etc. consider how an immutable string with exactly one character could differ from a mutable variant.
some cases include:
- immutable types could share their immutable contents.
- they may also reduce allocations. for example, an implementation of
initWithType: could return the source retained, rather than a deeep or shallow physical copy.
or anything else?
it makes it easier to write clear interfaces. you can guarantee and (attempt to) restrict some things. if everything were mutable, there would be many more mistakes to make and special cases. in fact, the distinction could entirely change the way we approach writing objc libraries:
[[textField stringValue] appendString:@" Hz"]; [textField stateDidChange];
so it's nice to be able to pass objects around without worrying that the client will change behind your back, while avoiding copying all over the place.