RSS

Code Tip to Prevent Assignment Errors in Conditionals

During my Comp Sci lecture yesterday, my professor mentioned a convention he follows that he learned over time in his development with Java (this tip applies to almost all languages though). You might be familiar with the usual if statement as seen below:

if(tester == null) {
   // something
}

If you’ve programmed for any amount of time, you probably have come across the mistake of doing an assignment instead of a comparison (ie using one = instead of ==). If you do something like below, you’re in serious trouble.

if(tester = null) {
   tester.setValue("A");
}

Whoops. You totally screwed yourself, and it’s not immediately evident either when debugging (imagine large nested ifs or if the value set to null is used much later on in your code than in the conditional). To solve this problem my professor suggested that you swap the order of your comparisions. As you know, assignments are done right to left, so the value to the right of the equal sign is assigned into the variable on the right.

testInt = 15; // 15 put into testInt

And because most languages don’t let you do the reverse:

15 = testInt; // throws an error

Our conditionals that are written with the comparisons swapped will run just fine if you correctly use == but throw an error when you use one equal sign.

if(null = tester) {
   // throws an error here
}
if(null == tester) {
   // still works fine
}

I hope this tip might save you future angst at the debugger.

Have anything to say?

« Receiving Enter & Arrow Key Presses From NSSearchField | Online Puzzles for Keeping Your Brain Sharp »