zoukankan      html  css  js  c++  java
  • 重构第16天 封装条件(Encapsulate Conditional)

    理解:本文中的“封装条件”是指条件关系比较复杂时,代码的可读性会比较差,所以这时我们应当根据条件表达式是否需要参数将条件表达式提取成可读性更好的属性或者方法,如果条件表达式不需要参数则可以提取成属性,如果条件表达式需要参数则可以提取成方法。

    详解:重构前code

     1 using System;
     2 using System.Collections;
     3 using System.Collections.Generic;
     4 using System.Linq;
     5 using System.Text;
     6 
     7 namespace ReflectorDemo
     8 {
     9     public class RemoteControl
    10     {
    11         private string[] Functions { get; set; }
    12         private string Name { get; set; }
    13         private int CreatedYear { get; set; }
    14 
    15         public string PerformCoolFunction(string buttonPressed)
    16         {
    17             // Determine if we are controlling some extra function
    18             // that requires special conditions
    19             if (Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2)
    20                 return "doSomething";
    21             return string.Empty;
    22         }
    23     }
    24 }

    PerformCoolFunction里面的if条件判断比较复杂,看起来有点杂乱,所以就把它提出来。

    重构后代码:

     1 using System;
     2 using System.Collections;
     3 using System.Collections.Generic;
     4 using System.Linq;
     5 using System.Text;
     6 
     7 namespace ReflectorDemo
     8 {
     9     public class RemoteControl
    10     {
    11         private string[] Functions { get; set; }
    12         private string Name { get; set; }
    13         private int CreatedYear { get; set; }
    14 
    15         private bool HasExtraFunctions
    16         {
    17             get { return Functions.Length > 1 && Name == "RCA" && CreatedYear > DateTime.Now.Year - 2; }
    18         }
    19 
    20         public string PerformCoolFunction(string buttonPressed)
    21         {
    22             // Determine if we are controlling some extra function
    23             // that requires special conditions
    24             if (HasExtraFunctions)
    25                 return "doSomething";
    26             return string.Empty;
    27         }
    28     }
    29 }

    我们把条件表达式封装成HasExtraFunctions属性,这样先前的条件判断就成了if (HasExtraFunctions) ,所以这样就在很大程度上提高了可读性。

    这个重构在很大程度上能改善代码的可读性,尤其是在一个逻辑很复杂的应用中,把这些条件判断封装成一个有意义的名字,这样很复杂的逻辑也会立刻变得简单起来。

  • 相关阅读:
    spring中用到哪些设计模式?
    配置监听器使项目启动时创建消费者
    ActiveMQ依赖JDK版本关系
    ActiveMQ之topic主题模式
    ActiveMQ与Spring整合
    ac自动机模板
    poj 3735 Training little cats矩阵快速幂
    KMP算法模板 求子串和模板串首先匹配的位置
    hdoj 2665 Kth number主席树裸
    vijos P1081野生动物园 主席树求区间第K大
  • 原文地址:https://www.cnblogs.com/yplong/p/5362663.html
Copyright © 2011-2022 走看看