Please don’t nest ternary operators.

For one of my courses, we are given a framework of java compiler and our homework is to extend it.While doing this, I decided to read up some implementations because I couldn’t figure out what the methods did, and then I encountered this

    private static String descriptorFor(Class cls) {
        return cls == null ? "V" : cls == void.class ? "V" : cls
            .isArray()
            ? "[" + descriptorFor(cls.getComponentType())
            : cls.isPrimitive() ? (cls == int.class
                ? "I"
                : cls == char.class ? "C" : cls == boolean.class
                    ? "Z"
                    : "?") : "L" + cls.getName().replace('.', '/')
                + ";";
    }

Now maybe this is a commonly used Java idiom, but I am not a Java guru and presumably, this is for inexperienced programmers, ie. students, to read. So my reaction to that is WTF. I would certainly prefer nested if-elses, or even better,  using multiple return points. I think this is the first time I really saw a chunk of code that really does not agree with me.

Advertisements

3 Comments on “Please don’t nest ternary operators.”

  1. Tom says:

    It’s not an idiom. It’s just poor whitespace choices.
    Try removing the newlines, then put in a newline and an indentation after ?’s and just a newline after :’s.
    So something like this
    condition ?
    firstThing :
    secondCondition ?
    secondThing :
    lastThing;

    • Tom says:

      apparently spaces at the beginning of lines get cleared out so, I’ll try again.
      cond ?
      -> thing
      -> cond2
      ->-> thing2
      ->-> last

      where -> is a tab or spaces or whatever you use to indent.

    • jdshu says:

      Yeah wordpress does some annoying things, unfortunately.

      That would make a lot more sense, you’re right. Thanks, for the suggestion. I’ll remember to do that if I ever write similar code 🙂

      I think another problem is that nesting so many conditionals is bad anyway, coupled with the ternary operator which is cryptic without a good C-style background.


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