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 )
   ) {
   ...
}

Cross-Reference

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

Cross-Reference ...

Get Code Complete, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.