Safer Java: Constants First

Here is a simple change in your Java development style that will save you a lot of time: When comparing something against a constant, always put the constant first. Examples:

    if (0 == x)...

    public final static String RUN = "run";
    if (RUN.equals (mode))...

That will look strange at first because we’re used to have the constants on the right hand side (from assigns). So what’s the advantage of this? There are three:

  1. It will save you a lot of NullPointerException when using equals().
  2. It’s more readable in big if/else “switch-alikes”, when you compare a variable against a lot of values.
  3. It avoids the accidental assignment as in if (x = 0) (which should have been if (x == 0) … and if you can’t see the difference between the two, you really should always do it this way!) because if (0 = x) generates a compile time error.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: