Re: returning nil on initialization
Re: returning nil on initialization
- Subject: Re: returning nil on initialization
- From: Andy Lee <email@hidden>
- Date: Fri, 2 Apr 2004 00:57:38 -0500
On Apr 1, 2004, at 5:26 PM, Chris Hanson wrote:
Not necessarily. [super init] can return a different self,
particularly when class clusters are involved. This is why you should
never write the following:
NSString *s = [NSString alloc];
[s init];
This is a special case of a more general pitfall that can occur when
(1) you ignore a method's return value, and/or (2) a method's name
misleads you into thinking its return value can safely be ignored.
For example, consider the NSArray method -sortedArrayUsingSelector:.
The Apple programmer who named that method could have saved us all a
bunch of typing by naming the method -sortUsingSelector:. But then you
could have code like this:
NSMutableArray *myArray;
// ...
[myArray sortUsingSelector:@selector(compare:)]; // oops!
A reasonable person could easily overlook the bug here, especially if
he didn't write the code himself, or if he's new to Cocoa. It looks
like it's telling myArray to sort itself, because "sort using selector"
is a verb phrase. The noun phrase "sorted array using selector" makes
it clearer that there's a return value, so the bug is easier to spot in
the following:
[myArray sortedArrayUsingSelector:@selector(compare:)];
One could argue that "-init" is a misnomer, because it's a verb phrase.
Even after seeing the pattern "[[MyClass alloc] init]" many times,
it's easy to assume the return value of -init is merely a convenience,
as it is for -retain. Things would be clearer if -init were renamed
with a noun phrase, like this:
myInstance =
[[MyClass alloc]
transformedIntoAnInitializedInstance];
But I'm willing to live with "-init".
Once in a while I deliberately ignore a return value that would
normally serve some purpose (for example, maybe I'm sending the message
to force a cache to be loaded). As a way of reminding myself that's
what I'm doing, I'll cast the message expression to (void):
(void)[foo resultOfOperationThatIsSlowTheFirstTime];
--Andy
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.