ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
范例(Examples)
我从下列这段简单代码开始:
int discount(int inputVal, int quantity, int yearToDate) {
    if(inputVal > 50) inputVal -= 2;
    if(quantity > 100) inputVal -= 1;
    if(yearToDate > 1000) inputVal -= 4;
    return inputVal;
}
以临时变量取代对参数的赋值动作,得到下列代码:
 int discount(int inputVal, int quantity, int yearToDate) {
    int result = inputVal;
    if(inputVal > 50)
result -= 2;
    if(quantity > 100) result -= 1;
    if(yearToDate > 1000) result -= 4;
    return result
}
还可以为参数加上关键词final,从而强制它遵循[不对参数赋值]这一惯例:
  int discount(final int inputVal, final int quantity, final int yearToDate) {
    int result = inputVal;
    if(inputVal > 50)
result -= 2;
    if(quantity > 100) result -= 1;
    if(yearToDate > 1000) result -= 4;
    return result
}

不过我的承认,我并不经常使用final来修饰参数,因为我发现,对于提高短函数的清晰度,这个办法并无太大帮助。我通常会在较长的函数中使用它,让它帮助我检查参数是否被做了修改。
posted on 2005-08-29 15:40 ivaneeo 阅读(196) 评论(0)  编辑  收藏 所属分类: refactoring-从地狱中重生

只有注册用户登录后才能发表评论。


网站导航: