封装条件(Encapsulate Conditional)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装条件(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)的主要内容,如果未能解决你的问题,请参考以下文章