Skip to main content

NullObject Pattern: Misleading Name

No replies
pdoubleya
Offline
Joined: 2004-02-09
Points: 0

I think the name NullObject Pattern is misleading, although Joshua points out that others used it before him. I think the name should be something like SafeDefault or DefaultInstance, which is its purpose.

Although the examples he gives serve to replace checks for null instances, there is a reason why those instances might be null. Given the context of the request for the object, the instance cannot be created, has not been previously created, or something like that. What he proposes is there should be some "safe" default instance that can be accessed if the particular, specific instance is not available.

This would also happen if you requested an instance from a Factory class, and the parameters you specified for the instance dont resolve to an actual or "instatiatable" object.

Some are objecting that an NPE is a useful exception, because it clearly indicates that the original request for the instance was not well specified. I think that is only true in some cases. Specifically, we need to ask, if the instance is not available or cannot be instantiated, is there a safe default we can use which will not affect normal operation of the application?

In some cases, there will not be a safe default. Suppose we request a database connection using invalid connection parameters. The correct response to the request should be either a specific exception (CantConnectException) or a NPE (I prefer the former). Thats because there likely will be no safe default database connection we can use that would make any sense--we need a specific database with specific tables and data in it.

In other cases, we may be able to use a safe default--those would be the examples that Joshua gives in the article.

IMO!
Patrick