代码整洁之道—对象和数据结构
一.数据结构VS对象
数据结构是用于保存数据的特殊类,例如Car,Animal,Event,Employee,Company,Customer 等。这些数据通常在其他类的开头声明为实例变量。这个类的方法不应该做任何真正重要的工作,否则数据结构类不再是数据结构了!其函数只有getters和setters,其数据是公开的。而普通对象,像MainActivity,ListAdapter,Calculator,Iterator等则隐藏自己的数据,公开自己的方法。
二.代码示例:
public class Square {
public Point topLeft;
public double side;
}
public class Rectangle {
public Point topLeft;
public double height;
public double width;
}
public class Circle {
public Point center;
public double radius;
}
public class Geometry {
public final double PI = 3.141592653589793;
public double area(Object shape) throws NoSuchShapeException {
if (shape instanceof Square) {
Square s = (Square)shape;
return s.side x s.side;
}else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle)shape;
return r.height x r.width;
}else if (shape instanceof Circle) {
Circle c = (Circle)shape;
return PI x c.radius x c.radius; }
throw new NoSuchShapeException(); }
}
在段代码中Square,Rectangle,Circle是数据结构,而Geometry类是Object
优点:如果需要添加更多方法,只需在Geometry类中添加它们。
缺点:如果需要添加更多数据结构,则必须更改Geometry类中的所有函数。
下面我对其进行改进,代码如下:
public class Square implements Shape {
private Point topLeft;
private double side;
public double area() {
return side x side;
}
}
public class Rectangle implements Shape {
private Point topLeft;
private double height;
private double width;
public double area() {
return height x width;
}
}
public class Circle implements Shape {
private Point center;
private double radius;
public final double PI = 3.141592653589793;
public double area() {
return PI x radius x radius;
}
}
在上面代码中,没有数据结构,只有类。
优点:如果要添加更多形状,则无需更改任何旧代码。
缺点:如果要添加新方法,则必须在所有类中添加。
本文探讨了数据结构与对象的区别,通过代码示例展示了如何将数据结构转化为对象,以实现更好的代码组织和扩展性。改进后的代码能够轻松添加新形状,无需修改现有代码。
1万+

被折叠的 条评论
为什么被折叠?



