Keeping constants on the left

It is often said that when using null checks, or equating variables, the constant values must be kept on left hand side.

Until now, I’ve believed that it is a myth. But today I sat down to peel out the truth.

Why one should follow it?

Lets take the following example,

String var = null;


var.equals(“constant”) // NullPointerException

“constant”.equals(var) // False, No NullPointerException

This happens because the equals method is usually written to include the null check in it. Saving us from the dreadful null pointer exception in this particular scenario. Also, the redundant null check could be avoided. (One in equals and the other in our explicit null check)

Thus, whenever using a method inside a conditional statement. Keeping the constant on the left hand side is a good practice.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: