ivaneeo's blog

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

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks

          范例(Examples)
          首先,我從一個簡單函數(shù)開始:
          double getPrice() {
             int basePrice = _quantity * _itemPrice;
             double discountFactor;
             if(basePrice > 1000) discountFactor = 0.95;
             else   discountFactor = 0.98;
             return basePrice * discountFactor;
          }

          我希望將兩個臨時變量都替換掉.當(dāng)然,每次一個.

          盡管這里的代碼十分清楚,我還是先把臨時變量聲明為final,檢查它們是否的確只被賦值一次:
          double getPrice() {
             final int basePrice = _quantity * _itemPrice;
             final double discountFactor;
             if(basePrice > 1000) discountFactor = 0.95;
             else   discountFactor = 0.98;
             return basePrice * discountFactor;
          }

          這么一來,如果有任何問題,編譯器就會警告我.之所以先做這件事,因為如果臨時變量不知被賦值一次,我就不該進(jìn)行這項重構(gòu).接下來我開始替換臨時變量,每次一個.首先我把賦值(assignment)動作的右側(cè)表達(dá)式提煉出來:
          double getPrice() {
             final int basePrice = basePrice();
             final double discountFactor;
             if(basePrice > 1000) discountFactor = 0.95;
             else   discountFactor = 0.98;
             return basePrice * discountFactor;
          }
          private int basePrice() {
             return _quantity * _itemPrice;
          }

          編譯并測試,然后開始使用Inline Temp(119).首先把臨時變量basePrice的第一個引用點替換掉:
          double getPrice() {
             final int basePrice = basePrice();
             final double discountFactor;
             if(basePrice() > 1000) discountFactor = 0.95;
             else   discountFactor = 0.98;
             return basePrice * discountFactor;
          }


          編譯,測試,下一個.由于[下一個]已經(jīng)是basePrice的最后一個引用點,所以我把basePrice臨時變量的聲明式一并摘除:
          double getPrice() {
             final double discountFactor;
             if(basePrice() > 1000) discountFactor = 0.95;
             else   discountFactor = 0.98;
             return basePrice() * discountFactor;
          }


          搞定basePrice之后,我再以類似辦法提煉出一個discountFactor():
          double getPrice() {
             final double discountFactor = discountFactor();
                return basePrice() * discountFactor;
          }
          private double discountFactor() {
             if(basePrice() > 1000) return 0.95;
             else   return 0.98;
          }

          你看,如果我沒有把臨時變量basePrice替換為一個查詢式,將多么難以提煉discountFactor()!

          最終,getPrice()變成了這樣:
          double getPrice() {
                return basePrice() * discountFactor();
          }

          posted on 2005-08-25 15:14 ivaneeo 閱讀(257) 評論(0)  編輯  收藏 所屬分類: refactoring-從地獄中重生
          主站蜘蛛池模板: 马尔康县| 扎赉特旗| 高雄县| 仲巴县| 平谷区| 正定县| 甘孜| 刚察县| 广南县| 乐亭县| 柘城县| 连南| 苏尼特右旗| 竹溪县| 固安县| 汝南县| 监利县| 南平市| 闽侯县| 多伦县| 樟树市| 临颍县| 郎溪县| 郯城县| 雷波县| 常山县| 普陀区| 玉环县| 若尔盖县| 平阳县| 靖州| 晋江市| 桑日县| 怀宁县| 古蔺县| 康平县| 邓州市| 桑植县| 汉阴县| 花莲县| 邵阳县|