封裝就是將相關的方法或者屬性抽象成為一個對象。 封裝的意義: 當代碼中包含許多條件判斷,為了改善代碼的可讀性和可維護性,我們可以將條件封裝。 有兩種封裝方式: 一、無參數的條件判斷,封裝為屬性 重構前代碼 public class RemoteControl { private string[] F ...
封裝就是將相關的方法或者屬性抽象成為一個對象。 封裝的意義:
- 對外隱藏內部實現,介面不變,內部實現自由修改。
- 只返回需要的數據和方法。
- 提供一種方式防止數據被修改。
- 更好的代碼復用。
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"; } }