Re: nil pointers
Re: nil pointers
- Subject: Re: nil pointers
- From: j o a r <email@hidden>
- Date: Tue, 11 Jul 2006 09:19:44 +0200
On 11 jul 2006, at 04.59, Adam Johnson wrote:
why do Cocoa developers declare pointers as nil, then define them?
I don't think that you can make that general statement.
wouldn't it be easier just to do this?
NSMethodSignature * sig = [[self class]
instanceMethodSignatureForSelector:mySelector];
Absolutely.
On 11 jul 2006, at 05.26, Agent M wrote:
Another use of nil is messaging to hash values:
[(NSWindowController*)[_windowControllers objectForKey:@"window X"]
showWindow:self]; //don't bother checking for nil
That "objectForKey:" returns *nil* when there is no match is a Cocoa
pattern to indicate that the lookup failed, and not really related to
the topic of this thread.
jcr is also right that it is a matter of style too. Personally, I
prefer the old-school declarations:
NSString *gonk,*splonk,*conn=nil;
Note that you only assign *nil* to the last value here...
NSString *gonk=[NSString stringWithFormat:...],*splonk=[sender
window],*conn=[...];
gets cluttered fast.
NSString *foo = [NSString stringWithFormat:...];
NSString *bar = [NSString stringWithFormat:...];
...is as easy to read, and you avoid even having to consider any
unnecessary assignments to *nil*.
Source code serves two purposes: One is the basis for code
generation, and the other is to be the blueprint for the system, to
let the programmer understand what's going on. Both are very
important - but if anything, I would say that the second one is more
important.
When you say "NSString *foo = nil;" you communicate something, and a
programmer would have to pause to think about what it could be. In
the general case this pattern decreases the readability of the code
from the programmers point of view, and it doesn't benefit the compiler.
Clearly there are cases where you might be best served by the "old-
school" early declaration of some variables, and to assign them some
empty / invalid values that can be recognized later on, but I think
that these cases are the exception - not the rule.
It is my opinion that variables should be declared as close to where
they're used as possible, and the programmer should not hesitate to
use blocks of { [...] } to create a narrow scope for variables.
Declaring variables close to where they're used have a lot of
benefits, one of them being that it decreases the need for
unnecessary assignments.
And yes, a lot of this comes down to personal preferences... :-)
j o a r
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >nil pointers (From: "Adam Johnson" <email@hidden>) |