有时当我们的条件关系比较复杂时,代码的可读性会比较差,所以这时我们应该根据条件表达式是否需要参数将条件表达式提取成可读性更好的属性或是方法,如果条件表达式不需要参数则可以提取成属性,如果条件表达式需要参数则可以提取成方法。下面是我们来看一段重构前的代码:
1: public class RemoteControl
2: {
3: private string[] Functions { get; set; }
4: private string Name { get; set; }
5: private int CreatedYear { get; set; }
6:
7: public string PerformCoolFunction(string buttonPressed)
8: {
9: // Determine if we are controlling some extra function
10: // that requires special conditions
11: if (Functions.Length > 1 && Name == "RCA" && 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:
7: private bool HasExtraFunctions
8: {
9: get { return Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2; }
10: }
11:
12: public string PerformCoolFunction(string buttonPressed)
13: {
14: // Determine if we are controlling some extra function
15: // that requires special conditions
16: if (HasExtraFunctions)
17: return "doSomething";
18: }
19: }