Fabulous Adventures In Coding
Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric.
Quick, what's the difference between
If Blah = True Then Print "True!" Else Print "False!"
If Blah Then Print "True!"
Is there a difference?
Yes, there is a big difference. If
For example, what if
(ASIDE: But hold on a minute --
The same goes for numbers. When converted to a number,
It gets weirder. In JScript you can do something like this:
if (blah != null && blah.frob == 123)
and it works just fine. But in VBScript
If (Not Blah Is Nothing) And (Blah.Frob = 123) Then
What's going on is that VBScript is not logical. VBScript is bitwise. All the so-called logical operators work on numbers, not on Boolean values!
JScript has both logical (
(ASIDE: VB.NET has added lazy logic operators, at long last.)
This can lead to some strange situations if you're not careful. In VBScript, it is certainly possible for
If Blah Then
If Foo Then
to be both true, but
If Blah And Foo Then
to be false -- if
Given these potential "gotchas", what's the right thing to do? Here are my opinions of some best practices.
Conditional statements should always take Booleans. Or, in other words, use Booleans as Booleans, use nothing else as Booleans.
Suppose you've got a method that returns a number and you want to do something if it doesn't return zero. Don't do this, even though it does exactly what you want:
If Foo.Bar(Blah) Then
it's clearer to call it out and make the conditional take a Boolean:
If Foo.Bar(Blah) <> 0 Then
Conversely, if a value is a Boolean and you know that, there's no need to compare it. When I see
If Blah = True Then
what I think is that
Similarly with the "logical" operators. Don't mix-n-match -- either every argument should explicitly be a number, and you're doing bitwise comparisons, or every argument is a Boolean. Mixing the two makes the code harder to read and more bug-prone.
You saved me from growing gray hair!
Howcome the god of order (EL) rules over the domain of chaos (vbscript)?
PingBack from http://www.keyongtech.com/1949224-if-bpigscanfly-false-i-get