L-exp Mobile

Clarity Over Cleverness - But What Is Clever?

I think it's fair to say that we developers like the Ruby language. I recall back in my Java days reading articles with the code example written in Ruby. Ruby always seemed more expressive and elegant.

It is this expressiveness and elegance that I have come to love and now strive for in any piece of code I write. I can't say that I always achieve it, but the intent is there.

I like to be able to read code. I especially like to read code where the intent is clear. Cleverness is normally at the cost of clarity. Cleverness normally warrants a #comment.

I don't think anything I have said so far is particularly new. I would go so far to say that Clarity over Cleverness is considered best practice. When we deliberately choose to opt for clever we have hopefully considered the trade off's. In other words we have a damn good reason for it :-)

But sometimes I come across code where I am unsure. Initially the code is unclear but after I understand what it is doing I am left wondering it is the code being clever or just me being dumb? I came across some today. Have a look at it and keep hold of your initial thoughts as you think about what it is doing before reading on.

1 if (comments = @attributes['comments']) && comments.is_a?(String) 2 @attributes['comments'] = comments.split(" ") 3 end

So what happened for you? Did you think they've made a mistake with the conditional?

My initial reaction was they've accidentally used an = instead of == (a mistake I used to make in PERL all the time!). I then had to reread it and think hard about what it was actually doing. Then I thought wow, it's kind of cool, saves a line of code (sort of). But was it worth it?

It had already cost me a few minutes of time looking at it. Then I fired up irb to see it working. Another few minutes of my time.

I have not come across this use before so I don't believe it's an idiom, is it? What do you think?



Options:   Save This | Share
Viewed 0 times
Published 3 months ago
By Shane Mingins
From Resource Elc Tech Blog in lists:
Best Ruby on Rails Blogs

Menu

by Genís