简介

重构是持续改进代码的基础。抵制重构将带来技术麻烦:忘记代码片段的功能、创建无法测试的代码等等。

而有了重构,使用单元测试、共享代码以及更可靠的无bug 的代码这些最佳实践就显得简单多了。

鉴于重构的重要性,我决定在整个8 月份每天介绍一个重构。在开始之前,请允许我事先声明,尽管我试着对每个重构进行额外的描述和讨论,但我并不是在声明它们的所有权。

我介绍的大多数重构都可以在Refactoring.com 中找到,有一些来自《代码大全(第2 版)》,剩下的则是我自己经常使用或从其他网站找到的。我觉得注明每个重构的出处并不是重要的,因为你可以在网上不同的帖子或文章中找到名称类似的重构。

本着这一精神,我将在明天发布第一篇帖子并开始长达31天的重构马拉松之旅。希望你们能够享受重构并从中获益。

代码重构第1天:封装集合

在某些场景中,向类的使用者隐藏类中的完整集合是一个很好的做法,比如对集合的add/remove操作中包含其他的相关逻辑时。因此,以可迭代但不直接在集合上进行操作的方式来暴露集合,是个不错的主意。我们来看代码:

  1. public class Order
  2. {
  3. private int _orderTotal;
  4. private List<OrderLine> _orderLines;
  5. public IEnumerable<OrderLine> OrderLines
  6. {
  7. get { return _orderLines; }
  8. }
  9. public void AddOrderLine(OrderLine orderLine)
  10. {
  11. _orderTotal += orderLine.Total;
  12. _orderLines.Add(orderLine);
  13. }
  14. public void RemoveOrderLine(OrderLine orderLine)
  15. {
  16. orderLine = _orderLines.Find(o => o == orderLine);
  17. if (orderLine == null) return;
  18. _orderTotal -= orderLine.Total;
  19. _orderLines.Remove(orderLine);
  20. }
  21. }

如你所见,我们对集合进行了封装,没有将Add/Remove 方法暴露给类的使用者。在.NET Framework中,有些类如ReadOnlyCollection,会由于封装集合而产生不同的行为,但它们各自都有防止误解的说明。这是一个非常简单但却极具价值的重构,可以确保用户不会误用你暴露的集合,避免代码中的一些bug。

代码重构第2天:移动方法

今天的重构同样非常简单,以至于人们并不认为这是一个有价值的重构。迁移方法(Move Method),顾名思义就是将方法迁移到合适的位置。在开始重构前,我们先看看一下代码:

  1. public class BankAccount
  2. {
  3. public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
  4. {
  5. AccountAge = accountAge;
  6. CreditScore = creditScore;
  7. AccountInterest = accountInterest;
  8. }
  9. public int AccountAge { get; private set; }
  10. public int CreditScore { get; private set; }
  11. public AccountInterest AccountInterest { get; private set; }
  12. public double CalculateInterestRate()
  13. {
  14. if (CreditScore > 800)
  15. return 0.02;
  16. if (AccountAge > 10)
  17. return 0.03;
  18. return 0.05;
  19. }
  20. }
  1. public class AccountInterest
  2. {
  3. public BankAccount Account { get; private set; }
  4. public AccountInterest(BankAccount account)
  5. {
  6. Account = account;
  7. }
  8. public double InterestRate
  9. {
  10. get { return Account.CalculateInterestRate(); }
  11. }
  12. public bool IntroductoryRate
  13. {
  14. get { return Account.CalculateInterestRate() < 0.05; }
  15. }
  16. }

这里值得注意的是BankAccount.CalculateInterest 方法。当一个方法被其他类使用比在它所在类中的使用还要频繁时,我们就需要使用迁移方法重构了——将方法迁移到更频繁地使用它的类中。由于依赖关系,该重构并不能应用于所有实例,但人们还是经常低估它的价值。

最终的代码应该是这样的:

  1. public class BankAccount
  2. {
  3. public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
  4. {
  5. AccountAge = accountAge;
  6. CreditScore = creditScore;
  7. AccountInterest = accountInterest;
  8. }
  9. public int AccountAge { get; private set; }
  10. public int CreditScore { get; private set; }
  11. public AccountInterest AccountInterest { get; private set; }
  12. }
  1. public class AccountInterest
  2. {
  3. public BankAccount Account { get; private set; }
  4. public AccountInterest(BankAccount account)
  5. {
  6. Account = account;
  7. }
  8. public double InterestRate
  9. {
  10. get { return CalculateInterestRate(); }
  11. }
  12. public bool IntroductoryRate
  13. {
  14. get { return CalculateInterestRate() < 0.05; }
  15. }
  16. public double CalculateInterestRate()
  17. {
  18. if (Account.CreditScore > 800)
  19. return 0.02;
  20. if (Account.AccountAge > 10)
  21. return 0.03;
  22. return 0.05;
  23. }
  24. }

够简单吧?

代码重构第3天:提升方法

提升方法(Pull Up Method)重构是将方法向继承链上层迁移的过程。用于一个方法被多个实现者使用时。

  1. public abstract class Vehicle
  2. {
  3. // other methods
  4. }
  5. public class Car : Vehicle
  6. {
  7. public void Turn(Direction direction)
  8. {
  9. // code here
  10. }
  11. }
  12. public class Motorcycle : Vehicle
  13. {
  14. }
  15. public enum Direction
  16. {
  17. Left,
  18. Right
  19. }

如你所见,目前只有Car类中包含Turn方法,但我们也希望在Motorcycle 类中使用。因此,如果没有基类,我们就创建一个基类并将该方法“上移”到基类中,这样两个类就都可以使用Turn 方法了。这样做唯一的缺点是扩充了基类的接口、增加了其复杂性,因此需谨慎使用。只有当一个以上的子类需要使用该方法时才需要进行迁移。如果滥用继承,系统将会很快崩溃。这时你应该使用组合代替继承。重构之后的代码如下:

  1. public abstract class Vehicle
  2. {
  3. public void Turn(Direction direction)
  4. {
  5. // code here
  6. }
  7. }
  8. public class Car : Vehicle
  9. {
  10. }
  11. public class Motorcycle : Vehicle
  12. {
  13. }
  14. public enum Direction
  15. {
  16. Left,
  17. Right
  18. }

代码重构第4天:降低方法

昨天我们介绍了将方法迁移到基类以供多个子类使用的上移方法重构,今天我们来看看相反的操作。重构前的代码如下:

  1. public abstract class Animal
  2. {
  3. public void Bark()
  4. {
  5. // code to bark
  6. }
  7. }
  8. public class Dog : Animal
  9. {
  10. }
  11. public class Cat : Animal
  12. {
  13. }

这里的基类有一个Bark方法。或许我们的猫咪们一时半会也没法学会汪汪叫(bark),因此Cat 类中不再需要这个功能了。尽管基类不需要这个方法,但在显式处理Dog 类时也许还需要,因此我们将Bark 方法“降低”到Dog 类中。这时,有必要评估Animal基类中是否还有其他行为。如果没有,则是一个将Animal抽象类转换成接口的好时机。因为契约中不需要任何代码,可以认为是一个标记接口。

  1. public abstract class Animal
  2. {
  3. }
  4. public class Dog : Animal
  5. {
  6. public void Bark()
  7. {
  8. // code to bark
  9. }
  10. }
  11. public class Cat : Animal
  12. {
  13. }

代码重构第5天:提升字段

今天我们来看看一个和提升方法十分类似的重构。不过今天我们处理的不是方法,而是字段。

  1. public abstract class Account
  2. {
  3. }
  4. public class CheckingAccount : Account
  5. {
  6. private decimal _minimumCheckingBalance = 5m;
  7. }
  8. public class SavingsAccount : Account
  9. {
  10. private decimal _minimumSavingsBalance = 5m;
  11. }

