Agile Software Development –null Object mode

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.