Java敏捷开发技巧之消除代码异味
http://tech.ddvip.com 2008年01月22日 社区交流
内容摘要:本文通过简单通俗的例子,告诉我们如何判断代码的稳定性和代码中的异类,并且如何重构此类代码。
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
if (shapes[i] instanceof Line) {
Line line = (Line)shapes[i];
graphics.drawLine(line.getStartPoint(),line.getEndPoint());
} else if (shapes[i] instanceof Rectangle) {
Rectangle rect = (Rectangle)shapes[i];
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
} else if (shapes[i] instanceof Circle) {
Circle circle = (Circle)shapes[i];
graphics.drawCircle(circle.getCenter(), circle.getRadius());
}
}
}
}
因为没有类别代码了,现在每个类(Shape,Line,Rectangle,Circle)里面的所有属性就不会有时用得到,有时用不到了。现在我们也可以给它们取一些好听点的名字了(比如在Line里面,p1这个属性可以改名为startPoint了)。现在四种异味只剩一种了,那就是,在drawShapes里面还是有一大串if-then-else-if。我们下一步,就是要去掉这长长的一串。
消除代码异味:如何去掉一大串if-then-else-if(或者switch)
经常地,为了去掉if-then-else-if或者switch,我们需要先保证在每个条件分支下的要写的代码是一样的。在drawShapes这个方法里面,我们先以一个较抽象的方法(伪码)来写吧!
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
if (shapes[i] instanceof Line) {
画线条;
} else if (shapes[i] instanceof Rectangle) {
画长方形;
} else if (shapes[i] instanceof Circle) {
画圆;
}
}
}
}
条件下的代码还是不怎么一样,不如再抽象一点:
责编:豆豆技术应用