Optimize ternary operator

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)