在这个例子中,两个子类中包含重复的常量。为了提高复用性我们将字段上移到基类中,并简化其名称。

  1. public abstract class Account
  2. {
  3. protected decimal _minimumBalance = 5m;
  4. }
  5. public class CheckingAccount : Account
  6. {
  7. }
  8. public class SavingsAccount : Account
  9. {
  10. }

重构代码第6天:降低字段

与提升字段相反的重构是降低字段。同样,这也是一个无需多言的简单重构。

  1. public abstract class Task
  2. {
  3. protected string _resolution;
  4. }
  5. public class BugTask : Task
  6. {
  7. }
  8. public class FeatureTask : Task
  9. {
  10. }

在这个例子中,基类中的一个字符串字段只被一个子类使用,因此可以进行下移。只要没有其他子类使用基类的字段时,就应该立即执行该重构。保留的时间越长,就越有可能不去重构而保持原样。

  1. public abstract class Task
  2. {
  3. }
  4. public class BugTask : Task
  5. {
  6. private string _resolution;
  7. }
  8. public class FeatureTask : Task
  9. {
  10. }

重构代码第7天:重命名(方法,类,参数)

这是我最常用也是最有用的重构之一。我们对方法/类/参数的命名往往不那么合适,以至于误导阅读者对于方法/类/参数功能的理解。这会造成阅读者的主观臆断,甚至引入bug。这个重构看起来简单,但却十分重要。

  1. public class Person
  2. {
  3. public string FN { get; set; }
  4. public decimal ClcHrlyPR()
  5. {
  6. // code to calculate hourly payrate
  7. return 0m;
  8. }
  9. }

如你所见,我们的类/方法/参数的名称十分晦涩难懂,可以理解为不同的含义。应用这个重构你只需随手将
名称修改得更具描述性、更容易传达其含义即可。简单吧。

  1. // Changed the class name to Employee
  2. public class Employee
  3. {
  4. public string FirstName { get; set; }
  5. public decimal CalculateHourlyPay()
  6. {
  7. // code to calculate hourly payrate
  8. return 0m;
  9. }
  10. }

重构代码第8天:使用委派代替继承

继承的误用十分普遍。它只能用于逻辑环境,但却经常用于简化,这导致复杂的没有意义的继承层次。看下面的代码:

  1. public class Sanitation
  2. {
  3. public string WashHands()
  4. {
  5. return "Cleaned!";
  6. }
  7. }
  8. public class Child : Sanitation
  9. {
  10. }

在该例中,Child 并不是Sanitation,因此这样的继承层次是毫无意义的。我们可以这样重构:在Child 的构造函数里实现一个Sanitation实例,并将方法的调用委托给这个实例。如果你使用依赖注入,可以通过构造函数传递Sanitation实例,尽管在我看来还要向IoC容器注册模型是一种坏味道,但领会精神就可以了。继承只能用于严格的继承场景,并不是用来快速编写代码的工具。

  1. public class Sanitation
  2. {
  3. public string WashHands()
  4. {
  5. return "Cleaned!";
  6. }
  7. }
  8. public class Child
  9. {
  10. private Sanitation Sanitation { get; set; }
  11. public Child()
  12. {
  13. Sanitation = new Sanitation();
  14. }
  15. public string WashHands()
  16. {
  17. return Sanitation.WashHands();
  18. }
  19. }

代码重构第9天:提取接口

今天我们来介绍一个常常被忽视的重构:提取接口。如果你发现多于一个类使用另外一个类的某些方法,引入接口解除这种依赖往往十分有用。该重构实现起来非常简单,并且能够享受到松耦合带来的好处。

  1. public class ClassRegistration
  2. {
  3. public void Create()
  4. {
  5. // create registration code
  6. }
  7. public void Transfer()
  8. {
  9. // class transfer code
  10. }
  11. public decimal Total { get; private set; }
  12. }
  13. public class RegistrationProcessor
  14. {
  15. public decimal ProcessRegistration(ClassRegistration registration)
  16. {
  17. registration.Create();
  18. return registration.Total;
  19. }
  20. }

在下面的代码中,你可以看到我提取出了消费者所使用的两个方法,并将其置于一个接口中。现在消费者不必关心和了解实现了这些方法的类。我们解除了消费者与实际实现之间的耦合,使其只依赖于我们创建的契约。

  1. public interface IClassRegistration
  2. {
  3. void Create();
  4. decimal Total { get; }
  5. }
  6. public class ClassRegistration : IClassRegistration
  7. {
  8. public void Create()
  9. {
  10. // create registration code
  11. }
  12. public void Transfer()
  13. {
  14. // class transfer code
  15. }
  16. public decimal Total { get; private set; }
  17. }
  18. public class RegistrationProcessor
  19. {
  20. public decimal ProcessRegistration(IClassRegistration registration)
  21. {
  22. registration.Create();
  23. return registration.Total;
  24. }
  25. }

代码重构第10天:提取方法

今天我们要介绍的重构是提取方法。这个重构极其简单但却大有裨益。首先,将逻辑置于命名良好的方法内有助于提高代码的可读性。当方法的名称可以很好地描述这部分代码的功能时,可以有效地减少其他开发者的研究时间。假设越少,代码中的bug 也就越少。重构之前的代码如下:

  1. public class Receipt
  2. {
  3. private IList<decimal> Discounts { get; set; }
  4. private IList<decimal> ItemTotals { get; set; }
  5. public decimal CalculateGrandTotal()
  6. {
  7. decimal subTotal = 0m;
  8. foreach (decimal itemTotal in ItemTotals)
  9. subTotal += itemTotal;
  10. if (Discounts.Count > 0)
  11. {
  12. foreach (decimal discount in Discounts)
  13. subTotal -= discount;
  14. }
  15. decimal tax = subTotal * 0.065m;
  16. subTotal += tax;
  17. return subTotal;
  18. }
  19. }

你会发现CalculateGrandTotal方法一共做了3件不同的事情:计算总额、折扣和发票税额。开发者为了搞清楚每个功能如何处理而不得不将代码从头看到尾。相比于此,向下面的代码那样将每个任务分解成单独的方法则要节省更多时间,也更具可读性:

  1. public class Receipt
  2. {
  3. private IList<decimal> Discounts { get; set; }
  4. private IList<decimal> ItemTotals { get; set; }
  5. public decimal CalculateGrandTotal()
  6. {
  7. decimal subTotal = CalculateSubTotal();
  8. subTotal = CalculateDiscounts(subTotal);
  9. subTotal = CalculateTax(subTotal);
  10. return subTotal;
  11. }
  12. private decimal CalculateTax(decimal subTotal)
  13. {
  14. decimal tax = subTotal * 0.065m;
  15. subTotal += tax;
  16. return subTotal;
  17. }
  18. private decimal CalculateDiscounts(decimal subTotal)
  19. {
  20. if (Discounts.Count > 0)
  21. {
  22. foreach (decimal discount in Discounts)
  23. subTotal -= discount;
  24. }
  25. return subTotal;
  26. }
  27. private decimal CalculateSubTotal()
  28. {
  29. decimal subTotal = 0m;
  30. foreach (decimal itemTotal in ItemTotals)
  31. subTotal += itemTotal;
  32. return subTotal;
  33. }
  34. }

代码重构第11天:使用策略类

