zoukankan      html  css  js  c++  java
  • 31天重构指南之二十八:为布尔方法命名

    今天要说的重构我不确定是否是来自于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

  • 相关阅读:
    01
    Django2
    Django01
    DS18B20时序解析,以及读出85原因诠释
    python字符串打印-不同方法vars
    2.对象属性
    1.excel-vba-对象
    搭建 eclipse,maven,tomcat 环境
    jsp include flush true
    oracle数据库基础
  • 原文地址:https://www.cnblogs.com/zhangronghua/p/1597282.html
Copyright © 2011-2022 走看看