else ifの代わりにMapを使用する場合

2730 ワード

ビジネス開発では、判断を用いて異なるメソッドを呼び出したり、同じメソッドを呼び出して異なるパラメータを渡したりすることがよくあります.例:
public class IFELSE {
	
	public void doBusiness(String type){
		if ("1".equals(type)) {
			this.callRemoteProduce("method1");
		}else if ("2".equals(type)) {
			this.callRemoteProduce("method2");
		}else if ("3".equals(type)) {
			this.callRemoteProduce("method3");
		}else if ("4".equals(type)) {
			this.callRemoteProduce("method4");
		}else if ("5".equals(type)) {
			this.callRemoteProduce("method5");
		}else if ("6".equals(type)) {
			this.callRemoteProduce("method6");
		}else if ("7".equals(type)) {
			this.callRemoteProduce("method7");
		}else if ("8".equals(type)) {
			this.callRemoteProduce("method8");
		}else if ("9".equals(type)) {
			this.callRemoteProduce("method9");
		}else if ("10".equals(type)) {
			this.callRemoteProduce("method10");
		}
	}
	
	private void callRemoteProduce(String method){
		
	}
	
}

ブランチ条件が多すぎると、コードはかなり肥大化しているように見えます.この場合,分岐判定の代わりにmapを用いることが考えられる.例:
public class MapReplace {

	public void doBusiness(String type){
		
		Map map = new HashMap();
		map.put("1", "method1");
		map.put("2", "method2");
		map.put("3", "method3");
		map.put("4", "method4");
		map.put("5", "method5");
		map.put("6", "method6");
		map.put("7", "method7");
		map.put("8", "method8");
		map.put("9", "method9");
		map.put("10", "method10");
		
		this.callRemoteProduce(map.get(type));
	}
	
	private void callRemoteProduce(String method){
		
	}

}
ですが、上記のコードでは、メソッドを呼び出すたびにmapインスタンスオブジェクトが作成され、メソッドが終了するとmapが破棄されます.共通コードとしてmapをクラスの静的メンバー変数として使用することが考えられます.コードは次のとおりです.
public class MapReplace {

	private static Map map = new HashMap(){
		private static final long serialVersionUID = 1L;
		{
			put("1", "method1");
			put("2", "method2");
			put("3", "method3");
			put("4", "method4");
			put("5", "method5");
			put("6", "method6");
			put("7", "method7");
			put("8", "method8");
			put("9", "method9");
			put("10", "method10");
		}
	};
	
	public void doBusiness(String type){
		this.callRemoteProduce(map.get(type));
	}
	
	private void callRemoteProduce(String method){}

}