background image

5

       if  (nAge  >  0 

&& nAge < 200) { 

6

        strRet = [NSString stringWithFormat:@"%d", nAge]; 

7

        if (bWithUnit) { 

8

            strRet = [strRet stringByAppendingString:NDSTR(@"岁")]; 

9

        } 

10

    } 

11

    return strRet; 

12

}

13
14

int getAge(int nBornYear, int nBornMonth, int nBornDay) 

15

16

    int nAge = 0;

17

    int nYear = ServerDate.serverYear; 

18

    int nMonth = ServerDate.serverMonth; 

19

    int nDay = ServerDate.serverDay; 

20

    nAge = nYear - nBornYear - 1; 

21

    if ((nMonth > nBornMonth) || (nMonth == nBornMonth && nDay > nBornDay)) {

22

        ++nAge; 

23

    } 

24

    nAge = MAX(nAge, 0);

25

    return nAge; 

26

}

其中,对内

getAgeTip()调用了 getAge(),对外用户可以根据需要调用 getAgeTip()或者

getAge()。粒度细并合理的情况下,代码的复用性和可读性就大大提供了。但也不能太细了,
这样函数的数目就会

“爆炸”从而影响了代码维护。粒度的拿捏很重要,但却很难,这需要在

实践中慢慢体会。

提取公用的方法以清理重复代码

代码重复是一个比较明显的

“坏味道”,提取公用的方法就是解决的途径之一。iPhone 开发中,

使用

UITableView 的时候就有如下一段“经典”的模板代码,因为这是项目模板自动生成的,

所以很多人就自然接受了。但随着越来越多地通过

copy&paste 在一个项目中使用这段代码,

大家是否有些采取行动的压力呢?好吧,我们就从这

“动刀”吧!

重构前

:

1

(UITableViewCell 

*)tableView:(UITableView 

*)tv 

cellForRowAtIndexPath:

(NSIndexPath *)indexPath {

2

    static NSString *CellIdentifier = @"wikiHowCell"; 

3

 

 

 

 UITableViewCell 

*cell 

(WHTableViewCell 

*)[tv 

dequeueReusableCellWithIdentifier:CellIdentifier]; 

                   找软件资料,就到一览软件文库

http://wk.yl1001.com/rj/