Wednesday, 8 December 2004

Simple tricks

One thing that I liked about coding with other people is the small but important tricks that people show you while you are pair-programming (or at least working closely together). One that Karen showed me a while ago is in what order you do a .equals() in Java.

Most people why they want to compare a variable against a constant would do something like this (forgive the formatting):
if (myLocalVar.equals(STATIC_CONSTANT)) {...}
Now this is all well and good except what happens if myLocalVar is null? Your code that wasn't protected throws a NullPointerException over something that you should have guarded against.

You could something like:
if (myLocalVar != null && myLocalVar.equals(STATIC_CONSTANT)) {...}
but that gets messy and more likely someone would forget to put that guard (or screw up the != for ==, ...)

Here is the simple trick. If you have a constant, you know that will never be null (assuming you didn't set it up to be null), so write the code like this:
if (STATIC_CONSTANT.equals(myLocalVar)) {...}
This protects you against myLocalVar being null and works (because equals is symmetric)

I like tricks and thought that I would share. ;-)

3 comments:

  1. That's a little bit like another trick I saw.
    If you want to say something like:
    if(variableName == 5)
    you can easily make a mistake and type:
    if(variableName = 5)
    which, in C/C++ at least, would compile fine, never crash, but always return true.
    so, you should get in the habit of writing it lik this:
    if(5 == variableName)
    which doesn't allow you to make mistakes of putting = instead of ==. This can help prevent a lot of hard to spot mistakes

    ReplyDelete
  2. Along the same vein, I got used to writing:
    if (false == condition)
    instead of
    if (condition == false)
    because of that C++ style (thanks Corel!), which I even prefer to
    if (!condition)
    since the ! is not as easy see the difference with
    if (condition)
    when skimming code... however, I don't usually write
    if (condition == true)
    just
    if (condition)

    ReplyDelete
  3. For Kibbee's point, with a good IDE (I think Eclipse does it), you can enable warnings for things like that...

    ReplyDelete