25. Null Object

image

© Jennifer M. Kohnke

Faultily faultless, icily regular, splendidly null, Dead perfection, no more.

—Lord Alfred Tennyson (1809–1892)

Description

Consider the following code:

Employee e = DB.GetEmployee("Bob");if (e != null && e.IsTimeToPay(today))  e.Pay();

We ask the database for an Employee object named "Bob". The DB object will return null if no such object exists. Otherwise, it will return the requested instance of Employee. If the employee exists and is owed payment we invoke the pay method.

We’ve all written code like this before. The idiom is common because, in C-based languages, the first expression of the && is evaluated ...

Get Agile Principles, Patterns, and Practices in C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.