2007-07-29
My standard for clear idioms in personal code
At least for personal code, I've decided that my standard for what I consider the clearest idiom for something is usually what first comes to mind when I try to write code to do the something. My idea here is that if a particular approach is what came to mind first when I tried to solve the problem, it is quite likely to be obvious to me what the code is trying to do when I reread it in the future because clearly this particular approach is what is on the top of my mind.
(The purpose of clear code is to communicate to future readers of the code what it does. For personal code, the future reader that I care most about is me.)
This does imply that what I consider the clearest idiom can change over time. This isn't just a matter of me becoming more familiar with a programming language or a library; sometimes it is because I don't always remember some algorithms and approaches all of the time, and what I remember clearly can shift.
For example, recently I wrote rounding up as 'nbits / 8 + !!(nbits %
8)
' (as expressed in C). A commentator gently pointed out that this is
equivalent to the shorter '(nbits + 7) / 8
'. At the time I wrote
the original code, the first version is what occurred to me. But now
that I have been poked about it, the shorter version is in my mind; if
it sticks, my clear idiom for doing rounding up will have changed.
(I will probably still be able to understand what my old code is doing, since the old version is still relatively clear and easy to reason through.)