今天的重构没有固定的形式,多年来我使用过不同的版本,并且我敢打赌不同的人也会有不同的版本。该重构适用于这样的场景:switch 语句块很大,并且会随时引入新的判断条件。这时,最好使用策略模式将每个条件封装到单独的类中。实现策略模式的方式是很多的。我在这里介绍的策略重构使用的是字典策略,这么做的好处是调用者不必修改原来的代码。

  1. namespace LosTechies.DaysOfRefactoring.SwitchToStrategy.Before
  2. {
  3. public class ClientCode
  4. {
  5. public decimal CalculateShipping()
  6. {
  7. ShippingInfo shippingInfo = new ShippingInfo();
  8. return shippingInfo.CalculateShippingAmount(State.Alaska);
  9. }
  10. }
  11. public enum State
  12. {
  13. Alaska,
  14. NewYork,
  15. Florida
  16. }
  17. public class ShippingInfo
  18. {
  19. public decimal CalculateShippingAmount(State shipToState)
  20. {
  21. switch (shipToState)
  22. {
  23. case State.Alaska:
  24. return GetAlaskaShippingAmount();
  25. case State.NewYork:
  26. return GetNewYorkShippingAmount();
  27. case State.Florida:
  28. return GetFloridaShippingAmount();
  29. default:
  30. return 0m;
  31. }
  32. }
  33. private decimal GetAlaskaShippingAmount()
  34. {
  35. return 15m;
  36. }
  37. private decimal GetNewYorkShippingAmount()
  38. {
  39. return 10m;
  40. }
  41. private decimal GetFloridaShippingAmount()
  42. {
  43. return 3m;
  44. }
  45. }
  46. }

要应用该重构,需将每个测试条件至于单独的类中,这些类实现了一个共同的接口。然后将枚举作为字典的键,这样就可以获取正确的实现,并执行其代码了。以后如果希望添加新的条件,只需添加新的实现类,并将其添加至ShippingCalculations 字典中。正如前面说过的,这不是实现策略模式的唯一方式。我在这里将字体加粗显示,是因为肯定会有人在评论里指出这点:)用你觉得好用的方法。我用这种方式实现重构的好处是,不用修改客户端代码。所有的修改都在ShippingInfo 类内部。
Jayme Davis指出这种重构由于仍然需要在构造函数中进行绑定,所以只不过是增加了一些类而已,但如果绑定IShippingCalculation的策略可以置于IoC中,带来的好处还是很多的,它可以使你更灵活地捆绑策略。

  1. namespace LosTechies.DaysOfRefactoring.SwitchToStrategy.After
  2. {
  3. public class ClientCode
  4. {
  5. public decimal CalculateShipping()
  6. {
  7. ShippingInfo shippingInfo = new ShippingInfo();
  8. return shippingInfo.CalculateShippingAmount(State.Alaska);
  9. }
  10. }
  11. public enum State
  12. {
  13. Alaska,
  14. NewYork,
  15. Florida
  16. }
  17. public class ShippingInfo
  18. {
  19. private IDictionary<State, IShippingCalculation> ShippingCalculations
  20. { get; set; }
  21. public ShippingInfo()
  22. {
  23. ShippingCalculations = new Dictionary<State, IShippingCalculation>
  24. {
  25. { State.Alaska, new AlaskShippingCalculation() },
  26. { State.NewYork, new NewYorkShippingCalculation() },
  27. { State.Florida, new FloridaShippingCalculation() }
  28. };
  29. }
  30. public decimal CalculateShippingAmount(State shipToState)
  31. {
  32. return ShippingCalculations[shipToState].Calculate();
  33. }
  34. }
  35. public interface IShippingCalculation
  36. {
  37. decimal Calculate();
  38. }
  39. public class AlaskShippingCalculation : IShippingCalculation
  40. {
  41. public decimal Calculate()
  42. {
  43. return 15m;
  44. }
  45. }
  46. public class NewYorkShippingCalculation : IShippingCalculation
  47. {
  48. public decimal Calculate()
  49. {
  50. return 10m;
  51. }
  52. }
  53. public class FloridaShippingCalculation : IShippingCalculation
  54. {
  55. public decimal Calculate()
  56. {
  57. return 3m;
  58. }
  59. }
  60. }

为了使这个示例圆满,我们来看看在ShippingInfo 构造函数中使用Ninject 为IoC容器时如何进行绑定。需要更改的地方很多,主要是将state 的枚举放在策略内部,以及Ninject 向构造函数传递一个IShippingInfo 的IEnumerable泛型。接下来我们使用策略类中的state属性创建字典,其余部分保持不变。(感谢Nate Kohari和Jayme Davis)

  1. public interface IShippingInfo
  2. {
  3. decimal CalculateShippingAmount(State state);
  4. }
  5. public class ClientCode
  6. {
  7. [Inject]
  8. public IShippingInfo ShippingInfo { get; set; }
  9. public decimal CalculateShipping()
  10. {
  11. return ShippingInfo.CalculateShippingAmount(State.Alaska);
  12. }
  13. }
  14. public enum State
  15. {
  16. Alaska,
  17. NewYork,
  18. Florida
  19. }
  20. public class ShippingInfo : IShippingInfo
  21. {
  22. private IDictionary<State, IShippingCalculation> ShippingCalculations
  23. { get; set; }
  24. public ShippingInfo(IEnumerable<IShippingCalculation> shippingCalculations)
  25. {
  26. ShippingCalculations = shippingCalculations.ToDictionary(
  27. calc => calc.State);
  28. }
  29. public decimal CalculateShippingAmount(State shipToState)
  30. {
  31. return ShippingCalculations[shipToState].Calculate();
  32. }
  33. }
  34. public interface IShippingCalculation
  35. {
  36. State State { get; }
  37. decimal Calculate();
  38. }
  39. public class AlaskShippingCalculation : IShippingCalculation
  40. {
  41. public State State { get { return State.Alaska; } }
  42. public decimal Calculate()
  43. {
  44. return 15m;
  45. }
  46. }
  47. public class NewYorkShippingCalculation : IShippingCalculation
  48. {
  49. public State State { get { return State.NewYork; } }
  50. public decimal Calculate()
  51. {
  52. return 10m;
  53. }
  54. }
  55. public class FloridaShippingCalculation : IShippingCalculation
  56. {
  57. public State State { get { return State.Florida; } }
  58. public decimal Calculate()
  59. {
  60. return 3m;
  61. }
  62. }

代码重构第12天:分解依赖

有些单元测试需要恰当的测试“缝隙”(test seam)来模拟/隔离一些不想被测试的部分。如果你正想在代码中引入这种单元测试,那么今天介绍的重构就十分有用。在这个例子中,我们的客户端代码使用一个静态类来实现功能。但当需要单元测试时,问题就来了。我们无法在单元测试中模拟静态类。解决的方法是使用一个接口将静态类包装起来,形成一个缝隙来切断与静态类之间的依赖。

  1. public class AnimalFeedingService
  2. {
  3. private bool FoodBowlEmpty { get; set; }
  4. public void Feed()
  5. {
  6. if (FoodBowlEmpty)
  7. Feeder.ReplenishFood();
  8. // more code to feed the animal
  9. }
  10. }
  11. public static class Feeder
  12. {
  13. public static void ReplenishFood()
  14. {
  15. // fill up bowl
  16. }
  17. }

重构时我们所要做的就是引入一个接口和简单调用上面那个静态类的类。因此行为还是一样的,只是调用的方式产生了变化。这是一个不错的重构起始点,也是向代码添加单元测试的简单方式。

  1. public class AnimalFeedingService
  2. {
  3. public IFeederService FeederService { get; set; }
  4. public AnimalFeedingService(IFeederService feederService)
  5. {
  6. FeederService = feederService;
  7. }
  8. private bool FoodBowlEmpty { get; set; }
  9. public void Feed()
  10. {
  11. if (FoodBowlEmpty)
  12. FeederService.ReplenishFood();
  13. // more code to feed the animal
  14. }
  15. }
  16. public interface IFeederService
  17. {
  18. void ReplenishFood();
  19. }
  20. public class FeederService : IFeederService
  21. {
  22. public void ReplenishFood()
  23. {
  24. Feeder.ReplenishFood();
  25. }
  26. }
  27. public static class Feeder
  28. {
  29. public static void ReplenishFood()
  30. {
  31. // fill up bowl
  32. }
  33. }

