loading...

Clever code

bertilmuth profile image Bertil Muth ・1 min read

Do you remember „clever code“ you wrote, to show off or because you thought it was cool, and it could have been way more simple?

I remember when learning C++, I loved the increment and assignment operators, so I wrote ridiculous lines like:

int c = (a=b) * d++

Discussion

pic
Editor guide
 

Not "clever code" but "clever design".

I'm at present working with an API that returns times (not datetimes, just the hours part) in this format:

{"open": "08:20:00", "close": "300"}

I asked about the meaning of "300" to the developers that wrote the API and the answer they gave me is: well, we compute the closing hour with this PHP algorithm:

date('H:i', strtotime('08:20:00') + (300*60))
# result is "13:20"

So, instead of writing the actual closing time, they decided to do this, in a REST API.

I wanted to scream :-D

Now I have to figure out how to implement the same thing in Python -_-

 

I wanted to scream too by reading this!

 

I feel your pain.

Literally, I shuddered after reading that.

 

Good luck ;)

 

This is the problem with "clever code":

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." - Brian W. Kernighan

 

A general problem with "clever code" is that it's infrequently "optimal". And, by "optimal", I don't limit the evaluation scope to traditional measures like speed of execution, resource-consumption, etc. versus other methods. I mean, because it's "clever", it is frequently hard to maintain — especially from the standpoint of handing stuff down.

Sadly, I'm a frequent flyer on the "so terse/compact/dense no one else can maintain it" side of "clever code". On the plus side, it affords the opportunity to teach others new methods ...but the time lost to having a second person having to track the originator down to teach them how to interpret, replicate and/or improve on the code renders it no longer optimal when measured in (expensive) man-hours consumed.

 

Code golf can be fun, but I don't think it belongs on real projects.

These days it's rather rare for tricky code to be really necessary. Even for fairly high performance projects, compilers have become good at making optimizations. Also, often the hardest thing to achieve is to find the simplification that takes a problem which appears hard and makes it easy.

I imagine that there are still places where tricky code is needed for performance, but it must be a vanishingly small segment of the total software ecosystem...