Should programmers use boolean variables to "document" their code?
I'm reading McConell's Code Complete, and he discusses using boolean variables to document your code. For example, instead of:
if((elementIndex < 0) || (MAX_ELEMENTS < elementIndex) ||
(elementIndex == lastElementIndex)){
...
}
He suggests:
finished = ((elementIndex < 0) || (MAX_ELEMENTS < elementIndex));
repeatedEntry = (elementIndex == lastElementIndex);
if(finished || repeatedEntry){
...
}
This strikes me as logical, good practice, and very self-documenting. However, I'm hesitant to start using this technique regularly as I've almost never come across it; and perhaps it would be confusing just by virtue of being rare. However, my experience is not very vast yet, so I'm interested in hearing programmers' opinion of this technique, and I'd be curious to know if anyone uses this technique regularly or has seen it often when reading code. Is this a worthwhile convention/style/technique to adopt? Will other programmers understand and appreciate it, or consider it strange?
Splitting an expression that's too nested and complicated into simpler sub-expressions assigned to local variables, then put together again, is quite a common and popular technique -- quite independently of whether the sub-expressions and/or the overall expression are boolean or of just about any other type. With well-chosen names, a tasteful decomposition of this kind can increase readability, and a good compiler should have no trouble generating code that's equivalent to the original, complicated expression.
Some languages that don't have the concept of "assignment" per se, such as Haskell, even introduce specialized constructs to let you use the "give a name to a subexpression" technique (the where
clause in Haskell) -- seems to bespeak some popularity for the technique in question!-)
I have used it, though normally wrapping boolean logic into a reusable method (if called from multiple locations).
It helps readability and when the logic changes, it only needs changing in one place.
Other will understand it and will not find it strange (except for those who only ever write thousand line functions, that is).
I try to do it wherever possible. Sure, you are using an "extra line" of code, but at the same time, you are describing why you are making a comparison of two values.
In your example, I look at the code, and ask myself "okay why is the person seeing the value is less than 0?" In the second you are clearly telling me that some processes have finished when this occurs. No guessing in the second one what your intent was.
The big one for me is when I see a method like: DoSomeMethod(true);
Why is it automatically set to true? It's much more readable like
bool deleteOnCompletion = true;
DoSomeMethod(deleteOnCompletion);