re: We don't need a ternary operator VIEW POST

re: I think if statements are something separate, assuming the ternary isn't being abused to introduce logic flow into a program. if statements are ab...

Most languages use if for flow control so they encourage you to write boolean reductions for your data and to think of your decisions in terms of booleans. Whereas my human brain doesn't tend to actually think in Discrete Logic. Sometimes I even draw truth tables to make sure it will produce the expected result. The problem isn't really with the language feature provided by if, but perhaps with our overuse of the construct.

So I guess the fundamental question is: does using if reduce the expressiveness of your solution? And if so, what are the alternatives?

When I am writing a guard clause, if's expressiveness is probably fine. But when I am making business decisions, using if for flow can feel pretty bad at times. As far as the 2nd question, I think really the only alternative to using if is to write higher level code so it is not needed. Those implementations will vary based on the problem and paradigm. Examples I've used: union types or shallow inheritance to make discrete data states.

As far as the relationship, ternary is just an expression + operator version of if. Being an operator makes it more cryptic, but I consider it being an expression to be a good thing. I tend to write in expression-based languages, so in my mind it is the exact same capability as if. (In F#, if is an expression and no ternary operator exists.) From that perspective, putting "too much" in the ternary operator feels appropriately bad because it is highlighting problems with expressing solutions in terms of booleans. Whereas the same code with a statement-based if may feel more comfortable than it should. Not that I am in favor of ternary. I think your alternative is better. I guess I was just isolating a problem that most people easily identify with ternary, but is less obvious with if. That being the lack of human legibility of boolean-based flow control.

code of conduct - report abuse