Hilton Giesenow's Jumbled Mind

Thursday, August 12, 2004

Boolean Operator Short-circuiting.

I was showing someone a code snippet today that included an AndAlso statement and they were quite surprised to discover what it was. It got me thinking back to when I discovered AndAlso and OrElse short circuiting. I remember reading a posting at the time where someone asked why it wasn't the default behaviour and the more I think about it the more I agree.

They way these statements work, for example is as follows. If you have a string variable strName and you want to determine if it is (a) Not Null and (b) not = "Bob". The following statement will fail:

If Not IsDBNull(strName) And strName <> "Bob" Then

The reason for this is that BOTH checks are evaluated and if the variable is in fact null an exception will occur on the last part. What we really want is: Check if the variable is not null THEN ALSO (i.e. if the first part evaluates to True) check that it is not equal to "Bob". This would need two separate If statements to accomplish otherwise. The AndAlso statement accomplishes this and OrElse performs a similar operation versus the Else statement. However, I am hard-pressed to think of many common situations when you would definitely want to execute both statements. Perhaps if one is calling one's own Boolean function it would make sense. Otherwise, I definitely think these should be the defaults. First of all, if you think about it "AndALSO" makes more sense in english (as does OrELSE). In addition, the current behaviour is more likely to trip a beginner up and it leads to unneccesary code.

Any opinions on this? Anyone agree / disagree?


  • By Anonymous Anonymous, at 5:49 PM  

  • Learn how to quickly create an RSS feeds with our RSS feeder, for high link popularity and ultimately better search engine rankings.

    By Anonymous Anonymous, at 5:09 PM  

  • Among these magnificent benefits is the chance to be able to promote your business, any business,

    By Anonymous Anonymous, at 12:41 PM  

  • to all of the major RSS feed directories on the Internet.

    By Anonymous Anonymous, at 2:55 AM  

Post a Comment

<< Home