重构读书笔记-9_7-Introduce_Null_Object

2019-07-14  本文已影响0人  MR_Model

重构第九章

7.Introduce Null Object(引入Null对象)

你需要再三检查[某物是否为null value]。将null value(无效值)替换为null object(无效物)。

Example:

class Site...
    Customer getCustomer() {
        return _customer;
    }
    Customer _customer;

class Customer...
    public String getName() {...}
    public BillingPlan getPlan() {...}
    public PaymentRistory getHistory() {...}
class PaymentHistory...
    int getWeekDelinquentInLastYear();

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 weeksDelinquent;
if(customer == null) weeksDelinquent = 0;
else weeksDelinquent = customer.getHistory().getWeeksDelinquentInLastYear();

End:

class NullPaymentHistory extends PaymentHistory...
    int getWeeksDelinquentInLastYear() {
        return 0;
    }
class NullCustomer...
    boolean isNull() {
        return true;
    }
    public BillingPlan getPlan() {
        return BillingPlan.basic();
    }
    public String getName() {
        return "occupant";
    }
    class NullCustoemr...
        public PaymentHistory getHistory() {
            return PaymentHistory.newNull();
        }
class Customer...
    public boolean isNull() {
        return false;
    }
    public String getName() {...}
    public BillingPlan getPlan() {...}
    public PaymentRistory getHistory() {...}

class PaymentHistory...
    int getWeekDelinquentInLastYear();

    Customer customer = site.getCustomer();
    BillingPlan plan = customer.getPlan();  
    String customerName = customer.getName();
    int weeksDelinquent = customer.getHistory().getWeeksDelinquentInLastYear();

Conclusion:

Introduce Null Object(引入Null对象)将Null Object作为class的一个子类,这样可以直接通过多态机制,来区分空对象和其他对象的区别,去除了多余的条件式,使得程序简洁一些;同时这项手法,可以让你对不同的空值所要进行的操作进行一个分类,即不同的空值有着不同的反应,而不需要添加新的条件式和型别码。

注意

重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!
上一篇 下一篇

猜你喜欢

热点阅读