Optimize ternary operator

后端 未结 6 1991
野的像风
野的像风 2021-02-03 18:49

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is th

6条回答
  •  情话喂你
    2021-02-03 19:44

    That's just horrible code.

    • It's badly formatted. I don't see the hierarchy of the expression.
    • Even if it had good formatting, the expression would be way too complex to quickly parse with the human eye.
    • The intention is unclear. What's the purpose of those conditions?

    So what can you do?

    • Use conditional statements (if).
    • Extract the sub-expressions, and store them in variables. Check this nice example from the refactoring catalog.
    • Use helper functions. If the logic is complex, use early returns. Nobody likes deep indentation.
    • Most importantly, give everything a meaningful name. The intention should be clear why something has to be calculated.

    And just to be clear: There's nothing wrong with the ternary operator. If used judiously, it often produces code that's easier to digest. Avoid nesting them though. I occasionally use a second level if the code is crystal clear, and even then I use parentheses so my poor brain doesn't have to do extra cycles decyphering the operator precedence.

    Care about the readers of your code.

提交回复
热议问题