Re: Returning exactly what has been promised
Re: Returning exactly what has been promised
- Subject: Re: Returning exactly what has been promised
- From: Bill Bumgarner <email@hidden>
- Date: Tue, 22 Jul 2008 23:17:41 -0700
On Jul 22, 2008, at 9:54 PM, Steve Cronin wrote:
I find if I have a method which returns an NSString for example,
that often, in the interior of that method I will use an
NSMutableString to construct the string I intend to return. My
question concerns the actual final return statement.
Is there ANY reason to choose A over B?
A) return [NSString stringWithString:myWorkingMutableString];
B) return myWorkingMutableString;
It just kinda sticks in my craw me that I 'promised' an NSString and
using (B) I don't return one.
Yeah I do understand inheritance and that a mutable entity
isKindOfClass of the base class
I looking for reasons like edge cases, compiler optimization, error
trapping, portability, etc..
Is there ANY benefit to the costs associated with the explicit
declaration of (A)?
Casting up the class hierarchy -- more specific to less specific --
upon return is an oft used implementation pattern. In particular,
returning the immutable superclass of the mutable classes from
Foundation (as in this case).
There is, however, a very real risk herein.
Specifically, consider if myWorkingMutableString was an instance
variable of your class. By returning myWorkingMutableString
directly, you have created the potential for encapsulation violations
in two ways:
(1) Caller grabs a reference to myWorkingMutableString, retains it,
and expects the value to remain constant over time. Your class
changes the contents and the aforementioned caller explodes.
(2) You return a reference to the instance variable
myWorkingMutableString and the caller does something silly and mutates
the string. Your class's instance explodes.
If you feel the need to defend against this kind of stuff, you can do
something like:
- (NSString *) myWorkingMutableString
{
return [[myWorkingMutableString copy] autorelease];
}
If using GC you can omit the -autorelease bit.
b.bum
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