iPhone 开发重构
提取方法以调整函数粒度
记得刚开始做软件开发的时候,我的导师就在一次函数设计的时候说:
“函数粒度很重要,
但即使我做了接近二十年的软件,有时也无法很好把握粒度。这点就只可意会不可言传了。
”
这句话可能一部分是出自谦虚,但更多是道出软件开发的规律。当时我们无法去理解,现在
开始慢慢理解。我们设计一个函数的时候,可能有时就按需设计了,比如需要获取一个对年
龄的文字提示的时候就设计一个
getAgeTip()的函数,实现代码如下:
重构前:
1
NSString* getAgeTip(int nBornYear, int nBornMonth, int nBornDay)
2
{
3
NSString* strRet = (@"");
4
int nAge = 0;
5
int nYear = ServerDate.serverYear;
6
int nMonth = ServerDate.serverMonth;
7
int nDay = ServerDate.serverDay;
8
nAge = nYear - nBornYear - 1;
9
if ((nMonth > nBornMonth) || (nMonth == nBornMonth && nDay > nBornDay)) {
10
++nAge;
11
}
12
nAge = MAX(nAge, 0);
13
if (nAge > 0 && nAge < 200) {
14
strRet = [NSString stringWithFormat:@"%d", nAge];
15
if (bWithUnit) {
16
strRet = [strRet stringByAppendingString:NDSTR(@"岁")];
17
}
18
}
19
return strRet;
20
}
但随着开发的深入以及需求的变更,可能就会有一个获取年龄的需求。这时候就会发现原来
getAgeTip()函数中就有获取年龄的逻辑,粒度太大了,无法实现复用。面对这种问题的时候
就需要重新调整函数粒度,通过提取
getAge()方法后重构代码如下:
重构后:
1
NSString* getAgeTip(int nBornYear, int nBornMonth, int nBornDay)
2
{
3
NSString* strRet = (@"");
4
int nAge = getAge(nBornYear, nBornMonth, nBornDay);
找软件资料,就到一览软件文库