Tuesday, September 25, 2007

Idiomatic Code

So, as it turns out, I am in fact human. As such, I remember all things clever, cheesy, cliche and the like. Conversely, I quickly forget all things boring.

Whoever said that using the simplest, most boring subset of a language makes your code readable is nuts! It makes your code painfully boring and usually very bulky.

I write lots of Perl. Perl is full of useful shortcuts and clever idioms.

Disclaimer: Don't use excessive cleverness when there's no justification, unless you are the only person to ever see the code--in that case, the purpose might by simply to amuse yourself. But, by George, use the dang idioms when they _are_ useful!

That brings me to another rant. I believe that (in most circumstances) code should be readable by someone reasonably adept at the language. Don't write for the beginners (even if they might happen to see you code). Two reasons.

One. Advanced features are added to a language to make it better. Choosing not to use them to make your code more readable _only_ makes it more readable for beginners. Moreover, it needlessly handcuffs you.

Two. It's good to give beginners something to chew on. A healthy bit of clever code never hurt anyone ... at least not since the advent of Google. If you see some cryptic looking code, remember that Google has the answers.

2 comments:

Curtis said...

The internet knows everything, so just ask it! ;-)

I really like idiomatic Perl, too. So far it hasn't appeared to hurt anyone, but may have caused some annoyance.

However some recent work has made me really upset with one particular wart: Tie::RefHash should be the default behavior of a hash, but it isn't.

my %foo; tie %foo, 'Tie::RefHash'; is by no means a shortcut.

Keith said...

So, by default it looks like it converts the ref into a string like "HASH(0xBLABLA)" with some number (probably the virtual memory address) to make it a unique string.

Yeah, I guess that is kinda weak. On the other hand, I don't think I've ever needed to use references as hash keys.