Boolean Variables

It's hard to misuse logical or boolean variables, and using them thoughtfully makes your program cleaner.

Use boolean variables to document your program. Instead of merely testing a boolean expression, you can assign the expression to a variable that makes the implication of the test unmistakable. For example, in the next fragment, it's not clear whether the purpose of the if test is to check for completion, for an error condition, or for something else:

Example 12-7. Java Example of Boolean Test in Which the Purpose Is Unclear

if ( ( elementIndex < 0 ) || ( MAX_ELEMENTS < elementIndex ) ||
   ( elementIndex == lastElementIndex )
   ) {


For details on using comments to document your program, see Chapter 32.

Cross-Reference ...

Get Code Complete, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.