Literals/Constants on LHS


This is something I learnt long back…years ago. As a part of “best coding practices” when C/C++ ruled programming world. This is a simple yet powerful tip for programming in C/C++, JavaScript and even Java (though condition must be boolean here)-

You should always put literal/constant or value on the LHS and variable on the RHS in if condition for equality!

i.e. if should always be –
if(100 == count) {
//.....
}

or

if(true == deleteAll){
//.....
}

The rationale here is simple – accidently you might use single assignment operator “=” instead of comparison operator “==”, and in case of languages where if condition does not only accept boolean (like C, C++), this could result in unintentional assignment instead of comparison; and worse still your compiler won’t be able to catch it in these languages – or it will go unnoticed in scripts like JS. However, when you use literal/constant on LHS; even an accidental, unintentional assignment is not possible. i.e. you simply cannot have this, compiler will show an error –

if(100 = count) {
//.....
}

but may not flag error here (depending on the language and the compiler) –

if(count = 100) {
//.....
}

and that’s exactly the point! You let compiler do the work of finding such problems instead of realizing it at runtime and then spending hour debugging and tracking down one small unintentional assignment whereas it should have an equality comparison.

There is counter-argument that says that with languages like Java you can only have “boolean” for “if” condition. But this approach still makes sense in Java for some reasons :

(1) Consider boolean comparison itself in Java, what would happen here (ignore compiler warning for assignment) if following code is unintentionally added –

if(deleteAll = true){
//.....
}

something like this will help you here, right? –

if(true = deleteAll){
//.....
}

(2) You seldom code in only one language. There are times when you need to come up with small snippet in JavaScript or groovy and all I mentioned above will hold valid there.

Developing this approach will help you in the long run – it’s not about any one particular language/technology. This is more about inculcating good programming habits, approaches that will help you in the long run irrespective of language & technology! Makes sense? I hope it does! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s