现在,我们可以在单元测试中将模拟的IFeederService 传入AnimalFeedingService 构造函数。测试成功后,我们可以将静态方法中的代码移植到FeederService 类中,并删除静态类。

代码重构第13天:提取方法对象

今天的重构来自于Martin Fowler的重构目录。在我看来,这是一个比较罕见的重构,但有时却终能派上用场。当你尝试进行提取方法的重构时,需要引入大量的方法。在一个方法中使用众多的本地变量有时会使代码变得丑陋。因此最好使用提取方法对象这个重构,将执行任务的逻辑分开。

  1. public class OrderLineItem
  2. {
  3. public decimal Price { get; private set; }
  4. }
  5. public class Order
  6. {
  7. private IList<OrderLineItem> OrderLineItems { get; set; }
  8. private IList<decimal> Discounts { get; set; }
  9. private decimal Tax { get; set; }
  10. public decimal Calculate()
  11. {
  12. decimal subTotal = 0m;
  13. // Total up line items
  14. foreach (OrderLineItem lineItem in OrderLineItems)
  15. {
  16. subTotal += lineItem.Price;
  17. }
  18. // Subtract Discounts
  19. foreach (decimal discount in Discounts)
  20. subTotal -= discount;
  21. // Calculate Tax
  22. decimal tax = subTotal * Tax;
  23. // Calculate GrandTotal
  24. decimal grandTotal = subTotal + tax;
  25. return grandTotal;
  26. }
  27. }

我们通过构造函数,将返回计算结果的类的引用传递给包含多个计算方法的新建对象,或者向方法对象的构造函数中单独传递各个参数。如下面的代码:

  1. public class OrderLineItem
  2. {
  3. public decimal Price { get; private set; }
  4. }
  5. public class Order
  6. {
  7. public IEnumerable<OrderLineItem> OrderLineItems { get; private set; }
  8. public IEnumerable<decimal> Discounts { get; private set; }
  9. public decimal Tax { get; private set; }
  10. public decimal Calculate()
  11. {
  12. return new OrderCalculator(this).Calculate();
  13. }
  14. }
  15. public class OrderCalculator
  16. {
  17. private decimal SubTotal { get; set; }
  18. private IEnumerable<OrderLineItem> OrderLineItems { get; set; }
  19. private IEnumerable<decimal> Discounts { get; set; }
  20. private decimal Tax { get; set; }
  21. public OrderCalculator(Order order)
  22. {
  23. OrderLineItems = order.OrderLineItems;
  24. Discounts = order.Discounts;
  25. Tax = order.Tax;
  26. }
  27. public decimal Calculate()
  28. {
  29. CalculateSubTotal();
  30. SubtractDiscounts();
  31. CalculateTax();
  32. return SubTotal;
  33. }
  34. private void CalculateSubTotal()
  35. {
  36. // Total up line items
  37. foreach (OrderLineItem lineItem in OrderLineItems)
  38. SubTotal += lineItem.Price;
  39. }
  40. private void SubtractDiscounts()
  41. {
  42. // Subtract Discounts
  43. foreach (decimal discount in Discounts)
  44. SubTotal -= discount;
  45. }
  46. private void CalculateTax()
  47. {
  48. // Calculate Tax
  49. SubTotal += SubTotal * Tax;
  50. }
  51. }

代码重构第14天:分离职责

把一个类的多个职责进行拆分,这贯彻了SOLID 中的单一职责原则(SRP)。尽管对于如何划分“职责”经常存在争论,但应用这项重构还是十分简单的。我这里并不会回答划分职责的问题,只是演示一个结构清晰的示例,将类划分为多个负责具体职责的类。

  1. public class Video
  2. {
  3. public void PayFee(decimal fee)
  4. {
  5. }
  6. public void RentVideo(Video video, Customer customer)
  7. {
  8. customer.Videos.Add(video);
  9. }
  10. public decimal CalculateBalance(Customer customer)
  11. {
  12. return customer.LateFees.Sum();
  13. }
  14. }
  15. public class Customer
  16. {
  17. public IList<decimal> LateFees { get; set; }
  18. public IList<Video> Videos { get; set; }
  19. }

如你所见,Video类包含两个职责,一个负责处理录像租赁,另一个负责管理管理用户的租赁总数。要分离职责,我们可以将用户的逻辑转移到用户类中。

  1. public class Video
  2. {
  3. public void RentVideo(Video video, Customer customer)
  4. {
  5. customer.Videos.Add(video);
  6. }
  7. }
  8. public class Customer
  9. {
  10. public IList<decimal> LateFees { get; set; }
  11. public IList<Video> Videos { get; set; }
  12. public void PayFee(decimal fee)
  13. {
  14. }
  15. public decimal CalculateBalance(Customer customer)
  16. {
  17. return customer.LateFees.Sum();
  18. }
  19. }

代码重构第15天:移除重复内容

这大概是处理一个方法在多处使用时最常见的重构。如果不加以注意的话,你会慢慢地养成重复的习惯。开发者常常由于懒惰或者在想要尽快生成尽可能多的代码时,向代码中添加很多重复的内容。我想也没必要过多解释了吧,直接看代码把。

  1. public class MedicalRecord
  2. {
  3. public DateTime DateArchived { get; private set; }
  4. public bool Archived { get; private set; }
  5. public void ArchiveRecord()
  6. {
  7. Archived = true;
  8. DateArchived = DateTime.Now;
  9. }
  10. public void CloseRecord()
  11. {
  12. Archived = true;
  13. DateArchived = DateTime.Now;
  14. }
  15. }

我们用共享方法的方式来删除重复的代码。看!没有重复了吧?请务必在必要的时候执行这项重构。它能有效地减少bug,因为你不会将有bug的代码复制/粘贴到各个角落。

  1. public class MedicalRecord
  2. {
  3. public DateTime DateArchived { get; private set; }
  4. public bool Archived { get; private set; }
  5. public void ArchiveRecord()
  6. {
  7. SwitchToArchived();
  8. }
  9. public void CloseRecord()
  10. {
  11. SwitchToArchived();
  12. }
  13. private void SwitchToArchived()
  14. {
  15. Archived = true;
  16. DateArchived = DateTime.Now;
  17. }
  18. }

代码重构第16天:封装条件

当代码中充斥着若干条件判断时,代码的真正意图会迷失于这些条件判断之中。这时我喜欢将条件判断提取到一个易于读取的属性或方法(如果有参数)中。重构之前的代码如下:

  1. public class RemoteControl
  2. {
  3. private string[] Functions { get; set; }
  4. private string Name { get; set; }
  5. private int CreatedYear { get; set; }
  6. public string PerformCoolFunction(string buttonPressed)
  7. {
  8. // Determine if we are controlling some extra function
  9. // that requires special conditions
  10. if (Functions.Length > 1 && Name == "RCA" &&
  11. CreatedYear > DateTime.Now.Year - 2)
  12. return "doSomething";
  13. }
  14. }

重构之后,代码的可读性更强,意图更明显:

  1. public class RemoteControl
  2. {
  3. private string[] Functions { get; set; }
  4. private string Name { get; set; }
  5. private int CreatedYear { get; set; }
  6. private bool HasExtraFunctions
  7. {
  8. get
  9. {
  10. return Functions.Length > 1 && Name == "RCA" &&
  11. CreatedYear > DateTime.Now.Year - 2;
  12. }
  13. }
  14. public string PerformCoolFunction(string buttonPressed)
  15. {
  16. // Determine if we are controlling some extra function
  17. // that requires special conditions
  18. if (HasExtraFunctions)
  19. return "doSomething";
  20. }
  21. }

