10.9introduce parameter object

来源:互联网 发布:永宏plc编程软件 编辑:程序博客网 时间:2024/06/15 20:18

 某些参数总是很自然地同时出现。

以一个对象取代这些参数。

动机:

常会看到特定的一组参数总是一起被传递。可能有好几个函数都使用这一组参数,这些函数可能隶属同一个类,也可能隶属不同的类。这就是data clumps(数据泥团),可以运用一个对象包装所有这些数据,再以该对象取代它们。

做法:

新建一个类,用以表现你想替换的一组参数。将这个类设为不可变的。

针对使用该组参数的所有函数,实施add parameter,传入上述新建类的实例对象,并将此参数值设为null。

=》如果你所修改的函数被其他很多函数调用,那么可以保留修改前的旧函数,并令它调用修改后的新函数。你可以先对旧函数进行重构,然后逐一修改调用端使其调用新函数,最后再将旧函数删除。

对于data clumps中的每一项,从函数签名中移除之,并修改调用端和函数本体,令它们都改而通过新的参数对象取得该值。

每去除一个参数,编译并测试。

将原先的参数全部去除之后,观察有无适当函数可以运用move method搬移到参数对象之中。

=》被搬移的可能是整个函数,也可能是函数中的一个段落。如果是后者,首先使用extract method将该段落提炼为一个独立函数,再搬移这一新建函数。

范例:

旧代码

class Entry...    Entry(double value, Date chargeDate)    {        _value = value;        _chargeDate = chargeDate;    }    Date getDate(){        return _chargeDate;    }    double getValue{        return _value;    }    private Date _chargeDate;    private double _value;class Account...    double getFlowBetween(Date start, Date end){        double result = 0;        Enumeration e = _entries.elements();        while(e.hasMoreElements()){            Entry each = (Entry)e.nextElement();            if(each.getDate().equals(start) || each.getDate().equals(end) || (each.getDate().after(start) && each.getDate().before(end)))             {                  result += each.getValue;             }    }     return result;    }    private Vector_entries = new Vector();client code...double flow = anAccount.getFlowBetween(startDate, endDate);


新代码

class DateRange{    DateRange(Date start, Date end){        _start = start;        _end = end;    }    Date getStart(){        return _start;    }    Date getEnd(){        return _end;    }    boolean includes(Date arg){        return (arg.equals(_start)||arg.equals(_end)||(args.after(_start) && arg.before(_end)));    }    private final Date _start;    private final Date _end;}class Account...    double getFlowBetween(DateRange range){        double result = 0;        enumeration e = _entries.elements();        while(e.hasMoreElements()){            Entry each = (Entry) e.nextElement();            if(range.includes(each.getDate())){                result += each.getValue();            }        }         return result;    }






原创粉丝点击