IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之二十八:为布尔方法命名

Posted on 2009-11-06 11:15  张荣华  阅读(545)  评论(1编辑  收藏  举报

今天要说的重构我不确定是否是来自于Fowlers的重构目录,如果有人知道今天要说的重构的实际出处,请告诉我。

今天要说的重构并不是普通字面意义上的重构,它有值得讨论的地方。当一个方法带有大量的布尔型参数时,会导致方法很容易被误解并产生非预期的行为,

根据布尔型参数的数量,我们可以决定提取出若干个独立方法来。下面让我们来看一段代码:

   1: public class BankAccount
   2: {
   3:     public void CreateAccount(Customer customer, bool withChecking, bool withSavings, bool withStocks)
   4:     {
   5:         // do work
   6:     }
   7: }
 
我们可以将上面的布尔型参数以独立方法的形式暴露以提高代码的可读性,同时我们还需要将原先的方法改为private以限制其可访问性。显然我们关于要
提取的独立方法会有一个很大的排列组合,所以我们可以考虑引入参数对象重构。
 
   1: public class BankAccount
   2: {
   3:     public void CreateAccountWithChecking(Customer customer)
   4:     {
   5:         CreateAccount(customer, true, false);
   6:     }
   7:  
   8:     public void CreateAccountWithCheckingAndSavings(Customer customer)
   9:     {
  10:         CreateAccount(customer, true, true);
  11:     }
  12:  
  13:     private void CreateAccount(Customer customer, bool withChecking, bool withSavings)
  14:     {
  15:         // do work
  16:     }
  17: }

 

原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/28/refactoring-day-28-rename-boolean-method.aspx