用方法对象取代方法

转自:http://chaimzane.iteye.com/blog/321951

七 Replace Methord with Method Object

 

 你有个大型函数,其中对局部变量的使用,使你无法采用Extact Method .

 

 动机:小型函数具有其优美动人之处,只要将它重大型函数中提炼出来,就可以大大提高代码的可阅读性。但是局部变量的存在会增加分解函数的难度。ReplaceTemporary with qury 可以帮助你减轻这一负担,但是有时候你会发现根本无法拆解需要拆解的函数。这时,你就应该祭出 函数对象(Method object)这件法宝。将所有的函数对象都变成函数对象的值域。然后你及可以对这个新对象用 Extract Method创造出新函数,从而使原来的大型函数拆解变短。

 

例子:

class Account 
{   
       public int  gamma(int inputVal, int quantity, int yearToDate) 
      {   
            int importantValue1 = (inputVal * quantity) + delta();   
            int importantValue2 = (inputVal * yearToDate) + 100;   
          
            if ((yearToDate - importValue1) > 100) 
           {   
                  importValue2 -= 20;   
           }   
  
           int importantValue3 = importValue2 * 7;   
          
         //等等
         return imortantValue3 - 2 * importantValue1;   
}  

 

 =>为了把这函数变成一个函数对象,首先要声明一个新的Class

 

class Gamma 
{
    private Account account ;   
    private int inputVal;   
    private int quantity;   
    private int yearToDate;   
    private int importtantantValue1;   
    private int importtantantValue2;   
    private int importtantantValue3;   
  
    public Gamma (Account souce, int inputValArg,   
                           int quantityArg, int yearToDateArg) 
   {   
           
        account = souce;   
        inputVal = inputValArg;   
        quantity = quantityArg;   
        yearToDate = yearToDateArg;   
   }   
  
    public int  compute()
    {   
        importtantantValue1 = (inputVal  * quantity) + account.delta();   
        importtantantValue2 = (inputVal  * yearToDate ) + 100;   
        
       if (( yearToDate - importantValue) > 100 ) 
      {   
            importtantantValue2   -= 20;   
      }   
  
         importantValue3 = importantValue2 * 7;   
  
         return importantValue3 - 2*  importantValue1;   
   } 

 

class Account 
{
    public int  gamma(int inputVal, int quantity, int yearToDate)
   {   
        return new Gamma(this, inputVal, quantity, yearToDate).compute();   
    }
}  

 

 

  这样一来,我们就可以轻松的对 compute()进行 Extract Method而不必担心 引数的传递

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值