|There's more than one way to do things|
Ternary operators: a hinderance, not a helpby Tanalis (Curate)
|on Aug 09, 2005 at 15:16 UTC||Need Help??|
It's been a long while since I've felt inspired or passionate enough about something to write a meditation about it.
I found myself in a situation this morning where I needed to assign a number or zero to a variable depending whether another variable was set or not.
Now, my normal reaction to this would be to use an if to write something like this:
.. and then I remembered the ternary operator existed, and that I could save myself code, and some keystrokes, by using
instead. It was early, and my brain saw this as a reasonable option, probably due to lack of coffee.
Now, in this contrived example, it's pretty obvious to see what's going on and what's being assigned where. Consider, however, extending this to a more complex real-world scenario, involving accessing elements in deep data structures, subroutines to format numbers, regular expressions and the like. Clarity, maintainability and even code elegance are quickly lost, all for the sake of a few keystrokes and a newline, unless the person doing the coding is very careful about how he uses the operator.
Where the use of the if makes it obvious what the value of the variable is being set to, I found that even a little while later, the meaning of the ternary operator was significantly less clear. I tried a few other examples, and found that the same assertion held for all of them: the ternery operator hinders, not helps, the understanding of code.
Turning to my now-trusty copy of Perl Best Practises, hoping to find some rule to make this a lot clearer, TheDamian's suggestion is to format cascaded ternery operators in columns(1). I agree that this helps to undo some of the damage done to the code's clarity, but I still think there's a way to go. If I'm honest, I don't think that I completely buy TheDamian's explainations as to why the ternary operator is advantageous over an if construct - sacrifices seem to be made in both options - and I'd rather sacrifice compactness over maintainability.
I talked with a couple of colleagues about this, and found that opinion seems to be divided one way or the other: either you love boolean ? value_if_true : value_if_false, or you hate it.
Why choose one over another? I guess it's another one of those situations that come down to personal preference. There's more than one way to do it, after all.
What do others think? Is this simply a preference issue, or am I missing something?Joost's feedback.