What's the benefit of this coding style?
Recently I came across this Objective-C coding style:
- (NSFetchedResultsController *)fetchedResultsController
{
NSFetchRequest *fetchRequest;
NSEntityDescription *entity;
NSSortDescriptor *sortDescriptor;
NSArray *sortDescriptors;
NSError *error;
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
entity = [NSEntityDescription entityForName:@"Deck" inManagedObjec开发者_如何转开发tContext:self.managedObjectContext];
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
[fetchRequest setSortDescriptors:sortDescriptors];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
DLog(@"Failed fetching decks: %@, %@", [error localizedDescription], [error userInfo]);
}
// etc...
The thing I'm talking about are the declarations at the top of the method. What's that for? Is it good practice? It seems to add some clarity to the code, as you can instantly see what variables the method will use, right?
On one hand, it adds clarity as you immediately see what variables the method will use. It is a legacy from C where you had to declare all the variables at the top of a brackets block as no declarations were allowed in the middle of a block.
On the other hand, one may argue that the variable declarations are sometimes far from the place where they will be used for the first time, so it does not help understanding what a variable will be used for. I think it's just a matter of taste.
I can't imagine a benefit from "immediately seeing what variables the method will use", while I see great benefits in declaring variables where they are used, and initializing them on the same line as the declaration.
This style is no longer required and has fallen out of use. However, I could see some benefit if this group of declarations at the top of a method are followed by a corresponding group of releases at the bottom, but as others have pointed out, it comes at the cost of readability.
精彩评论