ios

写代码有时和说话一样,要体现层次感,可能是首先罗列要点,然后再逐点 细化。但如果时而说要点,时而谈细节,就会造成听者理解上的障碍。如下的代 码就会有这样的一个问题:

重构前:

- (UITableViewCell *)tableView:(UITableView *)tableView 

cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 switch 

(indexPath.section) {
 case 0:
 return [[preferences 

objectAtIndex:indexPath.row] cell];
 break;
 case 1:
 {
 

static NSString *CellIdentifier = @"wikiHowAboutCell";
 

UITableViewCell *cell = (UITableViewCell *)[tableView 

dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == 

nil) {
 cell = [[[UITableViewCell alloc] initWithFrame.:CGRectZero 

reuseIdentifier:CellIdentifier] autorelease];
 }
 

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 

if (indexPath.row == 0) {
 cell.text = @"About wikiHow 

App";
 } else {
 cell.text = @"wikiHow Tips";
 

}
 return cell;
 }
 break;
 }
 return nil;
 }

其中,Case 0和Case 1之间严重失衡,Case 0隐藏了创建的细节,而Case 1 则是将其暴露无遗。抽象层次的差别造成了平衡感地缺少以及理解代码时的“颠 簸”。重构后代码如下:

重构后:

- (UITableViewCell *)tableView:(UITableView *)tableView 

cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 UITableViewCell 

*cell = nil;
 NSUInteger sectionIndex = indexPath.section;
 if 

(sectionIndex == 0) {
 cell = [[preferences 

objectAtIndex:indexPath.row] cell];
 }
 else if(sectionIndex == 

1) {
 cell = [self prepareCellForTable: tableView 

withRowIndex:indexPath.row];
 }
    return cell;
 }
- 

(UITableViewCell *)prepareCellForTable: (UITableView *) tableView 

withRowIndex:(NSUInteger)index {
 static NSString *CellIdentifier = 

@"wikiHowAboutCell";
    UITableViewCell *cell = 

(UITableViewCell *)[tableView 

dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == 

nil) {
 cell = [[[UITableViewCell alloc] initWithFrame.:CGRectZero 

reuseIdentifier:CellIdentifier] autorelease];
 }
 

cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 

if (index == 0) {
 cell.text = @"About wikiHow App";
 

} else {
 cell.text = @"wikiHow Tips";
 }
 return 

cell;
 }

这样,理解代码时候如果只关注梗概就可以关注- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath,如果需要知道创建Cell的细节就可以看下- (UITableViewCell *)prepareCellForTable: (UITableView *) tableView withRowIndex: (NSUInteger)index。两个不同抽象层次上的函数形成的是一种代码的层次感以 及平衡感。

来源: http://blog.csdn.net/lbj05/archive/2011/04/15/6326681.aspx

原文地址:https://www.cnblogs.com/ranger-jlu/p/3957111.html