重构第16天 封装条件(Encapsulate Conditional)

理解:本文中的“封装条件”是指条件关系比较复杂时,代码的可读性会比较差,所以这时我们应当根据条件表达式是否需要参数将条件表达式提取成可读性更好的属性或者方法,如果条件表达式不需要参数则可以提取成属性,如果条件表达式需要参数则可以提取成方法。

详解:重构前code

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

PerformCoolFunction里面的if条件判断比较复杂,看起来有点杂乱,所以就把它提出来。

重构后代码:

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

我们把条件表达式封装成HasExtraFunctions属性,这样先前的条件判断就成了if (HasExtraFunctions) ,所以这样就在很大程度上提高了可读性。

这个重构在很大程度上能改善代码的可读性,尤其是在一个逻辑很复杂的应用中,把这些条件判断封装成一个有意义的名字,这样很复杂的逻辑也会立刻变得简单起来。

原文地址:https://www.cnblogs.com/yplong/p/5362663.html