Snippet Tutorial – Short Circuiting

Typically here at Switch On The Code, we cover something that is language specific, focusing on syntax solutions that help you with your projects. Today we are going to step back a bit and talk about a feature of programming that I think is neat and worthy of talking about. This feature is known as Short-Circuiting, and it may elude some of you beginners out there.

Perhaps we should begin with an explanation. Short-Circuiting is a term used to describe logical operators that only evaluate if the first does not. For example, lets take the following PHP snippet:

$one = true;
$two = false;

if($one == null && !$two)
  echo "GO IF!";

In the context of short-circuiting, the second logical test would never get evaluated because the first one in the line already failed. Variable $two doesn’t even have to exist in this example, because it is technically never used.

You may be asking yourself “Why would I need this?” and in some languages don’t even offer this feature. Trust me though, it is extremely useful when you are dealing with large systems, with highly dynamic data. In the example above, it is clear that if you have short-circuiting available, it can be used when one variable relies on another. My favorite example of this is when you are using a Dataset, because it is very clear why you would use something like this:

DataSet data = GetSomeData();

if(data.tables.count > 0 && data.tables(0).rows.count > 0)
{
  //Do Something with data…
}

Normally you would never see something like this, mainly because if there are no tables, then there is certainly no rows in table 0. However, since we used short-circuiting operators, we can make both tests in one if statement. If there are no tables in the dataset, then it will “short-circuit” and break from the if statement. This way we can order our logical tests so that one can depend on the other evaluating.

It is an extremely useful feature that comes in handy more than it seems like at first. Now the only thing we need to know is what languages support short-circuiting. This is quickly remedied from a quick look at the wikipedia page provided in the references below.

One language that makes is quite obvious that is supports short-circuiting is the classic vb. The normal logical operators are And and Or, while the short-circuiting operators are AndAlso and OrElse. Most other languages use && and || as their short-circuiting operators. In the end you may just have to do some research to find out if your preferred language supports it.

So this is going to wrap it up for this tutorial. I hope you have been enlightened, and are learning about it before you need it. Just remember, when you need coding help, all you have to do is Switch On The Code.

Leave a Reply

Your email address will not be published. Required fields are marked *