Eclipse重构——Replace TypeCode with Class

《重构——改善既有代码》

Motivation

ü  类型码不是类型安全的,终究只是一堆数字或者一个字符串。使用类代替类型码,可以做更好的编译检查。

ü  如果类型码不影响宿主类的行为,则优先考虑使用Replace Type Code with Class

Mechanics

ü  为类型码建立一个类。类中应该定义一组静态变量,表示允许被创建的实例。

ü  修改源类实现,将类型码替换为上面新建的类。


Eclipse重构菜单中没有直接的对应选项,一般主要应用下面两个可逆操作,完成类型码变量的替换:

[Inline]                        CLAIMED  -->  PermissionState.CLAIMED

[Extract Constant]  PermissionState.CLAIMED --> CLAIMED

 


表示类型的Class,一般可以是enum, 静态内部类,或者一般的类。

1. 使用enum

 

         private enum PermissionState {
		REQUESTED("REQUESTEDd"),
		CLAIMED("CLAIMEDd"),
		DENIED("DENIED"),
		GRANTED("GRANTED");
		
		String mState;
		private PermissionState(String state) {mState = state;}
		private String getState() { return mState; }
// enum 有valueof(String arg)作为setState()
	}


2. 静态内部类

 

 

	static class PermissionState {
		public final static PermissionState REQUESTED = new PermissionState("REQUESTED");
		public final static PermissionState CLAIMED = new PermissionState("CLAIMED");
		public final static PermissionState DENIED = new PermissionState("DENIED");
		public final static PermissionState GRANTED = new PermissionState("GRANTED");
		public final static PermissionState UNKNOWN = new PermissionState("UNKNOWN");	
		
		String mState;
		// 构造函数应该private
		private PermissionState(String state) {
			mState = state;
		}

		public String getState() {
			return mState;
		}

	}

3. 一般类,意味着有继承体系

 

 

abstract class PermissionState {
	public final static String REQUESTED = "REQUESTED";
	public final static String CLAIMED = "CLAIMED";
	public final static String DENIED = "DENIED";
	public final static String GRANTED = "GRANTED";
	public final static String UNKNOWN = "UNKNOWN";	
	
	// String mState;  // no field mState
	public abstract String getState() ;  // override by subclass
	public void setState() { //switch REQUESTED, CLAIMED 
	}
}


一般两个特征总是必不可少,getState, setSate。 进一步,因为类型码是有限可列举的,所以setState最好是可以使用HashMap实现,static Hashmap<typecode,  class>.

 


over

完整的重构代码包here下载



 

posted @ 2013-04-14 11:15  xinyuyuanm  阅读(267)  评论(0编辑  收藏  举报