Consider wrapper classes for optional data

Optional data is everywhere. Databases almost always have a significant fraction of their fields as optional (that is, as possibly NULL). In addition, the forms submitted in web applications can contain absent parameters. All web applications must deal with such possibly-null data as part of normal processing.

For modeling optional data, wrapper classes such as IntegerBoolean, and so on, seem to have a significant advantage over primitives (intboolean, and so on).  This is because both NULL database fields and missing request parameters naturally map to null object references. With primitives, there is no such natural mapping.

For instance, how would you model a person's age as an optional number, with no reasonable default value, using an int? The only means is to use a magic value such as -1. This should likely be avoided, if possible.

JDK 1.5 introduced a language feature called autoboxing, whereby primitives and wrappers are more or less interchangeable. However, they are not entirely interchangeable, since wrapper objects can be null, while primitives cannot.

See Also :
Avoid null if possible
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -