空对象模式以避免空的检查? [英] Null Object Pattern to avoid Null checks?

查看:198
本文介绍了空对象模式以避免空的检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到了Null对象的设计模式,同事们说可以用这个方法去掉整个代码中遇到的空指针检查。



,例如假设DAO类返回Customer(在名为CustomerVO的值对象)中的信息。我的主要课程是提取firstName和emailId并发送电子邮件给客户。

  ... 
CustomerVO custVO = CustomerDAO.getCustomer(customerID);
if(custVO!= null){// imp,否则我们可能在下一行中获得空ptr异常
sendEmail(custVO.getFirstName(),custVO.getEmailID());
}
...

这是非常简单的例子,但是这样的null检查可以根据价值对象的复杂性快速传播到整个代码中。



我有两个问题与空检查,
- 他们倾向于代码丑陋,难以阅读
- 较少经验的开发人员放置不必要的空检查实际上他们应该抛出异常。例如。在上面的代码中,最好从getCustomer()本身抛出异常,因为如果它不能找到给定的CustID的客户信息,它表示CustID无效。



好的,回到null对象模式,我们可以使用一个'null'CustomerVO对象来隐藏null检查吗?

  CustomerVO {
String firstName =;
String emailID =;
}

这不是有道理的。你觉得怎么样?



你应该怎么做才能最小化你的应用程序中的空值检查。

解决方案

在这种情况下,空对象可能是不适当的,因为默认值可能在实际上隐藏了异常。如果你发现自己必须检查你的安全性是否为null执行一些其他活动,空格式不会买你任何东西。



正如你所说的许多新开发者花时间尝试保护他们的代码免受比停止程序更糟糕的异常情况。


Lately I have come across Null Object design pattern and my colleagues say it can be used to do away with the null pointer checks that are encountered throughout the code.

for e.g suppose a DAO class returns information on Customer (in a value object called CustomerVO). My main class is supposed to extract the firstName and emailId and send email to customer.

...
CustomerVO custVO = CustomerDAO.getCustomer(customerID);
if(custVO != null) { // imp, otherwise we may get null ptr exception in next line
     sendEmail(custVO.getFirstName(), custVO.getEmailID());
}
...

This is very simple example, but such null checks can quickly spread throughout your code based on the complexity of the value objects.

I have two issues with null check, - they tend tmake the code ugly and hard to read - lesser experienced developers put unnecessary null checks when in fact they are supposed to throw exceptions. for e.g. in above code, it would be better to throw exception from getCustomer() itself because if its not able to find customer info for given CustID, it indicates the CustID was invalid.

okay, coming back to null object pattern, can we use a 'null' CustomerVO object to hide the null check?

CustomerVO {
   String firstName = "";
   String emailID = ""; 
}

Don't it would make sense. what do you think?

And what are the things you follow to minimize null checks in your app.

解决方案

In this case a null object may be inappropriate since the default may infact hide what is in actuality an exception. If you find yourself having to check to see if your have safe null to perform some other activity the null pattern isn't buying you anything.

As you stated many new developers spend time trying to protect their code from exception situations that are worse then a halting program.

这篇关于空对象模式以避免空的检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