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的菜单栏上找到“测试-->运行全部测试”菜单项。或者在“测试资源管理器中”选择 “在视图中运行全部测试”按钮, 以运行测试。测试所有经过。以下图。