【Clean Code】 02

一、多用抽象形态描述数据

 

二、过程式代码与面向对象代码

过程式代码例子:

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 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值