代码整洁之道三(对象和数据结构)

代码整洁之道—对象和数据结构

一.数据结构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;
        }
    }

在上面代码中,没有数据结构,只有类。
优点:如果要添加更多形状,则无需更改任何旧代码。
缺点:如果要添加新方法,则必须在所有类中添加。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值