zoukankan      html  css  js  c++  java
  • 提炼函数案例 一次循环中完成多个任务

    提炼函数案例 一次循环中完成多个任务

    参考

    修改代码的艺术 6.1 新生方法

    原始代码

    需求:只对没有发布过的entry进行发布日期并且添加到列表中。

    public class TransactionGate{
    	public void postEntries(List entries){
    		for(Iterator it = entries.iterator(); it.hasNext();){
    			Entry entry = (Entry) it.next();
    			entry.postDate();
    		}
    		transactionBundle.getListManager().add(entriesToAdd);
    	}
    }
    

    方式一

    public class TransactionGate{
    	/*
    	我们将2个操作混在一起了:一个是日期发送,另一个是重复项检查。
    	*/
    	public void postEntries(List entries){
    		List entriesToAdd = new LinkedList();
    		for(Iterator it = entries.iterator(); it.hasNext();){
    			Entry entry = (Entry) it.next();
    			if(!transactionBundle.getListManager().hasEntry(entry){
    				entry.postDate();
    				entriesToAdd.add(entry);
    			}
    		}
    		transactionBundle.getListManager().add(entriesToAdd);
    	}
    }
    

    方式二

    public class TransactionGate{
    	public List uniqueEntries(List entries){
    		List result = new LinkedList();
    		for(Iterator it = entries.iterator(); it.hasNext();){
    			Entry entry = (Entry) it.next();
    			if(!transactionBundle.getListManager().hasEntry(entry){
    				result.add(entry);
    			}
    		}
    		return result;
    	}
        /*
            当再出现一些针对非重复项的操作的时候,我们可以创建独立的方法来处理这些新的操作。
        */
        public void postEntries(List entries){
            List entriesToAdd = uniqueEntries(entries);
            for(Iterator it = entries.iterator(); it.hasNext();){
                Entry entry = (Entry) it.next();
                entry.postDate();
            }
            transactionBundle.getListManager().add(entriesToAdd);
        }
    }
    
  • 相关阅读:
    PHP之Trait详解
    PHP中__call()方法与重载解析
    PHP Closure(闭包)类详解
    PHP 核心特性
    回调函数
    php的各种 I/O流 以及用法
    关于php的buffer(缓冲区)
    php的运行原理、cgi对比fastcgi以及php-cgi和php-fpm之间的联系区别
    低功耗设计入门(一)——低功耗设计目的与功耗的类型
    从CMOS到触发器(一)
  • 原文地址:https://www.cnblogs.com/mozq/p/12248106.html
Copyright © 2011-2022 走看看