代码重构第17天:提取父类

今天的重构来自于Martin Fowler的重构目录,当一个类有很多方法希望将它们“提拔”到基类以供同层次的其他类使用时,会经常使用该重构。下面的类包含两个方法,我们希望提取这两个方法并允许其他类使用。

  1. public class Dog
  2. {
  3. public void EatFood()
  4. {
  5. // eat some food
  6. }
  7. public void Groom()
  8. {
  9. // perform grooming
  10. }
  11. }

重构之后,我们仅仅将需要的方法转移到了一个新的基类中。这很类似“Pull Up”重构,只是在重构之前,并不存在基类。

  1. public class Animal
  2. {
  3. public void EatFood()
  4. {
  5. // eat some food
  6. }
  7. public void Groom()
  8. {
  9. // perform grooming
  10. }
  11. }
  12. public class Dog : Animal
  13. {
  14. }

代码重构第18天:使用条件判断代替异常

今天的重构没有什么出处,是我平时经常使用而总结出来的。欢迎您发表任何改进意见或建议。我相信一定还有其他比较好的重构可以解决类似的问题。

我曾无数次面对的一个代码坏味道就是,使用异常来控制程序流程。您可能会看到类似的代码:

  1. public class Microwave
  2. {
  3. private IMicrowaveMotor Motor { get; set; }
  4. public bool Start(object food)
  5. {
  6. bool foodCooked = false;
  7. try
  8. {
  9. Motor.Cook(food);
  10. foodCooked = true;
  11. }
  12. catch (InUseException)
  13. {
  14. foodcooked = false;
  15. }
  16. return foodCooked;
  17. }
  18. }

异常应该仅仅完成自己的本职工作:处理异常行为。大多数情况你都可以将这些代码用恰当的条件判断替换,并进行恰当的处理。下面的代码可以称之为契约式设计,因为我们在执行具体工作之前明确了Motor类的状态,而不是通过异常来进行处理。

  1. public class Microwave
  2. {
  3. private IMicrowaveMotor Motor { get; set; }
  4. public bool Start(object food)
  5. {
  6. if (Motor.IsInUse)
  7. return false;
  8. Motor.Cook(food);
  9. return true;
  10. }
  11. }

代码重构第19天:提取工厂类

今天的重构是由GangOfFour首先提出的,网络上有很多关于该模式不同的用法。

在代码中,通常需要一些复杂的对象创建工作,以使这些对象达到一种可以使用的状态。通常情况下,这种创建不过是新建对象实例,并以我们需要的方式进行工作。但是,有时候这种创建对象的需求会极具增长,并且混淆了创建对象的原始代码。这时,工厂类就派上用场了。最复杂的工厂模式是使用抽象工厂创建对象族。而我们只是使用最基本的方式,用一个工厂类创建
一个特殊类的实例。来看下面的代码:

  1. public class PoliceCarController
  2. {
  3. public PoliceCar New(int mileage, bool serviceRequired)
  4. {
  5. PoliceCar policeCar = new PoliceCar();
  6. policeCar.ServiceRequired = serviceRequired;
  7. policeCar.Mileage = mileage;
  8. return policeCar;
  9. }
  10. }

如您所见,New方法负责创建PoliceCar并根据一些外部输入初始化PoliceCar的某些属性。对于简单的创建工作来说,这样做可以从容应对。但是久而久之,创建的工作量越来越大,并且被附加在controller 类上,但这并不是controller类的职责。这时,我们可以将创建代码提取到一个Factory类中去,由该类负责PoliceCar实例的创建。

  1. public interface IPoliceCarFactory
  2. {
  3. PoliceCar Create(int mileage, bool serviceRequired);
  4. }
  5. public class PoliceCarFactory : IPoliceCarFactory
  6. {
  7. public PoliceCar Create(int mileage, bool serviceRequired)
  8. {
  9. PoliceCar policeCar = new PoliceCar();
  10. policeCar.ReadForService = serviceRequired;
  11. policeCar.Mileage = mileage;
  12. return policeCar;
  13. }
  14. }
  15. public class PoliceCarController
  16. {
  17. public IPoliceCarFactory PoliceCarFactory { get; set; }
  18. public PoliceCarController(IPoliceCarFactory policeCarFactory)
  19. {
  20. PoliceCarFactory = policeCarFactory;
  21. }
  22. public PoliceCar New(int mileage, bool serviceRequired)
  23. {
  24. return PoliceCarFactory.Create(mileage, serviceRequired);
  25. }
  26. }

由于将创建的逻辑转移到了工厂中,我们可以添加一个类来专门负责实例的创建,而不必担心在创建或复制代码的过程中有所遗漏。

代码重构第20天:提取子类

今天的重构来自于Martin Fowler的模式目录。你可以在他的目录中找到该重构。

当一个类中的某些方法并不是面向所有的类时,可以使用该重构将其迁移到子类中。我这里举的例子十分简单,它包含一个Registration类,该类处理与学生注册课程相关的所有信息。

  1. public class Registration
  2. {
  3. public NonRegistrationAction Action { get; set; }
  4. public decimal RegistrationTotal { get; set; }
  5. public string Notes { get; set; }
  6. public string Description { get; set; }
  7. public DateTime RegistrationDate { get; set; }
  8. }

当使用了该类之后,我们就会意识到问题所在——它应用于两个完全不同的场景。属性NonRegistrationAction和Notes 只有在处理与普通注册略有不同的NonRegistration 时才会使用。因此,我们可以提取一个子类,并将这两个属性转移到NonRegistration类中,这样才更合适。

  1. public class Registration
  2. {
  3. public decimal RegistrationTotal { get; set; }
  4. public string Description { get; set; }
  5. public DateTime RegistrationDate { get; set; }
  6. }
  7. public class NonRegistration : Registration
  8. {
  9. public NonRegistrationAction Action { get; set; }
  10. public string Notes { get; set; }
  11. }

代码重构第21天:合并继承

今天的重构来自于Martin Fowler的模式目录。你可以在他的目录中找到该重构。昨天,我们通过提取子类来下放职责。而今天,当我们意识到不再需要某个子类时,可以使用Collapse Hierarchy 重构。如果某个子类的属性(以及其他成员)可以被合并到基类中,这时再保留这个子类已经没有任何意义了。

  1. public class Website
  2. {
  3. public string Title { get; set; }
  4. public string Description { get; set; }
  5. public IEnumerable<Webpage> Pages { get; set; }
  6. }
  7. public class StudentWebsite : Website
  8. {
  9. public bool IsActive { get; set; }
  10. }

这里的子类并没有过多的功能,只是表示站点是否激活。这时我们会意识到判断站点是否激活的功能应该是通用的。因此可以将子类的功能放回到Website 中,并删除StudentWebsite 类型。

  1. public class Website
  2. {
  3. public string Title { get; set; }
  4. public string Description { get; set; }
  5. public IEnumerable<Webpage> Pages { get; set; }
  6. public bool IsActive { get; set; }
  7. }

代码重构第22天:分解方法

今天的重构没有任何出处。可能已经有其他人使用了相同的重构,只是名称不同罢了。如果你知道谁的名字比Break Method更好,请转告我。

这个重构是一种元重构(meta-refactoring),它只是不停地使用提取方法重构,直到将一个大的方法分解成若干个小的方法。下面的例子有点做作,AcceptPayment 方法没有丰富的功能。因此为了使其更接近真实场景,我们只能假设该方法中包含了其他大量的辅助代码。

