今天这个重构比较不错,将代码中充斥的N多判断条件提取成为一个属性,可以实现复用,并且使得结构清晰

旧的代码:

    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 "Other";
         }
     }

重构成如下模样:

    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";
         }
     }

重构后代码结构更加清晰,这个重构我比较喜欢


Leave a Reply