Programming Tips: Make your Booleans Readable

The boolean variable is one of the simplest programming constructs in the programmer’s toolbox. Just two values: true or false. Throw it in an IF statement to execute one set of code in favor of another. Of course, things never seem to stay so simple once multiple conditions begin to overlap and create complicated webs of execution. There are techniques, however, to keep boolean logic as easy-to-read as possible.

Use Implicit Comparisons
Implicit boolean comparisons, i.e. not using explicit comparisons to the values true and false is a simple technique for increasing readability. This compact form of writing boolean comparisons not only saves a tiny bit of time when writing boolean comparisons, it also makes such logic read more like natural English.

Consider the small, but definite, increase in readability when changing a line of code like this:

if( bEnabled == true && bBufferReady == false )

into this:

if( bEnabled && !bBufferReady )

Use Positive Naming
When naming boolean variables, use positive names. This isn’t about making your code more life-affirming or encouraging; it’s a technique for maintaining readability. The English language doesn’t support double negatives for a good reason. Most people have a harder time reading multiple compounding negatives than non-compounded negatives.

Given the choice between:

if( bEnabled && bNotDone)

and:

if( bEnabled && !bDone)

I opt for the latter for nothing else if not to avoid having to later read through logic like this:

if( !bNotDone)

Delineate Blocks of Logic with Parentheses
Taking blocks of related logic and tying them together can make long, overly-complicated streams of boolean tests (usually the result of late-night hacks to handle annoying edge cases) infinitely easier to read. Consider the following:

if( bFileReaderEnabled && bFileHandleValid && bBufferSafe && !bBufferEmpty || !bFileReaderEnabled )

versus:

if( ( ( bFileReaderEnabled && bFileHandleValid ) && ( bBufferSafe && !bBufferEmpty ) ) || !bFileReaderEnabled )

The parentheses explicitly identify three major conditions for passing this IF statement which were only implicitly defined in the earlier example: tests related to file handling, tests related to buffer validity, and a fall-through when the file reader is not enabled. During later refactoring, these blocks become obvious candidates for being abstracted behind functions as they identify coherent blocks of logic you may be likely to use in other places as well:

if( ( FileHandleIsValid() && BufferIsReady() ) || !bFileReaderEnabled )
このトピックに関しての記事をもっと読みたい方はここをチェックしてみてください: ゲーム開発
  • 言語

  • Sponsored Links

  • Rob's Portfolio

    Games Writing Contributions

コメントはまだありません。

コメントをどうぞ