Your supposition about the code being a security leak may or may not be true depending on the language you are using. In C code it could be a problem (particularly because in C a boolean is just an int that is non-zero or zero)--but in most strongly typed languages (i.e. runtime type checking) if the passwordCheck
variable was declared as a boolean, there is no way to assign something else to it. In fact, everything in an if
predicate must resolve to a boolean, whether you use the boolean operators or simply use the value. If you managed to have another type of object bound to passwordCheck
the runtime would throw some type of illegal cast exception.
Simple if/else constructs are much easier to read than if/if constructs--and less prone to inadvertant problems if someone tries to flip the construct. Let's take the same example for a second:
if(passwordCheck == false) {
denyAccess();
}
if(passwordCheck) {
letThemIn();
}
The meaning of the mutually exclusive clauses you want to execute above is lost. That's what the if/else construct conveys. Two mutually exclusive branches of execution, where one of them will always run. This is an important part of security--ensuring there is no way to letThemIn
after you've called denyAccess
.
For the purpose of code clarity, and for the purpose of ensuring critical sections are most protected, they should be inside the primary clause (the if
part). The default non-compliant behavior should be in the alternate clause (the else
part). For example:
if(passwordCheck) {
letThemIn();
} else {
denyAccess();
}
NOTE: in working with different languages, I've developed a coding habbit that does help avoid the question of "what if it's a string?" Essentially, it is to put the constant first in the boolean expression. For example, instead of checking passwordCheck == false
I am checking false == passwordCheck
. This also avoids the accidental assignment problem possible in C++. Using this approach, the compiler will complain if I type =
instead of ==
. In languages like Java and C#, the compiler would treat the assignment in the if clause as an error, but C++ will happily accept it. That's why I also tend to do null checking with the null
first.
If you routinely change languages placing the constant first is very helpful. However, on my team it is opposite the coding standard and the compiler catches those problems anyway. It can be a hard habbit to break.
I know that passwordCheck is likely to be a boolean...
What do you mean? In any strong-typed language.passwordCheck
will be whatever you want it to be. – Bobby Dec 20 '10 at 11:23else
statements... – gablin Dec 20 '10 at 12:43passwordCheck()
possibly not being boolean (which may be a reasonable concern), and then you blame it onelse
? I don't see what problems theelse
causes. – David Thornley Dec 20 '10 at 15:21