Re: question about mutable vs. non-mutable
Re: question about mutable vs. non-mutable
- Subject: Re: question about mutable vs. non-mutable
- From: Peter Duniho <email@hidden>
- Date: Thu, 30 Apr 2009 20:43:40 -0700
On Apr 30, 2009, at 6:47 PM, Ali Ozer wrote:
[...]
What I don't get is... why is there NSMutableString and NSString?
#1. It seems weird to me that a string object can't be modified
once it's
created. Why is this?
Immutable objects are useful for various reasons:
- Knowing that they can't change can help you predict your program's
behavior better. If you stashed away an immutable object in a data
structure, you know it will not have changed later on.
Note that the benefit of "you know it will not have changed later on"
is not just about helping "you predict your program's behavior
better" (in fact, I'd argue if you can't easily predict your program's
behavior, you haven't implemented it well :) ).
There are lots of scenarios where knowing an object can't mutate is
useful, but IMHO one of the most important is when implementing multi-
threaded code. One of the hardest things for people to get right
about multi-threaded code is dealing with objects that have to be
modified in one or more threads, while accessed by one or more _other_
threads.
Obviously, if you can't modify an object, then the entire business of
dealing with objects that have to be modified becomes a non-issue.
It's not a panacea, but it's a very powerful coding technique, and
having classes like NSString and NSArray aid in that. (Ignoring for a
moment the slight weakness in Cocoa's implementation caused by having
the mutable versions inherit the immutable versions, in that you have
to be in charge of the code creating the immutable version to
guarantee that the object is truly immutable...in practice, this isn't
that big of a problem IMHO, and having that inheritance relationship
can be helpful in other ways).
Pete
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden