个人感觉简化函数调用不属于重构,二是开发就应该注意的事情。

函数改名

函数改名,应该遵循一些原则。例如函数名字应该指明做了什么而不是怎么做。

Add Parameter(添加参数)

Remove Parameter(移除参数)

Separate Query from Modifier (将查询函数和修改函数分离)

Parameterize Method(令函数携带参数)

其实就是提炼函数,我再写代码中遇到很多,都懒得提炼,现在看来,需要提炼一下了。

Replace Parameter with Explicit Methods (以明确函数取代参数)

和上一步相反,你有一个函数,其中完全取决于参数值而采取不同行为。这时候就提取出不同的函数。

Preserve Whole Object(保持对象完整)

如果你的函数参数是某个对象的多个值,还不如把函数参数改为对象。

Replace Parameter with Methods(以函数取代参数)

对象调用某个函数,并将所得结果作为参数,传递给另一个函数。 而接受该参数的函数本身也能够调用前一个函数。

int basePrice = _quantity * _itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice (basePrice,discountLevel);

这里 discountedPrice() 方法需要两个参数,而 第二个参数 discountLevel 也是调用 getDiscountLevel() 计算得到的。还不如在 discountedPrice() 方法中调用 getDiscountLevel()。

Introduce Parameter Object(引入参数对象)

某些参数总是经常一起出现,就将他们作为参数对象传入。

Remove Setting Method(移除设值函数)

类中的某个字段应该在对象创建时被设值,然后就不再改变。 去掉该字段的所有设值函数。

Hide Method(隐藏函数)

重构的时候要注意有些函数的可见度。

Replace Constructor with Factory Method (以工厂函数取代构造函数)

这个经常需要用在某些类似单例模式的类。另外就是前面所说的,有关类型码的操作。这个必须熟悉,因为经常用到:

class Employee {
	private int _type;
	static final int ENGINEER = 0;
	static final int SALESMAN = 1;
	static final int MANAGER = 2;
	Employee(int type){
	_type = type;

}

这种代码改为

class Employee {
	private int _type;
	static final int ENGINEER = 0;
	static final int SALESMAN = 1;
	static final int MANAGER = 2;
	private Employee(int type){
	_type = type;
	
	static Employee create(int type){
		return new Employee(type);
	}
}

static Employee create(int type){
	switch (type){
		case ENGINEER:
			return new Engineer();
		case SALESMAN:
			return new Salesman();
		case MANAGER:
			return new Manager();
	default:
		throw new IllegalArgumentException("Incorrect type code value");
	}
}

这个 switch 是可以接受的,但是如果要移除,只能通过反射。

Encapsulate Downcast(封装向下转型)

其实这个再java有了 泛型就用的不多了,但是还是要注意。在调用端不应该强制转型。

Replace Error Code with Exception (以异常取代错误码)

这个是开发应该注意的事情。

Replace Exception with Test(以测试取代异常)

实际上就是指异常不能作为常用情况的判断,只能作为很少发生情况下的判断。