Null object pattern to avoid null checks?

Recently, I came across a Null Object design pattern, and my colleagues say that it can be used to eliminate null pointers that are found throughout the code.

for example, suppose the DAO class returns customer information (to the CustomerVO value object). My main class is to extract firstName and emailId and send an email to the client.

...
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 a very simple example, but such null checks can quickly spread throughout your code based on the complexity of the value objects.

I have two problems with zero checking - they tend to make the code ugly and hard to read - less experienced developers introduce unnecessary zero checks when in fact they should throw exceptions. eg. in the above code, it would be better to throw an exception from getCustomer (), because if he cannot find the client information for this CustID, this indicates that the CustID was invalid.

okay, returning to the null object template, is it possible to use the null null CustomerVO object to hide the null check?

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

There would be no point. what do you think?

And what do you do to minimize null checks in your application.

+5
source share
5 answers

, , . , , null - , .

, , , .

+2

, , sendEmail() , ( sendEmail(), null).

, CustomerVO sendEmail(). , getCustomer() , null :

CustomerDAO.getCustomer(customerID).sendEmail();

sendEmail() , " " ( - ).

+3

getCustomer , , null?

, , , : , ? , ? , .

, - . , , .

" ", , . , "" , , , , ?

, , -, , , , , . - , , , NotFound.

+1

, . , , . , , , SRP.

CustomerVO custVO = CustomerDAO.getCustomer(customerID); .

-, , - null, . .

:

bool customerExists = CustomerDAO.exists(customerID);

if (customerExists)
{
  CustomerVO custVO = CustomerDAO.getCustomer(customerID);
  sendEmail(custVO.getFirstName(), custVO.getEmailID());
}
else
{
   // Do whatever is appropriate if there is no such customer.
}

}

, , , , , . , - , (, , does-not-exist-returns-null). , CustomerDAO.getCustomer(customerID) ArgumentException, . , Customer .

, , null. null : " , , ". null , . : " , , , ? GetCustomer , , Customer. null, , , . , , , .

+1

- NULL, NULL. . , , . , NULL .

NULL NULL. NULL, , .

NULL NULL, .

, DO Donts NULL.

http://www.codeproject.com/Articles/1042674/NULL-Object-Design-Pattern

0

All Articles