五、重構2:對GetFrequentRenterPoints方法的參數進行重構
重構最重要的思想就是普通程序也能寫出優秀的程序。重構一個項目的巨大工作量就是修改變量名、提取方法、抽取接口、修改方法參數等簡單的工作。作為一個普通的程序就可以通過這些簡單且容易完成的工作目標來提升自己的編碼能力,加深自己對項目的認知,從而為最高層次的重構打下基礎。在這個過程中發現Bug、修改Bug,這不是重構。優化不是重構。強化異常捕捉、增加預防性代碼不是重構。讓代碼更容易測試不是重構——盡管重構能達到相同的效果。這些所有的事都是有益的。但這些都不是重構。
我們觀察 代碼重構與單元測試(一)文章中的共享充電寶計費代碼中,發現Customer類的GetFrequentRenterPoints()方法也需要進行重構,GetFrequentRenterPoints方法有三個參數,這三個參數不是所有參數都是必須的,本文使用重構中的“刪除參數”,對這個方法的參數進行重構。
1.在Visual Studio 2019代碼編輯器中打開Customer.cs文件,找到GetFrequentRenterPoints方法並選中,讓其突出顯示。如下圖。
2. 接下來,執行以下操作之一:
在Visual Studio 2019的菜單欄上選擇“編輯 > 重構 > 刪除參數” 。
在Visual Studio 2019的菜單欄上選擇“編輯 > 重構 > 重新排列參數” 。
3. 在彈出的“更改簽名”對話框中,可以使用右側的按鈕更改方法的參數數量與位置。然后點擊“確定”按鈕。如下圖。
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,代碼如下:
[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的菜單欄上找到“測試-->運行所有測試”菜單項。或者在“測試資源管理器中”選擇 “在視圖中運行所有測試”按鈕, 以運行測試。測試全部通過。如下圖。