2007-08-17

Java Blooper #1 Solution: Ternary Insanity

class Thing {
  private boolean _visible;

  boolean isVisible() {
    return _visible ? true : false;
  }
}

This code is unnecessarily using the ternary conditional operator when it's not needed.

Occasionally developers get so captivated by the expressiveness of this operator that they find it tempting to use it when it's not really needed. In this particular example, it almost looks like the original writer forgot that the type of the _visible field was boolean anyway and could just be returned directly:

class Thing {
  private boolean _visible;

  boolean isVisible() {
    return _visible;
  }
}

AddThis Social Bookmark Button

2 comments:

  1. That's a good one. Of course there's still good use for a ternary operator for situations like:

    int as_boolean = byteBuffer.getInt();
    boolean b = (as_boolean) ? true : false;

    I still find int to boolean conversion a drag sometimes, but I'm sure it's there for a good reason :P

    Cheers!

    ReplyDelete
  2. boolean b = (as_boolean==1) ? true : false;

    -----
    That's what I mean.. guess it tells how bad I am at Java!

    ReplyDelete