IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之二十六: 避免双重否定

Posted on 2009-10-19 15:33  张荣华  阅读(360)  评论(1编辑  收藏  举报

今天要说的重构来自于Martin Fowlers的重构目录,你可以在这里看到原始的描述。

避免双重否定重构本身非常简单实现,但我却在太多的代码中见过因为双重否定降低了代码的可读性以致于非常让人容易误解原始意图。存在双重否定的代码具有非常大的危害性,因为这种类型的代码容易引起错误的假定,错误的假定又会导致书写出错误的维护代码,最终会导致bug产生。让我们来看下面的例子:

   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: }
 
上面代码中的双重否定的可读性非常低,因为我们很难搞明白双重否定的正确值。要重构它非常容易,下面是重构后的代码:
   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: }
 
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/26/refactoring-day-26-remove-double-negative.aspx