您的位置:首页 > 其它

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

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

详解:重构前code

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReflectorDemo
{
public class RemoteControl
{
private string[] Functions { get; set; }
private string Name { get; set; }
private int CreatedYear { get; set; }

public string PerformCoolFunction(string buttonPressed)
{
// Determine if we are controlling some extra function
// that requires special conditions
if (Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2)
return "doSomething";
return string.Empty;
}
}
}


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

重构后代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReflectorDemo
{
public class RemoteControl
{
private string[] Functions { get; set; }
private string Name { get; set; }
private int CreatedYear { get; set; }

private bool HasExtraFunctions
{
get { return Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2; }
}

public string PerformCoolFunction(string buttonPressed)
{
// Determine if we are controlling some extra function
// that requires special conditions
if (HasExtraFunctions)
return "doSomething";
return string.Empty;
}
}
}


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

这个重构在很大程度上能改善代码的可读性,尤其是在一个逻辑很复杂的应用中,把这些条件判断封装成一个有意义的名字,这样很复杂的逻辑也会立刻变得简单起来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: