美文网首页
重构读书笔记-10_9-Introduce_Parameter_

重构读书笔记-10_9-Introduce_Parameter_

作者: MR_Model | 来源:发表于2019-07-23 09:39 被阅读0次

    重构第十章

    9.Introduce Parameter Object(引入参数对象)

    某些参数总是很自然地同时出现,以一个对象取代这些参数。

    Example:

    class Entry...
        Entry(double value, Date charegeDate) {
            _value = value;
            _chargeDate = chargeDate;
        }
        Date getDate() {
            return _chargeDate;
        }
        double getValue() {
            return _value;
        }
        private double _value;
        private Date _chargeDate;
    
    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 = Account.getFlowBetween(startDate, endDate);
    

    Analyse:
    Date start和Date end以[一对值]表示[一个范围],本项重构的价值在于缩短了参数列的长度。
    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;
        }
    class DateRange...
        boolean includes(Date arg) {
            return (arg.equals(_start) || arg.equals(_end) || (arg.after(_start) && arg.before(_end));
        }
    

    Conclusion:

    Introduce Parameter Object(引入参数对象)使用一个对象包装所有这些数据,再以该对象取代他们,缩短了参数列的长度,可以是代码更具一致性,降低了代码的理解难度和修改难度。
    同时使用了这项重构手法之后,更加容易发现一些[可被移到新建class]的行为,可以减少很多重复代码。

    注意

    重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!

    相关文章

      网友评论

          本文标题:重构读书笔记-10_9-Introduce_Parameter_

          本文链接:https://www.haomeiwen.com/subject/ozinlctx.html