|XP is just a number|
Re: ?: = Obfuscation? (value)by tye (Sage)
|on Dec 01, 2006 at 17:25 UTC||Need Help??|
?: gives back a value. Using it in a situation where you don't use the return value is a good indication that you should probably just replace it with if/else. Although Perl allows if/else to give back a value as well, using it in that way is usually a good way to surprise people.
So I use ?: only for fairly simple cases of just picking between two values (or perhaps a few more, via multiple uses of ?:). I use if/else if the primary point is not simply giving back either this or that value. For cases of picking between some values that aren't quite simple, I use sub. Of course, using sub for a simple case of picking between two values is also acceptable and is sometimes a much better choice than inlining a ?:.
Note that using ?: as it was intended (to return a value) also usually means that you don't run into precedence problems and so you usually won't need parens (which can quickly become visual clutter if many are required).
And, using if/else is often appropriate or even better than ?:. For example, in:
The more verbose version might be preferred just for style reasons, because it is easier to add comments to without impacting readability, or because it is suspected that future maintenance will complicate the two blocks to the point of making ?: inappropriate anyway.
Of course, the ?: has some advantages that can be important sometimes. Obviously, it is more compact. Although making code too compact can make it harder to read, I also find that making code too expansive can make it hard to read. That can distract the viewer by giving too much space to items of relatively little importance or it can make it impossible to view an entire logical structure and get the feel for the "big picture" of it.
Also, $x is not repeated in the compact form. This becomes even more of an advantage in a fairly common example like this:
Note that we had to repeat $x three times for the sake of using if/else.
And you might have good reason to prefer to use if/else as part of a way to simply return either this or that value:
The biggest advantage of ?: is for cases like:
Finally, there are rare cases where restrictions make using the rather surprising ability of if/else to give back a value quite appropriate. For example: