Your skill will accomplish
what the force of many cannot
A new idiom -or- I Hate Unlessby erikharrison (Deacon)
|on Aug 22, 2004 at 20:59 UTC||Need Help??|
I hate unless.
I have code like this:
There are two problems with this. First, that block goes on for about 10 lines, but it's mostly about handling an error condition - I'd rather it not distract from the flow of the code. Second, that unlink should make you sit up and notice. But it gets tucked inside the parens, and doesn't get enough attention. We could put it the success/fail in a temp var, which does make the unlink a little more noticable, but at the expense of an extra var, and a little excessive verbosity (I crime I commit already in speech ;-).
unless tends to guard error conditions I find. This always trips me up, especially when rereading my own code, since I tend to skim stuff I wrote. I either skip the unless because I know it's error handling, or get halfway through the block and go "Wait a minute" and scroll back up to reorient myself. I started using ifs on negated conditions, but that unary not is even more invisible when wrapped in parens.
If I push the error handling into a sub or function somwhere, this is pretty ideal:do_error($file) unless unlink $file;
as the function name makes it good and self documenting, and it doesn't interrupt the flow when I'm digging around.
But now I've picked up maintainance on a bunch of code that has been growing both in terms of quantity and quality over the last 5 years. Because of the design of the code (not to mention my deadlines) refactoring the error code out into a seperate function really isn't possible, and the code has a tendency to blend unreadable line noise with hiding important action in obscured places. This is the idiom I came up with to keep myself sane.
It's simple, it's readable, and it puts the scary unlink out there at the beginning of the line. My only problem with it is I got tripped up by the semicolon the first couple of times. I've managed to purge most of the more frusterating unlesses from my new code, and I think readablity improves considerably. Does any one else use this idiom? If you had to maintian my code later would this bother you? What other tricks have people come up with to keep the code oriented on the main action as opposed to exceptions?
Light a man a fire, he's warm for a day. Catch a man on fire, and he's warm for the rest of his life. - Terry Pratchet