DEV Community

Discussion on: Refactoring If-else statement

Collapse
 
fnh profile image
Fabian Holzer • Edited

I personally would use the ternary operator over an if statement when I had a structure like this

if (condition) {
  return firstExpression;
} else {
  return secondExpression;
}


in which the equivalent to condition, firstExpression and secondExpression are rather simplistic expressions, e.g. constants, already calculated values or the evaluation of a function which is free from any side effects.

If I cannot refactor all of those expressions in a readable manner so that the resulting one-liner

return condition ? firstExpression : secondExpression;

does not exceed a certain column width, I would go for the if statement.

Also, if I would advise to abstain from nesting a ternary statement into one or both of the expressions. Even if hidden within a function, I would prefer to have the flow of control visible.

When there is really complex logic, it does not go away by obscurity.

Also, it would not be the first time, that I encountered, in which a lots of complex boolean logic is actually a simple polymorphic dispatch trying to come out of hiding.