返回 null 值,基本上是在给本身增长工做量,也是给调用者添乱。只有一处没有检查返回的是否为 null,程序就会抛 NullPointerException 异常。php
若是你打算在方法中返回 null 值,不如:api
以下的一段代码:wordpress
List<Employee> employees = getEmployees();
if (employees != null) {
for (Employee employee : employees) {
totalPay += employee.getPay();
}
}
之因此这样处理,天然 getEmployees() 可能返回 null,不妨对 getEmployees 函数作进一步的封装:函数
public List<Employee> getNoNullEmployees() {
List<Employee> employees = getEmployees();
if (employees == null) {
return Collections.emptyList();
}
return employees;
}
该模式的类图以下:spa
特例类一样继承自普通基类,只是其封装的是异常处理。code
咱们将以下两种不友好的(返回 null 或特殊值的异常处理),改造为特例类的处理方式:对象
// 不要返回 null
class MissingCustomer implements Customer {
public Long getId() {
return null;
}
}
// 不要返回特殊值
class MissingCustomer implements Customer {
public Long getId() {
return 0;
}
}
而是采用以下的方式(抛出有意义的特殊异常):blog
class MissingCustomer implements Customer {
public Long getId() throws MissingCustomerException {
throw new MissingCustomerException();
}
}
特例类封装了异常处理,有时当异常发生时,咱们并不想让程序直接崩溃退出,而是继续运行下去。此时在特例类中,还需给出当异常状况发生时,特例实例的异常处理方式:继承
class MissingSprite implements Sprite {
public void draw() {
// draw nothing or a generic something.
}
}