Hacker News new | past | comments | ask | show | jobs | submit login

If/else chains are worse because they allow problems like this:

    if (cond) {
      var1 = x;
    } else if (cond2) {
      var2 = y;
    } else {
      var1 = z;
    }
Did you notice the second block assigned to var2 instead of var1? Best case it’s a gotcha for anyone reading the code later. It might be a bug by the original author; we can’t tell at a glance if this behaviour was intentional. Ternaries remove this problem. The intent of the author is clearer, and (with proper formatting) there’s no gotchas for anyone reading the code later.



If I understand correctly, what you're really advocating isn't ternary vs if/else, but expressive conditionals vs imperative conditionals. A statement that is something vs a statement that does something. Using expressions instead of imperative code that mutates state is a staple of functional programming, and is basically always preferred where possible. In some languages you can do this:

  var1 = if cond {
    x
  } else if cond2 {
    y
  } else {
    z
  }
Which in my opinion is strictly better than using a ternary, if the language supports it.


Yes exactly. I mentioned in another comment that rust allows this, and having used it I think the best of all worlds.

My favorite part is that its easy to add extra statements into the conditional blocks if you want. Doing that with ternaries requires either using the comma operator, repeating the condition on another line or refactoring the whole expression back out into if-else chains. All of those options are bad.


True.

When in Java, I've gotten into the habit of using the final initializer to mitigate these kinds of issues, like this:

    final T var1;
    if (cond) {
      var1 = x;
    } else if (cond2) {
      var2 = y;
    } else {
      var1 = z;
    }
In this specific case, the compiler will catch the lack of initialization in the second block. It's also very helpful with a complicated/nested conditionals to guarantee that you initialize the variable through every code path.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: