examples for refactor

来源:互联网 发布:淘宝新开店铺怎么找 编辑:程序博客网 时间:2024/05/16 19:21

 讲多无谓,食多会滞,去片

详细请参考http://www.refactoring.com/catalog/index.html

要点: 

重构之前,首先检查自己是否有一套可靠的测试机制,这些测试必须有自我检验能力(self-checking).

重构技术是以微小的步骤修改程序,如果你犯下错误,很容易便可发现它.

更改变量名称,使代码更加清晰易读.任何一个傻瓜都能写出计算机可以理解的代码,唯有写出人类容易理解的代码,才是优秀的程序员.


定义常量代替hardcode的值:
Create a constant, name it after the meaning, and replace the number with it.
double potentialEnergy(double mass, double height) {
return mass * height * 9.81;
}

=====>
double potentialEnergy(double mass, double height) {
return mass * GRAVITATIONAL_CONSTANT * height;
}
static final double GRAVITATIONAL_CONSTANT = 9.81;

 

把方法的一部分变成一个静态的方法

 

 

Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.

 

class Order...double price() {double primaryBasePrice;double secondaryBasePrice;double tertiaryBasePrice;// long computation;...}

 

to be continued... 

 

Replace Method with Method ObjectYou have a long method that uses local variables in such a way that you cannot apply Extract Method

原创粉丝点击