NOTE: This document may be circulated or quoted from freely, as long as the copyright credit is included.
I keep seeing these patterns in code written by students, clients, and even a few textbook authors:
if (condition)
result = true;
else result = false;
| if (condition)
return true;
else return false;
|
or even, to comply with misguided local standards, with standalone brackets consuming eight lines on a screen or printed listing:
if (condition)
{
return true;
}
else
{
return false;
}
|
After staring at that for a minute, the programmer realizes that it's just a long-winded way of saying either of these:
result = condition; |
return condition; |
Actually you may have to stare at it for more than a minute if the condition is
a messy expression with lots of ands (&&),
ors
(||), nots
(!), and
parentheses.1
Logical ("Boolean") expressions have been an essential part of all2 but the earliest programming languages, and are well supported in the C-family (C, C++, Java, C#). One programming manager confided that he didn't think his staff was comfortable with logical expressions and thought that redundant testing and setting was more "natural". But logical thinking is what computer programming is all about. Do we really want people3 who don't understand it implementing solutions to our complex problems?
I don't want to see that pattern in either student exercises or clients' programs.
Nor do I want to see this silly
variation: condition ? true : false
which
is endorsed by a well-known C++ programming
textbook.
2—Algol (1960), APL (1962), PL/I (1964), and Pascal (1969) supported logical expressions, as has nearly every modern language.
3—In 1959 some of COBOL's designers argued that the language had to cater to programmers who didn't understand parenthesized numeric expressions!
Return to IDI Home Page
Return to Technical articles
Last modified October 7, 2008