一、多用抽象形态描述数据
二、过程式代码与面向对象代码
过程式代码例子:
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 = 30141592653589793;
public double area(Object shape) throws NoSuchShapeException{
if(shape instanceof Square){
Square s = (Square)shape;
return s.side * s.side;
}else if(shape instanceof Rectangle){
Rectangle r = (Rectangle)shape;
return r.height * r.width;
}else if (shape instanceof Circle) {
Circle c = (Circle) shape;
return PI * c.radius * c.radius;
}
throws new NoSuchShapeException;
}
}
如果现在有新的需求,需要添加一个新的形状,则写多一个形状类的同时,在Geometry的area()里面追加一个else if ,这样便改动了area()方法。
如果又有新的需求,需要添加一个新的计算方法,则直接在Geometry的里面添加一个方法,这样不会改动原有方法。
面向对象(多态)代码例子:
public interface shape{
double area();
}
public class Square implements shape{
private Point topLeft;
private double side;
public double area(){
return side*side;
}
}
public class Rectangle implements shape{
private Point topLeft;
private double height;
private double width;
public double area(){
return height*width;
}
}
public class Circle implements shape{
private Point center;
private double radius;
public final double PI = 30141592653589793;
public double area(){
return PI * radius * radius;
}
}
如果现在有新的需求,需要添加新的形状,则只用实现shape接口写即可,不会改动原有方法。
如果又有新的需求,需要添加一个新的计算方法,则所有的形状类都要添加新的方法。
过程式与面向对象各有利弊,根据实际情况使用。
三、错误处理
1、使用异常而非返回码
2、使用 try..catch..finally
3、自定义异常,并给异常添加描述
4、别返回null值
参考书籍:
《代码简洁之道》—— Robert C. Martin