Tip of the day: Logical Syntax :)

Neat little way of thinking about logical vs syntax errors. Ever had to hunt high and low for a reason why something is not working as intended? Ever had an if statement that always evaluates as true? Yes? So, all of you are probably aware that if…

Neat little way of thinking about logical vs syntax errors.

Ever had to hunt high and low for a reason why something is not working as intended? Ever had an if statement that always evaluates as true?

Yes?

So, all of you are probably aware that if the IF statement evaluates as true all the time chances are you’ve used an assignment operator instead of a comparison (aka = instead of ==). Thing is, in a mountain of code it can be a nightmare to find that out, so how do you prevent it from ever being a problem?

Think backwards.

Instead of:
IF ( favChocolate == “buttons”){ echo “He likes Cadbury buttons!” }

Use:

IF (“buttons” == favChocolate){ echo “he likes Cadbury buttons!” }

What does this do? Well in non-interpreted languages if you accidentally type:

If (“buttons” = favChocolate){… then it will result in a build error. You can’t assign a variable to a string.

If its interpreted it’ll result in a runtime error as again, you can’t assign a variable to a string J

Thus eliminating the guess work involved in finding logical errors in your tests.

Leave a Reply