Tip of the Week #184 – Tricky Conditions in IF Statements

Tip of the Week #184 – Tricky Conditions in IF Statements

Project Manager Torben Nielsen has a tip of the week with a specific target audience: Developers at a level of beginner to intermediate.

Sometimes you need to have more than one condition in your IF statement.

Normally you will just add a AND or OR operator to handle this and we are all good.

So, when it goes something like this no problem:

// <Ok code Start>

HasRecord := ItemRec.GET(ItemNo);

IF HasRecord AND (ItemRec.Description <> ”) THEN

// <Ok code End>

Note that both conditions are using values both known prior to the execution of the IF statement.

All good.

But… sometimes we come across code that is constructed like this:

// <Bad code Start>

IF ItemRec.GET(ItemNo) AND (ItemRec.Description <> ”) THEN

// <Bad Code End>

Several issues here!

First, readability! – not quite clear what you expect from the code, second, and more important,

…due to the way compilers work, you cannot always be sure that the conditions are executed from left to right.

And some compilers may even skip checking remaining conditions when result can been established, based on evaluating just one/a few conditions.

So, the above code may be executed right to left, meaning that you are checking the ItemRec.Description <> ” before actually (if at all) retrieving the record using the ItemRec.GET(ItemNo).

Or worse, if in a loop, ItemRec.Description <> ” may even be checking the previously fetched record!

To avoid all these potential issues, structure your code like this, splitting the conditions to separate IF statements:

// <Excellent code Start>

IF ItemRec.GET(ItemNo) THEN

IF ItemRec.Description <> THEN

// <Excellent code End>

Ahh… much better looking and more readable, and no doubt on what happens first, and then second.

This also gives you an easy opportunity to expand the code to handle the situation of what should happen if ItemRec.GET fails, by using BEGIN … END;

That was it!

Happy coding out there!

Thank you Torben!