DEV Community

Discussion on: Why I'm phasing out ternary statements

Collapse
 
costinmanda profile image
Costin Manda • Edited

I think your frustration comes from cases where you neatly define a variable using a ternary operator and then you have to do something for one of the branches of the condition. It feels like duplicating code if you add a new if afterwards and it looks ugly if you turn the ternary into an if/else block and then add the action in one of the branches. I feel you.

However, I think that if we put readability first, then checking a condition twice is the least of our problems. I would much prefer:

var backgroundColor = IsTransparent()
  ? Color.Transparent
  : this.defaultBackgroundColor;
if (!IsTransparent()) {
  DrawSomething();
}

than the alternative:

Color backgroundColor;
if (IsTransparent()) {
  backgroundColor = Color.Transparent;
} else {
  backgroundColor = this.defaultBackgroundColor;
  DrawSomething();
}

One block defines a value, the other is executing an action. I think we should be allowed to use the hammer of our choice for each individual nail.