下面的AcceptPayment 方法可以被划分为多个单独的方法。

  1. public class CashRegister
  2. {
  3. public CashRegister()
  4. {
  5. Tax = 0.06m;
  6. }
  7. private decimal Tax { get; set; }
  8. public void AcceptPayment(Customer customer, IEnumerable<Product> products, decimal payment)
  9. {
  10. decimal subTotal = 0m;
  11. foreach (Product product in products)
  12. {
  13. subTotal += product.Price;
  14. }
  15. foreach (Product product in products)
  16. {
  17. subTotal -= product.AvailableDiscounts;
  18. }
  19. decimal grandTotal = subTotal * Tax;
  20. customer.DeductFromAccountBalance(grandTotal);
  21. }
  22. }
  23. public class Customer
  24. {
  25. public void DeductFromAccountBalance(decimal amount)
  26. {
  27. // deduct from balance
  28. }
  29. }
  30. public class Product
  31. {
  32. public decimal Price { get; set; }
  33. public decimal AvailableDiscounts { get; set; }
  34. }

如您所见,AcceptPayment方法包含多个功能,可以被分解为多个子方法。因此我们多次使用提取方法重构,结果如下:

  1. public class CashRegister
  2. {
  3. public CashRegister()
  4. {
  5. Tax = 0.06m;
  6. }
  7. private decimal Tax { get; set; }
  8. private IEnumerable<Product> Products { get; set; }
  9. public void AcceptPayment(Customer customer, IEnumerable<Product> products, decimal payment)
  10. {
  11. decimal subTotal = CalculateSubtotal();
  12. subTotal = SubtractDiscounts(subTotal);
  13. decimal grandTotal = AddTax(subTotal);
  14. SubtractFromCustomerBalance(customer, grandTotal);
  15. }
  16. private void SubtractFromCustomerBalance(Customer customer, decimal grandTotal)
  17. {
  18. customer.DeductFromAccountBalance(grandTotal);
  19. }
  20. private decimal AddTax(decimal subTotal)
  21. {
  22. return subTotal * Tax;
  23. }
  24. private decimal SubtractDiscounts(decimal subTotal)
  25. {
  26. foreach (Product product in Products)
  27. {
  28. subTotal -= product.AvailableDiscounts;
  29. }
  30. return subTotal;
  31. }
  32. private decimal CalculateSubtotal()
  33. {
  34. decimal subTotal = 0m;
  35. foreach (Product product in Products)
  36. {
  37. subTotal += product.Price;
  38. }
  39. return subTotal;
  40. }
  41. }
  42. public class Customer
  43. {
  44. public void DeductFromAccountBalance(decimal amount)
  45. {
  46. // deduct from balance
  47. }
  48. }
  49. public class Product
  50. {
  51. public decimal Price { get; set; }
  52. public decimal AvailableDiscounts { get; set; }
  53. }

代码重构第23天:引入参数对象

该重构来自于Fowler的重构目录。有时当使用一个包含多个参数的方法时,由于参数过多会导致可读性严重下降,如:

  1. public void Create(decimal amount, Student student, IEnumerable<Course> courses, decimal credits)
  2. {
  3. // do work
  4. }

这时有必要新建一个类,负责携带方法的参数。如果要增加更多的参数,只需为对参数对象增加其他的字段就可以了,代码显得更加灵活。要注意,仅仅在方法的参数确实过多时才使用该重构,否则会使类的数量暴增,而这本应该越少越好。

  1. public class RegistrationContext
  2. {
  3. public decimal Amount { get; set; }
  4. public Student Student { get; set; }
  5. public IEnumerable<Course> Courses { get; set; }
  6. public decimal Credits { get; set; }
  7. }
  8. public class Registration
  9. {
  10. public void Create(RegistrationContext registrationContext)
  11. {
  12. // do work
  13. }
  14. }

代码重构第24天:分解复杂判断

今天的重构基于c2的wiki条目。Los Techies的Chris Missal同样也些了一篇关于反模式的post。简单地说,当你使用大量的嵌套条件判断时,形成了箭头型的代码,这就是箭头反模式(arrowhead
antipattern)。我经常在不同的代码库中看到这种现象,这提高了代码的圈复杂度(cyclomatic complexity)。下面的例子演示了箭头反模式:

  1. public class Security
  2. {
  3. public ISecurityChecker SecurityChecker { get; set; }
  4. public Security(ISecurityChecker securityChecker)
  5. {
  6. SecurityChecker = securityChecker;
  7. }
  8. public bool HasAccess(User user, Permission permission, IEnumerable<Permission> exemptions)
  9. {
  10. bool hasPermission = false;
  11. if (user != null)
  12. {
  13. if (permission != null)
  14. {
  15. if (exemptions.Count() == 0)
  16. {
  17. if (SecurityChecker.CheckPermission(user, permission) || exemptions.Contains(permission))
  18. {
  19. hasPermission = true;
  20. }
  21. }
  22. }
  23. }
  24. return hasPermission;
  25. }
  26. }

移除箭头反模式的重构和封装条件判断一样简单。这种方式的重构在方法执行之前往往会评估各个条件,这有点类似于契约式设计验证。下面是重构之后的代码:

  1. public class Security
  2. {
  3. public ISecurityChecker SecurityChecker { get; set; }
  4. public Security(ISecurityChecker securityChecker)
  5. {
  6. SecurityChecker = securityChecker;
  7. }
  8. public bool HasAccess(User user, Permission permission, IEnumerable<Permission> exemptions)
  9. {
  10. if (user == null || permission == null)
  11. return false;
  12. if (exemptions.Contains(permission))
  13. return true;
  14. return SecurityChecker.CheckPermission(user, permission);
  15. }
  16. }

如你所见,该方法大大整价了可读性和以后的可维护性。不难看出,该方法的所有可能的路径都会经过验证。

代码重构第25天:引入契约式设计

契约式设计(DBC,Design By Contract)定义了方法应该包含输入和输出验证。因此,可以确保所有的工作都是基于可用的数据,并且所有的行为都是可预料的。否则,将返回异常或错误并在方法中进行处理。要了解更多关于DBC的内容,可以访问wikipedia。

在我们的示例中,输入参数很可能为null。由于没有进行验证,该方法最终会抛出NullReferenceException。在方法最后,我们也并不确定是否为用户返回了一个有效的decimal,这可能导致在别的地方引入其他方法。

  1. public class CashRegister
  2. {
  3. public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
  4. {
  5. decimal orderTotal = products.Sum(product => product.Price);
  6. customer.Balance += orderTotal;
  7. return orderTotal;
  8. }
  9. }

在此处引入DBC 验证是十分简单的。首先,我们要声明customer 不能为null,并且在计算总值时至少要有一个product。在返回订单总值时,我们要确定其值是否有效。如果此例中任何一个验证失败,我们将以友好的方式抛出相应的异常来描述具体信息,而不是抛出一个晦涩的NullReferenceException。

在.NET Framework 3.5的Microsoft.Contracts命名空间中包含一些DBC框架和异常。我个人还没有使用,但它们还是值得一看的。关于该命名空间只有在MSDN上能找到点资料。

  1. public class CashRegister
  2. {
  3. public decimal TotalOrder(IEnumerable<Product> products, Customer customer)
  4. {
  5. if (customer == null)
  6. throw new ArgumentNullException("customer", "Customer cannot be null");
  7. if (products.Count() == 0)
  8. throw new ArgumentException("Must have at least one product to total", "products");
  9. decimal orderTotal = products.Sum(product => product.Price);
  10. customer.Balance += orderTotal;
  11. if (orderTotal == 0)
  12. throw new ArgumentOutOfRangeException("orderTotal", "Order Total should not be zero");
  13. return orderTotal;
  14. }
  15. }

