Java敏捷开发技巧之消除代码异味

http://tech.ddvip.com   2008年01月22日    社区交流

内容摘要:本文通过简单通俗的例子,告诉我们如何判断代码的稳定性和代码中的异类,并且如何重构此类代码。

  现在,看一下Shape这个类,它本身没有实际的方法。所以,它更应该是一个接口:

interface Shape { 
void draw(Graphics graphics);
} 
class Line implements Shape { 
... 
} 
class Rectangle implements Shape { 
... 
} 
class Circle implements Shape {
... 
} 

  改进后的代码

  改进后的代码就像下面这样:

interface Shape { 
void draw(Graphics graphics);
} 
class Line implements Shape { 
Point startPoint;
Point endPoint; 
void draw(Graphics graphics) { 
graphics.drawLine(getStartPoint(), getEndPoint()); 
}
} 
class Rectangle implements Shape { 
Point lowerLeftCorner; 
Point upperRightCorner; 
void draw(Graphics graphics) { 
graphics.drawLine(...); 
graphics.drawLine(...); 
graphics.drawLine(...); 
graphics.drawLine(...); 
}
} 
class Circle implements Shape {
Point center;
int radius; 
void draw(Graphics graphics) { 
graphics.drawCircle(getCenter(), getRadius()); 
}
} 
class CADApp { 
void drawShapes(Graphics graphics, Shape shapes[]) {
for (int i = 0; i < shapes.length; i++) {
shapes[i].draw(graphics);
}
}
}

  如果我们想要支持更多的图形(比如:三角形),上面没有一个类需要修改。我们只需要创建一个新的类Triangle就行了。

责编:豆豆技术应用

正在加载评论...