Consider the following blocks of pseudo code:
if( (conn=connectToDatabase())==FALSE ) { throw exception("could not connect to database"); } else { resultSet = conn.executeQuery("SELECT * FROM sometable"); }
and
conn = connectToDatabase(); if( conn==FALSE ) { throw exception("could not connect to database"); } else { resultSet = conn.executeQuery("SELECT * FROM sometable"); }
Both blocks of code perform the exact same function, but the first is considered poor practice because the assignment of the variable “conn” occurs in-line with the conditional statement. So, if they operate the same way, why is one bad and the other is not? Additionally, why is the one that performs the same operation with fewer lines of code bad?
It all stems from the use of the “=” assignment operator in the conditional statement. Take a look at this code:
a = 0; b = 1; // using conditional operator "==" to check for equality if( (a==b) ) print "a and b are equal"; else print "a and b are not equal"; print "a=".a." and b=".b; // using the assignment operator "=" in the wrong way if( (a=b) ) print "a and b are equal"; else print "a and b are not equal"; print "a=".a." and b=".b; a=1; b=0; // using the assignment operator "=" in the wrong way with different results if( (a=b) ) print "a and b are equal"; else print "a and b are not equal" // This program will output the following: // // a and b are not equal // a=0 and b=1 // a and b are equal // a=1 and b=1 // a and b are not equal // a=0 and b=0
In the example above, the output is unreliable because of the use of the assignment operator in the conditional. While any experienced programmer should be able to catch these problems right away, a novice may not see exactly what is happening here.
This leads me the conclusion that perhaps assignments in conditionals are not functionally bad, but they can be confusing. So, I would say that if you know what you are doing, and are confident that the people reading your code know what they are doing, these in-line conditionals may not be all bad. Just don’t teach them to anybody new to programming. It’s the whole “we’re professionals, don’t try this at home” principle.
But there’s even a problem with this line of thinking. I see these in-line assignments all the time in tutorials and various texts (teaching people programming). I can’t tell you the number of times I’ve taken boiler plate code from a book, and ended up with tons of compile time warnings complaining about assignment operators used in conditional statements.
I’ve worked on projects with people who would throw you out of the development team if you wrote code that looks like the first example above. Other times, I’ve seen every “while” loop in a program look like this.
I tend to believe that moderation and readability are the keys here. Use assignments like this where it makes sense; just don’t over do it simply because you can.
Thoughts?