Re: Best Practice for Returning Immutable Objects?
Re: Best Practice for Returning Immutable Objects?
- Subject: Re: Best Practice for Returning Immutable Objects?
- From: Karl Moskowski <email@hidden>
- Date: Tue, 3 Jun 2008 12:28:29 -0400
On 3-Jun-08, at 12:23 PM, email@hidden wrote:
Karl Moskowski wrote on 2008-06-03 17:16:48:
On 3-Jun-08, at 12:13 PM, Mike Abdullah wrote:
Well this cast is fairly pointless as it makes no change to the data
at all. Returning an NSMutableData object from an NSData method is
perfectly legitimate as it is a subclass. So you might as well just
do:
return myData;
Really, it's up to you. You can just use the simple option of
returning a mutable object, or you can do either of these:
return [NSData dataWithData:myData];
return [[myData copy] autorelease];
My concern is that the returned object be truly immutable. For now,
I'm the only one using the class, but that may change in the future.
If it has to be 'truly' immutable, then use one of Mike's suggestions,
which will return an immutable NSData object containing the same
bytes as
the bytes in the mutable object you constructed. The code you
originally
posted still returns the mutable object; casting doesn't change the
'isa'
which is what tells the ObjC runtime what class the instance is. I.e.
given an NSMutableData *foo:
(NSData *)foo "is a" NSMutableData
(NSObject *)foo "is a" NSMutableData
(id) foo "is a" NSMutableData
Maybe "truly" was too strong a word. :-)
Since I can expect people to follow the conventions defined by the
API, I'll just cast and expect the callers not to mutate.
Thanks.
----
Karl Moskowski <email@hidden>
Voodoo Ergonomics Inc. <http://voodooergonomics.com/>
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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