zoukankan      html  css  js  c++  java
  • 代码可读性提升之多条件判断语句

            有时,看到类似这样的C#语句:

       1:          private static bool TraditionalVerify(int number)
       2:          {
       3:              if ((number > 0) && (number >= 10) && (number % 2 > 0) && (number * 2 > 100))
       4:              {
       5:                  return true;
       6:              }
       7:              return false;
       8:          }

            这里只有四个条件,假设这里有超过四个或更多时,那时代码转行时可读性就更差了。我们可以将上面的代码改成:

       1:          /// <summary>
       2:          /// Demo for use Func combine conditions
       3:          /// </summary>
       4:          /// <param name="number">need verify number</param>
       5:          /// <returns>true</returns>
       6:          /// <seealso cref="http://msdn.microsoft.com/en-us/library/kdxe4x4w.aspx"/>
       7:          /// <remarks>author Petter Liu http://wintersun.cnblogs.com</remarks>
       8:          private static bool UseFunc(int number)
       9:          {
      10:              var conditionlist = new List<Func<bool>>()
      11:              {
      12:                   () => number > 0,
      13:                   () => number >= 10,
      14:                   () => number % 2 > 0,
      15:                   () => number * 2 > 100
      16:              };
      17:   
      18:              return conditionlist.TrueForAll(foo => foo.Invoke());
      19:          }

           注意粗体部分的代码,这样看上去更容易阅读。你可增多更多的条件判读语句。实际情况下,还可以考虑Strategies来重构代码。

           希望对您开发有帮助!


    作者:Petter Liu
    出处:http://www.cnblogs.com/wintersun/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    该文章也同时发布在我的独立博客中-Petter Liu Blog

  • 相关阅读:
    C#定时执行任务
    C#判断数据库是否可连接(PING)
    Excel之导入数据
    JQuery之杂项方法$.grep()
    .Net EF 之代码生成策略
    平台与WeLink深度融合技术汇总
    Host is not allowed to connect to this MySQL
    excel中过长的数字怎么筛选重复项
    oracle 函数大全
    WinXP添加TLS1.1、TLS1.2支持
  • 原文地址:https://www.cnblogs.com/wintersun/p/1952199.html
Copyright © 2011-2022 走看看