Re: Best Practice for Returning Immutable Objects?
Re: Best Practice for Returning Immutable Objects?
- Subject: Re: Best Practice for Returning Immutable Objects?
- From: "Michael Ash" <email@hidden>
- Date: Wed, 4 Jun 2008 10:33:50 +0800
On Wed, Jun 4, 2008 at 3:07 AM, Seth Willits <email@hidden> wrote:
> On Jun 3, 2008, at 9:15 AM, j o a r wrote:
>
>>> Would it be sufficient to cast, like this?
>>> :
>>> return (NSData *)myData;
>>>
>>> Does this generalize to other non-collection classes, e.g., NSString?
>>
>>
>> In the general case yes.
>
> I used to think that. Now I'm converting to making sure it truly is
> returning an immutable object. There have been cases where I've changed it
> under myself and run into problems. I figure if it says it's immutable, it'd
> better be immutable.
There are two fairly different cases to consider.
In one case, you're returning a pointer to a mutable instance
variable. Returning a copy can be a very good idea here, because you
might change the value when the caller doesn't expect it.
In another case, you're returning a mutable temporary object. Since
nobody else has a pointer to it, it can't change spontaneously, so
copying it is fairly pointless. This looks to be the case that the
original poster is in.
Mike
_______________________________________________
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