Should you define a null/unknown value for Java enums?

This is actually an example of applying Null Object pattern. IMHO it is always better to have a dummy object rather than null. For instance you can add dummy methods to null-object rather than scattering your code with null-checks all over the place. Very convenient.

Also the name of the enum gives you some additional semantics: is the price unknown, undefined, not trustworthy, not yet known? And what does it mean if the price is null?

UPDATE: As Aaron Digulla points out, Null Object pattern requires memory. But this isn’t actually the case most of the time. In the traditional implementation you typically have a singleton for Null object used everywhere as there is no need for separate instances. It gets even better with enums because you get singleton semantics for free.

Another point is that null reference and reference to some object occupy the same amount of memory (say 4 bytes on 32-bit machine). It is the object being referenced that occupies some extra memory. But if this is a singleton, there is practically no memory overhead here.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)