在验证过程中确实增加了不少代码,你也许会认为过度使用了DBC。但我认为在大多数情况下,处理这些棘手的问题所做的努力都是值得的。追踪无详细内容的NullReferenceException的确不是什么美差。

代码重构第26天:避免双重否定

今天的重构来自于Fowler的重构目录。
尽管我在很多代码中发现了这种严重降低可读性并往往传达错误意图的坏味道,但这种重构本身还是很容易实现的。这种毁灭性的代码所基于的假设导致了错误的代码编写习惯,并最终导致bug。如下例所示:

  1. public class Order
  2. {
  3. public void Checkout(IEnumerable<Product> products, Customer customer)
  4. {
  5. if (!customer.IsNotFlagged)
  6. {
  7. // the customer account is flagged
  8. // log some errors and return
  9. return;
  10. }
  11. // normal order processing
  12. }
  13. }
  14. public class Customer
  15. {
  16. public decimal Balance { get; private set; }
  17. public bool IsNotFlagged
  18. {
  19. get { return Balance < 30m; }
  20. }
  21. }

如你所见,这里的双重否定十分难以理解,我们不得不找出什么才是双重否定所要表达的肯定状态。修改代码是很容易的。如果我们找不到肯定的判断,可以添加一个处理双重否定的假设,而不要在得到结果之后再去验证。

  1. public class Order
  2. {
  3. public void Checkout(IEnumerable<Product> products, Customer customer)
  4. {
  5. if (customer.IsFlagged)
  6. {
  7. // the customer account is flagged
  8. // log some errors and return
  9. return;
  10. }
  11. // normal order processing
  12. }
  13. }
  14. public class Customer
  15. {
  16. public decimal Balance { get; private set; }
  17. public bool IsFlagged
  18. {
  19. get { return Balance >= 30m; }
  20. }
  21. }

代码重构第27天:去除上帝类

在传统的代码库中,我们常常会看到一些违反了SRP原则的类。这些类通常以Utils或Manager结尾,有时也没有这么明显的特征而仅仅是普通的包含多个功能的类。这种God 类还有一个特征,使用语句或注释将代码分隔为多个不同角色的分组,而这些角色正是这一个类所扮演的。

久而久之,这些类成为了那些没有时间放置到恰当类中的方法的垃圾桶。这时的重构需要将方法分解成多个负责单一职责的类。

  1. public class CustomerService
  2. {
  3. public decimal CalculateOrderDiscount(IEnumerable<Product> products, Customer customer)
  4. {
  5. // do work
  6. }
  7. public bool CustomerIsValid(Customer customer, Order order)
  8. {
  9. // do work
  10. }
  11. public IEnumerable<string> GatherOrderErrors(IEnumerable<Product> products, Customer customer)
  12. {
  13. // do work
  14. }
  15. public void Register(Customer customer)
  16. {
  17. // do work
  18. }
  19. public void ForgotPassword(Customer customer)
  20. {
  21. // do work
  22. }
  23. }

使用该重构是非常简单明了的,只需把相关方法提取出来并放置到负责相应职责的类中即可。这使得类的粒度更细、职责更分明、日后的维护更方便。上例的代码最终被分解为两个类:

  1. public class CustomerOrderService
  2. {
  3. public decimal CalculateOrderDiscount(IEnumerable<Product> products, Customer customer)
  4. {
  5. // do work
  6. }
  7. public bool CustomerIsValid(Customer customer, Order order)
  8. {
  9. // do work
  10. }
  11. public IEnumerable<string> GatherOrderErrors(IEnumerable<Product> products, Customer customer)
  12. {
  13. // do work
  14. }
  15. }
  16. public class CustomerRegistrationService
  17. {
  18. public void Register(Customer customer)
  19. {
  20. // do work
  21. }
  22. public void ForgotPassword(Customer customer)
  23. {
  24. // do work
  25. }
  26. }

代码重构第28天:为布尔方法命名

今天的重构不是来自于Fowler的重构目录。如果谁知道这项“重构”的确切出处,请告诉我。

当然,你也可以说这并不是一个真正的重构,因为方法实际上改变了,但这是一个灰色地带,可以开放讨论。一个拥有大量布尔类型参数的方法将很快变得无法控制,产生难以预期的行为。参数的数量将决定分解的方法的数量。来看看该重构是如何开始的:

  1. public class BankAccount
  2. {
  3. public void CreateAccount(Customer customer, bool withChecking, bool withSavings, bool withStocks)
  4. {
  5. // do work
  6. }
  7. }

要想使这样的代码运行得更好,我们可以通过命名良好的方法暴露布尔参数,并将原始方法更改为private以阻止外部调用。显然,你可能需要进行大量的代码转移,也许重构为一个Parameter Object 会更有意义。

  1. public class BankAccount
  2. {
  3. public void CreateAccountWithChecking(Customer customer)
  4. {
  5. CreateAccount(customer, true, false);
  6. }
  7. public void CreateAccountWithCheckingAndSavings(Customer customer)
  8. {
  9. CreateAccount(customer, true, true);
  10. }
  11. private void CreateAccount(Customer customer, bool withChecking, bool withSavings)
  12. {
  13. // do work
  14. }
  15. }

代码重构第29天:去除中间人对象

今天的重构来自于Fowler的重构目录。

有时你的代码里可能会存在一些“Phantom”或“Ghost”类,Fowler 称之为“中间人(Middle Man)”。这些中间人类仅仅简单地将调用委托给其他组件,除此之外没有任何功能。这一层是完全没有必要的,我们可以不费吹灰之力将其完全移除。

  1. public class Consumer
  2. {
  3. public AccountManager AccountManager { get; set; }
  4. public Consumer(AccountManager accountManager)
  5. {
  6. AccountManager = accountManager;
  7. }
  8. public void Get(int id)
  9. {
  10. Account account = AccountManager.GetAccount(id);
  11. }
  12. }
  13. public class AccountManager
  14. {
  15. public AccountDataProvider DataProvider { get; set; }
  16. public AccountManager(AccountDataProvider dataProvider)
  17. {
  18. DataProvider = dataProvider;
  19. }
  20. public Account GetAccount(int id)
  21. {
  22. return DataProvider.GetAccount(id);
  23. }
  24. }
  25. public class AccountDataProvider
  26. {
  27. public Account GetAccount(int id)
  28. {
  29. // get account
  30. }
  31. }

最终结果已经足够简单了。我们只需要移除中间人对象,将原始调用指向实际的接收者。

  1. public class Consumer
  2. {
  3. public AccountDataProvider AccountDataProvider { get; set; }
  4. public Consumer(AccountDataProvider dataProvider)
  5. {
  6. AccountDataProvider = dataProvider;
  7. }
  8. public void Get(int id)
  9. {
  10. Account account = AccountDataProvider.GetAccount(id);
  11. }
  12. }
  13. public class AccountDataProvider
  14. {
  15. public Account GetAccount(int id)
  16. {
  17. // get account
  18. }
  19. }

代码重构第30天:尽快返回

该话题实际上是诞生于移除箭头反模式重构之中。在移除箭头时,它被认为是重构产生的副作用。为了消除箭头,你需要尽快地return。

  1. public class Order
  2. {
  3. public Customer Customer { get; private set; }
  4. public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
  5. {
  6. Customer = customer;
  7. decimal orderTotal = 0m;
  8. if (products.Count() > 0)
  9. {
  10. orderTotal = products.Sum(p => p.Price);
  11. if (discounts > 0)
  12. {
  13. orderTotal -= discounts;
  14. }
  15. }
  16. return orderTotal;
  17. }
  18. }

