in reply to ?: = Obfuscation?
Terse Good, Obfuscated Bad
I have been reading Perl Best Practices by thedamian. When I first read what he had to say about using ?: I was only half listening (if that makes sense ;) - but I was struck by how he laid out the following code. At first I didn't like how it was spread out but as I traced the logic I realized it was beautiful.
Code From: Perl Best Practices, Damian Conway PBP @ O'Reilly# When their name is... Address them as... my $salute = $name eq $EMPTY_STR ? 'Customer' : $name =~ m/\A((?:Sir|Dame) \s+ \S+) /xms ? $1 : $name =~ m/(.*), \s+ Ph[.]?D \z /xms ? "Dr $1" : $name ;
My big gripe has already been addressed above, ?: has to be used in the correct circumstances. The way I generally use it is usually as a one line choice of functions:
$conditional ? foo() : bar();
or
$conditional ? foo($arg_1) : foo($arg_2);
What I don't like to see is extra processing in the choices:
$conditional ? $foo++ : $foo += 2;
When there are assignments involved it can get confusing and I would agree that a regular if else block is more appropriate and more easily expanded with extra logic.
??|| IMHO (I'm sorry) but that is a messy solution to a non language problem. The problem is not that the ?: is hard to see, it is that it gets abused... Kinda like forcing all cars to have square wheels to keep drunks from driving.
I hope this 2¢ helps :)
--Brig
Update: Added link to Damian's node.
Update: The reason I am tolerant of the "extra processing" in the first example is that the processing is a string search. When the search hits, the code directly to the right executes. Therefore I believe this is a very readable construct. The only drawback is that the regex must be reasonably short, I am not strict on the 80 column rule but it is a good rule.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: ?: = Obfuscation?
by sgt (Deacon) on Dec 05, 2006 at 00:08 UTC |