Introduce Explaining Variable (引入解釋性變量)

Summary:

將一個複雜表達式(或其中一部分)的結果放進一個臨時變量,以此變量名稱來解釋表達式用途。 java

Motivation:

表達式有可能很是複雜而難以閱讀。這種狀況下,臨時變量能夠幫助你將表達式分解爲比較容易的管理形式。 算法

Mechanics:

1. 聲明一個final臨時變量,將待分解之複雜表達式中的一部分動做的運算結果賦值給它。 函數

2.將表達式中的「運算結果」這一部分,替換爲上述臨時變量。 測試

  •     若是被替換的這一部分在代碼中重複出現,能夠每次一個,逐一替換

3.編譯,測試。 spa

4.重複上述過程,處理表達式的其餘部分。 code

範例:

從一個簡單的計算開始: 對象

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 );
    }
  這段代碼不算複雜,不過咱們可讓它變得更容易理解。首先,底價(basePrice)等於數量(quantity)乘以單價(itemPrice)。咱們把這一部分的結果放進一個臨時變量中:
double price1(){
      //price is base price - quantity discount + shipping
        final double basePrice = _quantity * _itemPrice;
        return basePrice - 
               Math.max( 0, _quantity - 500 ) * _itemPrice * 0.05 +
               Math.min( _quantity * _itemPrice * 0.1, 100.0 );
    }
後面也用到了「數量乘以單價」 運算結果,因此咱們一樣將它替換爲basePrice:
double price(){
      //price is base price - quantity discount + shipping
        final double basePrice = _quantity * _itemPrice;
        return basePrice - 
               Math.max( 0, _quantity - 500 ) * _itemPrice * 0.05 +
               Math.min(basePrice * 0.1, 100.0 );
    }
而後,將批發折扣(quantityDiscount)的計算提煉出來,將結果賦予臨時變量
double price()
    {
        //price is base price - quantity discount + shipping
        final double basePrice = _quantity * _itemPrice;
        final double quantityDiscount = 
                        Math.max( 0, _quantity - 500 ) * _itemPrice * 0.05;
        return basePrice - quantityDiscount + 
               Math.min( _quantity * _itemPrice * 0.1, 100.0 );
    }

最後,再把運費(shipping)計算出來,將運算結果賦予臨時變量shipping。同時仍是能夠刪掉代碼中的註釋,由於如今代碼已經能夠完美表達本身的意義了: ip

double price()
    {
        final double basePrice = _quantity * _itemPrice;
        final double quantityDiscount = 
                        Math.max( 0, _quantity - 500 ) * _itemPrice * 0.05;
        final double shipping = Math.min( basePrice * 0.1, 100.0 );
        return basePrice - quantityDiscount + shipping;
    }

Introduce Explaining Variable 是一個常見的重構手法,可是Extract Method 也能夠用來解釋一段代碼的意義,畢竟臨時變量只在它所處的那個函數中才有意義,侷限性較大,函數則能夠在對象的整個生命中都有用,而且能夠被其餘對象使用。那麼應該在何時使用Introduce Explaining Variable呢?答案是:在Extract Method 須要花費更大的工做量時。若是要要處理的是一個擁有大量局部變量的算法,那麼使用Extract Method絕非易事。這種狀況下就會使用Introduce Explaining Variable 來清理代碼,而後再考慮下一步該怎麼辦。搞清楚代碼邏輯以後,老是能夠運用Replace Temp with Query 把中間引入的那些解釋性臨時變量去掉。何況,若是最終使用Replace Method with Method Object,那麼中間引入的那些解釋性變量也有其價值。 it

相關文章
相關標籤/搜索