[TUHS] Clever code

Michael Kjörling e5655f30a07f at ewoof.net
Mon Dec 12 19:48:12 AEST 2022


On 11 Dec 2022 18:15 -0800, from bakul at iitbombay.org (Bakul Shah):
> Agree that clear code is preferable to complicated code. But in practice
> people sacrifice clarity for performance improvement all the time. Look
> at the kernel code of any modern os. Everybody pays lip service to this
> but most anything other than toy programs ends up getting needlessly
> complicated over time.

Performant code does not need to stand in opposition to clear code.
And if you are writing performance-critical or size-critical code
(such as the QNX microkernel that someone brought up), then of course
you might end up needing to do things in non-obvious ways; that's not
the point here. Clever is fine IMO _where the cleverness provides an
actual benefit in a real-world scenario_, and an operating system
kernel (and a language standard library) is a rather special type of
program where sometimes you have to do things in somewhat non-obvious
ways because of the environment the code is meant to execute in. But a
significant portion of the time, where I see "clever" code there is
_no_ significant benefit to the cleverness; it's often more about
"showing off", or saving a few source code characters at the expense
of at-a-glance readability, than it is about actual usefulness and
necessity.

Necessary complexity in order to solve the problem, combined with
things like performance requirements, may sometimes require clever
code. At that point, there is a benefit to the cleverness. But one can
still aim to write the clever code _clearly_, with everything from
comments to good variable and function names to formatting that
enhances readability by for example grouping related operations
together in the source code to keeping related parts grouped together
and separate from other code. Just such a simple thing as that I often
add extra parenthesis over and beyond what's actually required based
on operator precedence, because doing so makes it clearer what goes
together and unless the compiler is severely braindead by modern
standards, doing so costs _nothing_ past the compilation stage.

-- 
✍  Michael Kjörling                  🏡 https://michael.kjorling.se
“Remember when, on the Internet, nobody cared that you were a dog?”



More information about the TUHS mailing list