引入空对象
问题
因为有些方法会返回零
而不是真实的对象,你有许多检查零
在你的代码中。
解决方案
而不是零
,返回一个显示默认行为的空对象。
之前
if (customer == null) {plan = BillingPlan.basic();} else {plan = customer.getPlan();}
后
class NullCustomer extends Customer {boolean isNull(){返回true;}计划getPlan(){返回新的NullPlan();} //其他NULL函数。} //用null -object替换null值。客户=(订单。Customer != null) ?秩序。NullCustomer();//使用null对象,就像它是普通的子类一样。plan = customer.getPlan();
之前
if (customer == null) {plan = BillingPlan.Basic();} else {plan = customer.GetPlan();}
后
公共密封类NullCustomer:客户{公共override bool IsNull {get{返回true;}}公共覆盖计划GetPlan(){返回新的NullPlan();} //其他NULL函数。} //用null -object替换null值。顾客=订单。客户? ?新NullCustomer ();//使用null对象,就像它是普通的子类一样。plan = customer.GetPlan();
之前
if ($customer === null) {$plan = BillingPlan::basic();} else {$plan = $customer->getPlan();}
后
class NullCustomer extends Customer{公共函数isNull(){返回true;}公共函数getPlan(){返回新的NullPlan();} //其他NULL函数。} //用null -object替换null值。$customer = ($order->customer !== null) ?$order->客户:新的NullCustomer;//使用null对象,就像它是普通的子类一样。$plan = $customer->getPlan();
之前
如果客户为None:计划= BillingPlan.basic()否则:计划=客户。getplan ()
后
class NullCustomer(Customer): def isNull(self):返回True def getPlan(self):返回self. nullplan() #其他一些NULL函数。#用null对象替换null值。顾客=订单。使用null对象,就像它是普通的子类一样。plan = customer.getPlan()
之前
if (customer == null) {plan = BillingPlan.basic();} else {plan = customer.getPlan();}
后
class NullCustomer extends Customer {isNull(): boolean{返回true;} getPlan():计划{返回新的NullPlan();} //其他NULL函数。} //用null -object替换null值。让顾客=(订单。Customer != null) ?秩序。NullCustomer();//使用null对象,就像它是普通的子类一样。plan = customer.getPlan();
为什么重构
数十张支票零
让你的代码更长更丑。
缺点
- 摆脱条件句的代价是创建另一个新类。
如何重构
从所讨论的类中创建一个子类,它将执行空对象的角色。
在这两个类中,创建方法
isNull ()
,将返回真正的
对于空对象和假
对于真正的课程。找到代码可能返回的所有位置
零
而不是一个真实的物体。修改代码,使其返回一个空对象。找到与实类的变量进行比较的所有位置
零
.把这些支票换成催款支票isNull ()
.-
- 当值不等于时,原类的方法在这些条件下运行
零
,在空类中重新定义这些方法,并从其他的
这是部分原因。然后您可以删除整个条件,不同的行为将通过多态性实现。 - 如果事情不是那么简单,并且方法不能重新定义,那么看看是否可以简单地提取在a的情况下应该执行的操作符
零
值设置为null对象的新方法。调用这些方法而不是旧的代码其他的
为默认操作。
- 当值不等于时,原类的方法在这些条件下运行