Ad
  • Custom User Avatar
  • Default User Avatar

    A good heuristic for deciding between the ternary operator and if/else is whether you are choosing between side effects or between calculations. For example:

    if (employee.isBoss()) {
        status = employee.notifyDirectReports();
    } else {
        status = employee.notifyBoss();
    }
    

    Here it should be clear that the choice is between two actions. Contrast with:

    pay = employee.bonusActive() ? BONUS_RATE * employee.hours() + employee.bonusAmount()
                                 : BASE_RATE * employee.hours();
    

    In this case we're choosing one of two calculations. You could rewrite the first example to use the ternary operator, but then it's easier to miss the side effects.

    There is a strong tendency for beginning programmers to want to use language constructs to make code terser and denser than it should be, without considering the factor of readability. It comes down to the question of whether you have the experience and/or discipline to use the ternary operator when it's appropriate and not just because you want to see if you can fit something on one line. If you're not disciplined enough to consider the pros and cons each time you use it, then it's best to err on the side of verbosity. The same argument holds for the ++ and -- operators and other shortcuts.

    That's not to say that you personally aren't good enough or experienced enough, but if you think about a policy that has to cover a whole company or a whole open source project, you need rules that will prevent the worst programmer in the group from writing bad code, and so you end up with more always / never prescriptions.

    One last thing: Different languages vary widely on how verbose coders tend to be. Things like the ternary operator and using short-circuiting boolean operators for side effects is much more tolerated in JavaScript, for example. The best advice is to try to match what most people are doing for your given language and platform, since it will make it easier to adapt to any given code base in that language, and easier for others to give feedback on or contribute to your code.