5、重構2:對GetFrequentRenterPoints方法的參數進行重構編輯器
重構最重要的思想就是普通程序也能寫出優秀的程序。重構一個項目的巨大工做量就是修改變量名、提取方法、抽取接口、修改方法參數等簡單的工做。做爲一個普通的程序就能夠經過這些簡單且容易完成的工做目標來提高本身的編碼能力,加深本身對項目的認知,從而爲最高層次的重構打下基礎。在這個過程當中發現Bug、修改Bug,這不是重構。優化不是重構。強化異常捕捉、增長預防性代碼不是重構。讓代碼更容易測試不是重構——儘管重構能達到相同的效果。這些全部的事都是有益的。但這些都不是重構。ide
咱們觀察 代碼重構與單元測試(一)文章中的共享充電寶計費代碼中,發現Customer類的GetFrequentRenterPoints()方法也須要進行重構,GetFrequentRenterPoints方法有三個參數,這三個參數不是全部參數都是必須的,本文使用重構中的「刪除參數」,對這個方法的參數進行重構。單元測試
1.在Visual Studio 2019代碼編輯器中打開Customer.cs文件,找到GetFrequentRenterPoints方法並選中,讓其突出顯示。以下圖。 測試
2. 接下來,執行如下操做之一:優化
在Visual Studio 2019的菜單欄上選擇「編輯 > 重構 > 刪除參數」 。編碼
在Visual Studio 2019的菜單欄上選擇「編輯 > 重構 > 從新排列參數」 。3d
3. 在彈出的「更改簽名」對話框中,可使用右側的按鈕更改方法的參數數量與位置。而後點擊「肯定」按鈕。以下圖。blog
4.在進行了方法參數重構以後,GetFrequentRenterPoints方法代碼以下:接口
public int GetFrequentRenterPoints(Rental item, decimal amount) { int frequentRenterPoints = 0; //計算積分 if (item.Power.PriceCode == PowerBank.HighTraffic && item.RentedTime > 4) { frequentRenterPoints += (int)Math.Ceiling(amount * 1.5M); } else frequentRenterPoints += (int)Math.Ceiling(amount); return frequentRenterPoints; }
5. 在Visual Studio 2019中打開測試項目LeasePowerBankTest中的UnitTest1.cs測試類文件,修改測試類中的測試方法ValidGetFrequentRenterPointsTest,代碼以下:ci
[TestMethod] public void ValidGetFrequentRenterPointsTest() { int expected = 5; //建立用戶 var customer = new Customer("張三"); //建立充電寶 PowerBank regularPowerBank = new PowerBank("低-充電寶", PowerBank.LowTraffic); //建立租賃數據 var rental1 = new Rental(regularPowerBank, 5); // Act int actual = customer.GetFrequentRenterPoints(rental1,5); // Assert Assert.AreEqual(expected, actual, 0.001, "積分計算錯誤"); }
6. 在Visual Studio 2019的菜單欄上找到「測試-->運行全部測試」菜單項。或者在「測試資源管理器中」選擇 「在視圖中運行全部測試」按鈕, 以運行測試。測試所有經過。以下圖。
7.在通過上面的重構以後,GetFrequentRenterPoints方法的參數減小到了兩個。如今再仔細品品這個方法的參數,發現方法中的amount參數也不是必須的,也是能夠減小的。繼續進行重構。
8.在Visual Studio 2019代碼編輯器中打開Customer.cs文件,選中GetFrequentRenterPoints方法,讓其突出顯示,而後單擊鼠標右鍵,在彈出的快捷菜單中選擇「快速操做和重構」,會顯示如圖中方框中的菜單,選擇「更改簽名」。以下圖。
9. 在彈出的「更改簽名」對話框中,可使用右側的按鈕更改方法中的參數數量與位置。而後點擊「肯定」按鈕。以下圖。
10.通過上面的重構步驟以後,GetFrequentRenterPoints方法的代碼以下:
public int GetFrequentRenterPoints(Rental item) { int frequentRenterPoints = 0; decimal amount = GetAmount(item); //計算積分 if (item.Power.PriceCode == PowerBank.HighTraffic && item.RentedTime > 4) { frequentRenterPoints += (int)Math.Ceiling(amount * 1.5M); } else frequentRenterPoints += (int)Math.Ceiling(amount); return frequentRenterPoints; }
11.在Visual Studio 2019中打開測試項目LeasePowerBankTest中的UnitTest1.cs測試類文件,修改測試類中的測試方法ValidGetFrequentRenterPointsTest,代碼以下:
[TestMethod] public void ValidGetFrequentRenterPointsTest() { int expected = 5; //建立用戶 var customer = new Customer("張三"); //建立充電寶 PowerBank regularPowerBank = new PowerBank("低-充電寶", PowerBank.LowTraffic); //建立租賃數據 var rental1 = new Rental(regularPowerBank, 5); // Act int actual = customer.GetFrequentRenterPoints(rental1); // Assert Assert.AreEqual(expected, actual, 0.001, "積分計算錯誤"); }
12. 在Visual Studio 2019的菜單欄上找到「測試-->運行全部測試」菜單項。或者在「測試資源管理器中」選擇 「在視圖中運行全部測試」按鈕, 以運行測試。測試所有經過。以下圖。