徐州软件开发网、徐州程序员、徐州程序员招聘求职、徐州软件企业推荐、 软件项目交易。点击注册加入我们,进入论坛发布消息

【行动胜于雄辩】徐州程序员交流QQ群:324379(一群,满)1182709(二群).进群请先看公告! 招聘求职请先在本站'招聘\求职区'发布,只在群里发布的,将被请出程序员交流群! 谢谢合作

本主题共有 0 篇回复,最新回复发表于 10-10-2009 22:17,作者 xzsdn_08
页 1 / 1 (1 项)
帖子排序: 上一主题 下一主题
  • 10-10-2009 22:17

    • xzsdn_08
    • 灌水10强
      男
    • 注册时间 01-04-2009
    • 江苏徐州
    • 发帖总数 641

    31天重构指南 26避免双重否定

    Refactoring Day 26 : Remove Double Negative

    Today’s refactoring comes from Fowler’s refactoring catalog and can be found here.

    This refactoring is pretty simple to implement although I find it in many codebases that severely hurts readability and almost always conveys incorrect intent. This type of code does the most damage because of the assumptions made on it. Assumptions lead to incorrect maintenance code written, which in turn leads to bugs. Take the following example:

       1: public class Order
       2: {
       3:     public void Checkout(IEnumerable<Product> products, Customer customer)
       4:     {
       5:         if (!customer.IsNotFlagged)
       6:         {
       7:             // the customer account is flagged
       8:             // log some errors and return
       9:             return;
      10:         }
      11:  
      12:         // normal order processing
      13:     }
      14: }
      15:  
      16: public class Customer
      17: {
      18:     public decimal Balance { get; private set; }
      19:  
      20:     public bool IsNotFlagged
      21:     {
      22:         get { return Balance < 30m; }
      23:     }
      24: }

    As you can see the double negative here is difficult to read because we have to figure out what is positive state of the two negatives. The fix is very easy. If we don’t have a positive test, add one that does the double negative assertion for you rather than make sure you get it correct.

       1: public class Order
       2: {
       3:     public void Checkout(IEnumerable<Product> products, Customer customer)
       4:     {
       5:         if (customer.IsFlagged)
       6:         {
       7:             // the customer account is flagged
       8:             // log some errors and return
       9:             return;
      10:         }
      11:  
      12:         // normal order processing
      13:     }
      14: }
      15:  
      16: public class Customer
      17: {
      18:     public decimal Balance { get; private set; }
      19:  
      20:     public bool IsFlagged
      21:     {
      22:         get { return Balance >= 30m; }
      23:     }
      24: }

    This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.

页 1 / 1 (1 项)
徐州软件开发网、徐州软件开发社区、徐州程序员
© Copyright 2008-2011 XZSDN.NET   Powered By communityserver   站长博客 我的Blog
苏ICP备09002379号 | 意见反馈 | 联系我