It's more than a house. It's an adventure.

Friday, April 07, 2006

When < just doesn't cut it

While doing some more work on my documentation project today, I stumbled across this little gem:isPositive = (x == (x = Math.abs(x)));I had to scratch my head for a minute before I realized what it really does. All it does is set isPositive to true if x is positive, and false if x is negative.

It's basically a conditional without a conditional statement. If I could find my copy of Learning Perl, I'd compare it to a similar "shortcut" I read in there many years ago. This code reads like a Perl junkie wrote it and wanted to show off.

This code could just as easily, yet far more understandably, be written as follows:isPositive = true;
if (x < 0) {
isPositive = false;
}
At least that can be understood at a glance. But maybe it's just too obvious. Obfuscation is good, right kids?

2 Comments:

  • "If I could find my copy of Learning Perl, I'd compare it to a similar "shortcut" I read in there many years ago. This code reads like a Perl junkie wrote it and wanted to show off."

    I'd really appreciate it if you could find your copy of the llama to locate the code in question. I don't believe we ever wrote code just to show off. If code was included, it was for instructional purposes.

    By Blogger Randal L. Schwartz, at 4/25/2006 10:57 AM  

  • I think you misunderstood. I understand completely that the example in the llama book was for instructional purposes.

    My contention is with the JavaScript code that exists in the system I'm maintaining - the code is not commented and unless someone is already familiar with a similar technique (from the Perl book), it's simply obfuscation for the sake of doing something fancy.

    The JS code in question simply reminded me of a "how to write an if without using if" that I recalled reading in either the llama or camel books. In the book, it was documented, and made sense. In this application, with no documentation, I spent 5 minutes trying to figure out "what" - and then 15 minutes with "why?"

    By Blogger dakboy, at 4/25/2006 12:05 PM  

Post a Comment

<< Home