良好的程序设计——时常重构代码

平时为了业务实现简单,难免写一些if else语句,例如常年堆积起来的业务逻辑代码如下,可以考虑重构使得结构更为清晰:

 

#define SHANGHAI 100
#define BEIJING  101
#define SHENZHEN 102

#define SHANGHAI_RATE 1.01
#define BEIJING_RATE 1.02
#define SHENZHEN_RATE 1.01

void oldFunction(int base_money,int state){

	int rate;
	int money;

	if(state == SHANGHAI){
		rate = SHANGHAI_RATE;
		money = rate * base_money;
	}
	else if(state == BEIJING || state == SHENZHEN){
		rate = (state == SHENZHEN)?SHENZHEN_RATE:BEIJING_RATE;
		money = rate * base_money;
	}
	else{
		rate = 1;
		money = base_money;
	}
}

 功能很简单,就是计算各个城市的某个比例值。可以重构为下面的代码,简洁明了

 

enum Province{
	SHANGHAI = 100,
	BEIJING,
	SHENZHEN
};

double lookup_rate(int province_id){
	//...
}

void newFunction(int base_money,int state){

	int rate;
	int money;

	rate = lookup_rate(state);
	money = rate * base_money;

}

你可能感兴趣的:(良好的程序设计)