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);
        }
    }
    
  • 相关阅读:
    fatal error C1083: 无法打开包括文件:“iostream.h”: No such file or directory
    Dan Saks
    '=' : left operand must be lvalue 左值和右值
    sizeof使用
    stream.js :一个新的JavaScript数据结构
    Kibo:键盘事件捕捉高手
    c中不能用引用的办法
    分布式版本控制工具:git与Mercurial
    非常好的BASH脚本编写教程
    Handler让主线程和子线程进行通信
  • 原文地址:https://www.cnblogs.com/mozq/p/12248106.html
Copyright © 2011-2022 走看看