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) {
画出形状;
} else if (shapes[i] instanceof Rectangle) {
画出形状;
} else if (shapes[i] instanceof Circle) {
画出形状;
}
}
}
}
好,现在三个分支下的代码都一样了。我们也就不需要条件分支了:
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
画出形状;
}
}
}
最后,将“画出形状”这个伪码写成代码吧!
class CADApp {
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw(graphics);
}
}
}
当然,我们需要在每种Shape的类里面提供draw这个方法:
abstract class Shape {
abstract void draw(Graphics graphics);
}
class Line extends Shape {
Point startPoint;
Point endPoint;
void draw(Graphics graphics) {
graphics.drawLine(getStartPoint(), getEndPoint());
}
}
class Rectangle extends Shape {
Point lowerLeftCorner;
Point upperRightCorner;
void draw(Graphics graphics) {
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
graphics.drawLine(...);
}
}
class Circle extends Shape {
Point center;
int radius;
void draw(Graphics graphics) {
graphics.drawCircle(getCenter(), getRadius());
}
}
将抽象类变成接口
责编:豆豆技术应用