首页 > 代码库 > 封装条件(Encapsulate Conditional)
封装条件(Encapsulate Conditional)
封装就是将相关的方法或者属性抽象成为一个对象。
封装的意义:
- 对外隐藏内部实现,接口不变,内部实现自由修改。
- 只返回需要的数据和方法。
- 提供一种方式防止数据被修改。
- 更好的代码复用。
当代码中包含许多条件判断,为了改善代码的可读性和可维护性,我们可以将条件封装。
有两种封装方式:
一、无参数的条件判断,封装为属性
重构前代码
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。