Nested method calls vs. one-shot variables
What is the best practice when nesting method calls or using one-shot variables?
Should you never use one-shot variables?
example:
[persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType
configuration:nil
URL:[NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"storedata"]]
options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption]
error:&error];
Should you always break up a nested method into one-shot variables?
example:
NSNumber *yesNumber = [NSNumber numberWithBool:YES];
NSDictionary *optionsDict = [NSDictionary dictionaryWithObject:yesNumber
forKey:NSMigratePersistentStoresAutomaticallyOption];
NSString *urlPath = [applicationSupportDirectory stringByAppendingPathComponent:@"storedata"];
NSURL *url = [NSURL fileURLWithPath: urlPath];
[persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType
configuration:nil
URL:url
options:optionsDict
error:&error];
Or should you use some combination of the two?
example:
NSDictionary *optionsDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:NSMigratePersistentStoresAutomaticallyOption];
NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent:@"storedata"]];
[persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType
configuration:nil
URL:url
options:optionsDict
error:&error];
I tend to go with a combination of the two but I would like to hear wha开发者_如何学Got everyone else has to say about this. In case it is not clear above, these "one-shot variables" are created for the sole purpose of breaking up the nested method and will not be used anywhere.
Personally I think that you should use "one-shot" variables since it doesn't come with any overhead (in "release" mode, that is with optimization on) and it makes debugging easier. Unless of course you have a specific reason not to.
If one-shot variables make your code more readable, use them. There's not often a reason for it to matter, AFAIK.
My vote is to go for whatever is easiest to read.
When I provide code examples here on SO, I use one-shot variables (OSV) because it's easier to explain it to somebody that way. But I don't use them in my own code that much.
If there is a section of my code that needs code comments I look at that as a good candidate to refactor into a method. Same with variables. If I need to think about what a parameter represents I might have that as a OSV, but for obvious parameters, such as nil
or myView.subView
, I find it harder to read if I create separate variables for them.
To answer the question: I use a mixture as you do, but I try not to worry too much about these things. Coding styles are meant to be guidelines, not rods for our backs -- As long as the code is readable and consistent.
精彩评论