shreyas Kulkarni wrote:Can anyone please tell me what are the advantages of using Null object pattern? I tried to search too. I used it in my doubly linked list as first and last node(head and tail) but I am not able to figure out its use.
Thanks
Using the
Null Object Pattern you can avoid
null checks and
NullPointerExceptions
The
Null Object pattern is described in
Robert C. Martins book
Agile Software Development, Principles, Patterns, and Practices
Here is the example - let's assume that you have an application that check whether the user is authenticated:
and the code that returns the reference to the User object looks like this:
This way the code that checks whether our user is authenticated should look like the following snippet:
Checking whether the object is null is not only a boilerplate code but it can also give you a lot of bugs e.g. if you forget to check whether the object is
null.
And here the
Null Object can help you:
plus:
plus cleaner client code:
andi