Consider the following code
Employee e = Db.getemployee ("Bob"); if null && E.istimetopay (today)) { e.pay ();}
Most people have been frustrated by forgetting to check for null. This technique, though common, is ugly and error-prone.
By letting Db.getemployee throw an exception instead of returning NULL, you can reduce the likelihood of an error. However, the Try/catch block compares null checks to be uglier.
You can use the Null object mode to resolve these issues. Typically, this pattern eliminates the need to check for null and helps simplify the code.
Employee becomes an interface that has two implementations. Employeeimplementation is the normal implementation. It contains all the methods and variables that the employee object is expected to have. When Db.getemployee finds an employee in the database, it returns an Employeeimplementation instance. Returns an instance of Nullemployee only if Db.getemployee does not find an employee in the database.
Conclusion
Those who have been using C-based language for a long time have been accustomed to returning null or 0 to a function for some kind of failure. We think that the return value of such a function needs to be tested. The NULL object mode changes this point. Using this pattern, we can ensure that the function always returns valid objects, in a timely manner when they fail. These represent failed objects that "do nothing".
Excerpt from: [Mei]robertc.martin, Micahmartin, Aaron, Sun Yu translation Agile Software Development principles, patterns and practices (C # revision) [M], People's post and Telecommunications publishing house, 2013, 254-256,
Agile Software Development –null Object mode