ivaneeo's blog

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

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
          運用Extract Method處理上述范例
          面對上代碼,我通常不會以臨時變量來解釋其動作意圖,我更喜歡使用Extract Method(110).讓我們回到起點:
          double price() {
             //price is base price - quantity discount + shipping
             return _quantity * _itemPrice -
                Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
                Math.min(_quantity * _itemPrice * 0.1, 100.0);
          }

          這次我把底價計算提煉到一個獨立函數(shù)中:
          double price() {
             //price is base price - quantity discount + shipping
             return basePrice() -
                Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
                Math.min(basePrice() * 0.1, 100.0);
          }
          private double basePrice() {
             return _quantity * _itemPrice;
          }

          我繼續(xù)我的提煉,每次提煉出一個新函數(shù).最后得到下列代碼:
          double price() {
             //price is base price - quantity discount + shipping
             return basePrice() - quantityDiscount() + shipping();      
          }
          private double quantityDiscount() {
             Math.max(0, _quantity - 500) * _itemPrice * 0.05;
          }
          private double shipping() {
             Math.min(basePrice() * 0.1, 100.0);
          }
          private double basePrice() {
             return _quantity * _itemPrice;
          }


          我比較喜歡使用Extract Method(110),因為同一對象中的任何部分,都可以根據(jù)自己的需要去取用這些提煉出來的函數(shù).一開始我會這些新函數(shù)聲明為private;如果其他對象也需要它們,我可以輕易釋放這些函數(shù)的訪問限制.我還發(fā)現(xiàn),Extract Method(110)的工作量通常并不必Introduce Explaining Variable(124)來得大.

          那么,應(yīng)該在什么時候使用Introduce Explaining Variable(124)呢?答案是:在Extract Method(110)需要花費更大工作量時.如果我要處理的是一個擁有大量局部變量的算法,那么使用Extract Method(110)絕非易事.這種情況下我會使用Introduce Explaining Variable(124)幫助我清理代碼,然后再考慮下一步該怎么辦.搞清楚代碼邏輯之后,我總是可以運用Replace Temp with Query(120)把被我引入的那些解釋性臨時變量去掉.況且,如果我最終使用Replace Method with Method Object(135),那么被我引入的那些解釋性臨時變量也有其價值.
          posted on 2005-08-25 17:07 ivaneeo 閱讀(188) 評論(0)  編輯  收藏 所屬分類: refactoring-從地獄中重生
          主站蜘蛛池模板: 府谷县| 察雅县| 云阳县| 梅州市| 类乌齐县| 梁河县| 固始县| 吴堡县| 奉贤区| 金塔县| 香港 | 宁明县| 南雄市| 凌海市| 台州市| 天等县| 平南县| 资阳市| 宾阳县| 灌阳县| 上饶市| 大庆市| 彰武县| 麦盖提县| 怀来县| 浪卡子县| 湖北省| 孙吴县| 高雄县| 梧州市| 绥芬河市| 永和县| 玉树县| 木兰县| 增城市| 四川省| 海原县| 奉贤区| 花垣县| 营山县| 赤水市|