该重构的理念就是,当你知道应该处理什么并且拥有全部需要的信息之后,立即退出所在方法,不再继续执行。

  1. public class Order
  2. {
  3. public Customer Customer { get; private set; }
  4. public decimal CalculateOrder(Customer customer, IEnumerable<Product> products, decimal discounts)
  5. {
  6. if (products.Count() == 0)
  7. return 0;
  8. Customer = customer;
  9. decimal orderTotal = products.Sum(p => p.Price);
  10. if (discounts == 0)
  11. return orderTotal;
  12. orderTotal -= discounts;
  13. return orderTotal;
  14. }
  15. }

代码重构第31天:使用多态代替条件判断

最后一天的重构来自于Fowler的重构目录。

多态(Polymorphism)是面向对象编程的基本概念之一。在这里,是指在进行类型检查和执行某些类型操作时,最好将算法封装在类中,并且使用多态来对代码中的调用进行抽象。

  1. public abstract class Customer
  2. {
  3. }
  4. public class Employee : Customer
  5. {
  6. }
  7. public class NonEmployee : Customer
  8. {
  9. }
  10. public class OrderProcessor
  11. {
  12. public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)
  13. {
  14. // do some processing of order
  15. decimal orderTotal = products.Sum(p => p.Price);
  16. Type customerType = customer.GetType();
  17. if (customerType == typeof(Employee))
  18. {
  19. orderTotal -= orderTotal * 0.15m;
  20. }
  21. else if (customerType == typeof(NonEmployee))
  22. {
  23. orderTotal -= orderTotal * 0.05m;
  24. }
  25. return orderTotal;
  26. }
  27. }

如你所见,我们没有利用已有的继承层次进行计算,而是使用了违反SRP 原则的执行方式。要进行重构,我们只需将百分率的计算置于实际的customer类型之中。我知道这只是一项补救措施,但我还是会这么做,就像在代码中那样。

  1. public abstract class Customer
  2. {
  3. public abstract decimal DiscountPercentage { get; }
  4. }
  5. public class Employee : Customer
  6. {
  7. public override decimal DiscountPercentage
  8. {
  9. get { return 0.15m; }
  10. }
  11. }
  12. public class NonEmployee : Customer
  13. {
  14. public override decimal DiscountPercentage
  15. {
  16. get { return 0.05m; }
  17. }
  18. }
  19. public class OrderProcessor
  20. {
  21. public decimal ProcessOrder(Customer customer, IEnumerable<Product> products)
  22. {
  23. // do some processing of order
  24. decimal orderTotal = products.Sum(p => p.Price);
  25. orderTotal -= orderTotal * customer.DiscountPercentage;
  26. return orderTotal;
  27. }
  28. }

至此,恭喜你,完成了31天的代码重构学习。

【JAVA】代码重构技巧相关推荐

  1. IDEA代码重构技巧--抽取类和接口

    IDEA代码重构技巧--目录页 1. 小声哔哔 重构和检视代码过程中,我们有时会碰到由于项目交接或者人员替换导致的代码腐化,比较常见的是类的职责不单一,此时比较好的重构技巧就是按照职责抽取函数或者类, ...

  2. java代码重构工具_代码重构什么意思 Java代码重构的几种模式

    指对软件代码做任何更动以增加可读性或者简化结构而不影响输出结果. 软件重构需要借助工具完成,重构工具能够修改代码同时修改所有引用该代码的地方.在极限编程的方法学中,重构需要单元测试来支持. 在软件工程 ...

  3. IDEA代码重构技巧--迁移

    IDEA代码重构技巧--目录页 1. 小声哔哔 在代码重构和检视过程中,比较常见的是一个类或者方法职责不单一,导致代码有坏味道,这种情况就需要基于函数抽取,迁移来做代码重构,而迁移意味着调用点也需要同 ...

  4. java代码重构的思路Java代码重构的几种模式

    Java代码重构的几种模式 Java代码的重构模式主要有三种:重命名方法重构模式.引入解释性变量重构模式.以查询取代临时变量重构模式重命名方法重构模式建议执行如下的步骤来完成:1.建立一个具有新名称的 ...

  5. JavaScript代码重构技巧

    JavaScript代码重构技巧 (1)提炼函数 在js开发中,我们大部分时间在与函数打交道,将一段代码独立成函数可以避免出现超大函数.独立出来的函数有利于代码复用.独立出来的函数如果命名良好能够起到 ...

  6. 你应该知道的7个写出更好的 Java 代码的技巧

    来源:SpringForAll社区 查看这些技巧和窍门可以帮助你写出更好的 Java 代码. 是的,你可以按照以下7个技巧和窍门编写出简短.整洁的 Java 代码.他们中的一些可能会让你感到惊讶,但是 ...

  7. 代码重构技巧宝典,学透本篇就足够了!

    本文来源:http://n5d.net/ma76k 关于重构 为什么要重构 1_代码重构漫画.jpeg 项目在不断演进过程中,代码不停地在堆砌.如果没有人为代码的质量负责,代码总是会往越来越混乱的方向 ...

  8. 常见代码重构技巧(非常实用)

    点击关注公众号,Java干货及时送达  作者:VectorJin juejin.cn/post/6954378167947624484 关于重构 为什么要重构 1_代码重构漫画.jpeg 项目在不断演 ...

  9. python代码重构技巧_Python代码重构

    代码重构是一件很是辛苦却很是有意义的事情,代码重构的缘由在于:django 一.代码过于冗余.沉余架构 二.代码过于耦合函数 三.代码过于复杂学习 四.接口调用超出三层优化 此次重构主要在于架构问题, ...

最新文章

  1. linux开启FTP以及添加用户配置权限,只允许访问自身目录,不能跳转根目录
  2. Smarty中的变量
  3. [JS] 动态修改ckPlayer播放器宽度
  4. My1stServlet
  5. 办学10年,进入全国前10名!这所神奇的高校,迎来10岁生日
  6. Java中HashMap的常用操作
  7. 棋盘游戏(HDU-1281)
  8. JS跨页面调用变量的方法
  9. python数据读写 panda(to_csv和read_csv)【读取dat文件】【写入dat文件】【非csv文件并且有多列数据时】
  10. rsync同步目录及同步文件
  11. 三个杯子的倒水问题(BFS)
  12. 【web前端期末大作业】html在线网上书店 基于html制作我的书屋(23页面)
  13. Mac没有右Control的解决办法
  14. 一亿用户背后架构的秘密
  15. 杨昕立计算机学院,写在告别之前——那些来自辅导员们的悄悄话
  16. 看完面经,他拿出一打大厂offer玩起了斗地主,人生不过是如此枯燥乏味....
  17. mysql update join优化update in查询效率
  18. ZStack Cloud助力南京四方亿能升级配电自动化系统
  19. PAT 甲级 英语基础
  20. quartz_初步探索

热门文章

  1. 强化学习入门级实践教学
  2. oracle如何查当前日期所在周,Oracle查询当前日期对应周数
  3. 河北省沧州市谷歌卫星地图下载
  4. 全球及中国晶圆激光打标机行业投资竞争力及需求规模预测报告2022-2027年
  5. 8880 e7 v2配什么主板_Xeon E7 v2系列21款产品详解_Intel服务器CPU_服务器评测与技术-中关村在线...
  6. 咖说 | TON 项目宣告终止!但社区还将继续进行开发和发币
  7. JVM系列五JVM监测工具[整理中(转)
  8. 5G WiFi 安信可 BW16 模组 RTL8720DN 入门笔记 1 :搭建Arduino IDE 开发环境,点亮一盏LED灯。
  9. Devops-day1-Git+GitLab介绍及使用+被挖矿处理
  10. Windows下使用GitHub Pages搭建hexo博客详细教程以及Next主题超全配置