一而再,再而三地检查对象是否null
public class Site {
private Customer customer;
public Customer getCustomer() {
return customer;
}
}
public class Customer {
private String name;
private BillingPlan plan;
private PaymentHistory history;
public String getName() {
return name;
}
public String getPlan() {
return plan;
}
public String getHistory() {
return history;
}
}
public class PaymentHistory {
private Integer weeksDelingquent;
public int getWeeksDelingquentInLastYear() {
return weeksDelingquentInLastYear;
}
}
Customer customer = site.getCustomer();
BillingPlan plan;
if (customer == null) {
plan = BillingPlan.basic();
} else {
plan = customer.getPlan();
}
//...
String customerName;
if (customer == null) {
customerName = "occupant";
} else {
customerName = customer.getName();
}
//...
int weeksDelingquent;
if (customer == null) {
weeksDelingquent = 0;
} else {
weeksDelingquent = customer.getHistory().getWeeksDelingquentInLastYear();
}
重构:将null值替换为null对象
注意:空对象一定是常量,它们的任何成分都不会发生变化。因此可以使用Singleton 模式实现。
public interface Nullable {
public boolean isNull();
}
public class Site {
private Customer customer;
public Customer getCustomer() {
return customer == null ? Customer.newNull() : customer;
}
}
public class Customer implements Nullable {
private String name;
private BillingPlan plan;
private PaymentHistory history;
public boolean isNull() {
return false;
}
public static Customer newNull() {
return new NullCustomer();
}
public String getName() {
return name;
}
public String getPlan() {
return plan;
}
public void setPlan(BillingPlan plan) {
this.plan = plan;
}
public String getHistory() {
return history;
}
}
public class PaymentHistory implements Nullable {
private Integer weeksDelingquent;
public boolean isNull() {
return false;
}
public int getWeeksDelingquentInLastYear() {
return weeksDelingquentInLastYear;
}
public static PaymentHistory newNull() {
return new NullPaymentHistory();
}
}
public class NullCustomer extends Customer {
public boolean isNull() {
return true;
}
public String getName() {
return "occupant";
}
public String getPlan() {
return BillingPlan.basic();
}
public String getHistory() {
return PaymentHistory.newNull();
}
}
public class NullPaymentHistory extends PaymentHistory {
public boolean isNull() {
return true;
}
public int getWeeksDelingquentInLastYear() {
return 0;
}
}
Customer customer = site.getCustomer();
BillingPlan plan = customer.getPlan();
//...
String customerName = customer.getName();
//...
int weeksDelingquent = customer.getHistory().getWeeksDelingquentInLastYear();