首页 > 代码库 > 封装条件(Encapsulate Conditional)

封装条件(Encapsulate Conditional)

封装就是将相关的方法或者属性抽象成为一个对象。
封装的意义:
  1. 对外隐藏内部实现,接口不变,内部实现自由修改。
  2. 只返回需要的数据和方法。
  3. 提供一种方式防止数据被修改。
  4. 更好的代码复用。
 
当代码中包含许多条件判断,为了改善代码的可读性和可维护性,我们可以将条件封装。
有两种封装方式:
一、无参数的条件判断,封装为属性
 
重构前代码
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";        }    }

重构后代码

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";        }    }
二、有参数的条件判断,封装为方法
 
重构前代码
 public class RemoteControl    {        private string[] Functions { 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 && buttonPressed== "RCA" && CreatedYear > DateTime.Now.Year - 2)                return "doSomething";        }    }

重构后代码

 public class RemoteControl    {        private string[] Functions { get; set; }        private string Name { get; set; }        private int CreatedYear { get; set; }        private bool HasExtraFunctions(string buttonPressed)        {            get { return Functions.Length > 1 && buttonPressed== "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(buttonPressed))                return "doSomething";        }    }

 

封装条件(Encapsulate Conditional)