Beyond Code

There is more to Programming than programming...

Home   |   News   |   Articles   |   Resources   |   Projects   |   About


Boolean Variables Considered Harmful

Boolean variables are frequently used to encode business-domain type information, such as male/female, english/spanish, foreign/domestic, etc. Rarely is this a good choice of data-type.

Booleans are not Type-Codes

The first reason is that few business-domain types are truly restricted to two values only. Even the male/female distinction has a tendency to morph towards a multi-valued abstraction, including "unknown", "not applicable", and "answer refused". Once the choice to represent the information using a boolean variable has been made, it is difficult to adapt the system to such requirement changes.

The second reason has to do with the semantics implied by a boolean variable. Strictly speaking, only boolean expressions are truly boolean, i.e. statements, which have a clear truth value. The value of a variable gender is never true or false!

This indicates the proper way to deal with type information and booleans. Type codes should be of a multi-valued type (integers, enumerated types where available, even strings). The information in these codes can then be made available using truly boolean expressions, such as isMale(), isFemale(), etc.

Unambiguous Names for Boolean Values

Lastly, the sometimes remaining confusion "What does true stand for in this expression?", can be reduced through adopting an unambiguous naming convention, by explicitly mentioning all possible alternatives, as in: isMale_notFemale().

This convention is particularly helpful in those circumstances, where type information has been encoded into a boolean variable after all.

http://www.beyondcode.org/articles/booleanVariables.html Version 1.1 (2003/01/10 02:23:41)

Copyright © 2002-2006 by Philipp K. Janert. All rights reserved.