Write the most clever code you possibly can
77 points by hwayne
77 points by hwayne
def is_prime(x): if x == 1: return True return all([x%n != 0 for n in range(2, x)]
This is “clever” because it uses a single list comprehension, as opposed to a “simple” for loop.
This is not very clever because
)
return all(x % n != 0 for n in range(2, x))
Or, if you’ll tolerate a little more cleverness:
def is_prime(x):
if x <= 2:
return x == 2
if x % 2 == 0:
return False
return all(x % n != 0 for n in range(3, math.isqrt(x), 2))
The Kernighan misquote is cute, and maybe it’s an independent rediscovery, but you might want to give some credit to Linus Akesson for “Kernighan’s Lever”.
Here is how the article defines “clever code,”
Clever code is anything using features or domain concepts we don’t understand.
I would propose the modified definition,
Clever code is any solution we don’t expect.
There are solutions we don’t expect because of unfamiliarity, like with the people @hwayne mention who prefer straight-line code. I think if we find ourselves in that situation, it is reasonable for us to try to broaden what we are familiar with. We’ll slowly incorporate the “clever” solutions that make most sense until they are no longer clever to us. When Java 8 came out, I remember hearing that lambdas were too clever!
Then there are solutions we don’t expect because they are misuse or abuse (be it of familiar or unfamiliar constructs). This is what I think of when I think of clever code that is to be avoided. The kind of code that makes you stop in your tracks and ponder it even if you are familiar with all of its constituents.
Unfortunately it’s hard to draw a line between these two, and what you think is code golfing, I swear I’ve seen used normally (please don’t). It doesn’t help that some tricks we see as clever in one language are standard practice in other languages, (e.g. treating numbers as booleans).
I also took issue with the article’s definition and I think yours is better. However both are still about the code where as Kernighan’s advice was focused on the programmer. Cleverness is not an objective attribute of code. It is a scale defined by our debugging abilities. His advice can be read more generically as a reminder to be humble. So I would describe code as being clever reflexively, as any code for which, in the presence of a bug, I would lack an immediate instinct for where in the code the mistake could be found.
Since Kernighan’s quote software projects have grown quite a bit in terms of participants. They are social endeavors as much as anything today. What manifests as humility in the individual case often manifests as inclusiveness in social contexts. For example, when I (from the US) am in a social circle with people for whom English is not there first language, I strive to use fewer colloquialisms and adjust my word usage to use the most common word I can, even if there is a more compact phrasing because if there is a miscommunication I want them to be able to ask me a clear conversational question to clarify rather than the conversation getting bogged down by diverting into a language lesson. The same basic tenets apply to groups collaborating on software.
Since many push back against his advice to be humble, we could define it in this social context, with zero humility required:
Clever code is code that will require my expertise to change or fix when there is a bug.
My favorite part of this article is acknowledging the existence of grad students outside cs who write scripts for research. This is a demographic that I work almost exclusively with and nobody in the real programming world seems to be aware of their existence.
These people aren’t typically great programmers but they write a lot of code, enough that they are a relevant demographic when considering the user base of a code tool.
Reminds me of:
from itertools import count
def gen_primes():
for i in count(1):
if is_prime(i):
yield i
def is_prime(i):
if i < 3:
return i == 2
for d in gen_primes():
if d ** 2 > i:
return True
if i % d == 0:
return False
I like the fact that gen_primes
just uses is_prime
and is_prime
just uses gen_primes,
yet it works :)
I’d argue for committing the most clever code you can. But in a powerful language, that means building a DSL such that your actual program amounts to a configuration:
(send-report
:to client-emails ; At a certain size, nouns like "destination" can be easier to align with internals
:covering list-of-equities
:at 8 :in 'NYC
) ; "bad" paren style is nice for configs
Then you just implement this clever/short API (and e.g. add some webforms with logins which clients can use to add stuff to the equity list and sales can use to add to the clients.) Good, clever code makes empowering non-leaky abstractions! (Yes, I’m just redefining clever.)
i’ve grown to like bad paren style
the usual arguments are that the parens become invisible to you, and emacs counts them for you
but, after heartbleed, i no longer trust the first one. and emacs doesn’t help when i’m looking at a github PR or something
I’m going to join the proud tradition of commenters who ignore the purpose of the article to nitpick one specific code example.
The “too-clever” data-extraction function would be much simpler if they used a filter
instead of a reduce
, paired with Object.fromEntries
:
const extractDataFromResponse = (response) => {
const [Component, props] = response;
const resultsEntries = Object.entries({ Component, props });
const truthyResultsEntries = resultsEntries.filter( ([_k, v]) => !!v );
return Object.fromEntries(truthyResultsEntries);
}
Though, as I bet the linked article points out, it feels very goofy to go through all that trouble for an object with two keys we explicitly yoink out of the response object.
(Code not tested, as I’m somewhat jet-lagged, and even more-so lazy.)
And I’m going to join the proud tradition of Internet commenters who disregard the meaningful content of a comment to focus instead on an aspect of grammar :)
To be clear, I’m a staunch descriptivist, so this is a genuine non-judgemental inquiry into how you came to express it that way, not a claim that you’re “wrong”.
and even more-so lazy
I’ve noticed this pattern a lot recently (in the past six months, approximately) - the phrasing “more-so ” (with or without a hyphen) where “more ” would be sufficient and expected. I’m interested in understanding it more (so :P ).
To my mind, “more so” is a meaningful phrase, with a different sense than used here. If “so” is an adverb denoting “in the same manner or way” (”Make it so” => “Make things be the way that was just described”), then “more so” would be used to compare how much two nouns match a description - “I’m lazy, and my sister is even more so” (”…is even more in-the-way-just-described”).
Does “more so” also have that meaning to you, or does it only have the sense that you used it in here? Is it distinct from “more” - more intense, or with a whole different meaning? Do you happen to remember if you started using the phrase recently, or has it been part of your idiom for a while? To the extent that you’re comfortable sharing it, whereabouts are you based? (I was born and raised in Britain, but have lived in the Bay Area for ~9 years).
Again reiterating - there’s no such thing as wrong grammar, I’m not trying to make you feel bad for how you communicate, I’m genuinely interested in how language is formed.
I got a little side-tracked by that too! Your solution is a ton clearer than the “clever” data-extraction method.
The thing that immediately springs to mind for me is lodash:
const extractDataFromResponse = ([Component, props]) => {
return _.pickBy({ Component, props }, Boolean);
}
Some folks might not want lodash on the frontend, but if this sort of weird data-extraction manipulation is common, I think it makes sense to use shared utilities rather than needing to write “clever” code each time.
And if we wanted something “clever,” we could write something atrocious:
const extractDataFromResponse = (response) => {
return ["Component", "props"].reduce((acc, k, i) => response[i] ? { ...acc, [k]: response[i] } : acc, {});
}
The “too-clever” data-extraction function would be much simpler if they used a filter instead of a reduce, paired with Object.fromEntries:
About 9/10 times I see .reduce
, it should be written as something else (and that includes the code I just wrote). At least in the JS that I’ve read, it feels like one of the surer markers of code that could be written in a clearer way.
I do! … But only in human resource machine and its sequel 7 billion humans. Typically I write (up to) 3 versions of each challenge. 1, the simplest thing that comes to mind that solves the challenge. If that doesn’t satisfy the speed or “number of instructions” extra difficulty levels, I add a version as required to address those.
⚠️ Do NOT click those links. Do NOT check out those games. They will chew up your free time and spit it out. They don’t care that you had other weekend plans. They don’t care that you needed to sleep. Just stay away.
Also, if you value your productivity, avoid Zachtronics entirely. Especially TIS-100 and Opus Magnum.
And I will shamelessly plug my own single-instruction (subleq) programming game, SIC-1 (which is free and open source), in case you’re a glutton for tedium.
By the way, if you’ve finished all the Opus Magnum journal puzzles, there’s a series of extended symposiums: https://events.critelli.technology/
Thank you for this, I think I will just start writing more Julia because I liked it once even though I tried to recode all my numerical stuff in rust because it was more industrial and solid. But I really liked having fun in julia and being terse and writing complicated macros and doing magic and replacing all my sensibly named variables with unicode greek characters so it looked like the equations in the textbook. I’m not making anything safety critical as part of a big team. I will play.
FWIW, we use Julia at my hedge fund, and it has worked very well for us. Julia’s lispy features have allowed us to make the codebase ~20% smaller than it would be otherwise, and perhaps more importantly, make it easy for non-engineer researchers to work with. Admittedly we mostly avoid clever code, but we lean in really hard in a few places.
Completely off topic, but how does one break into shops that value making code faster and cheaper?
If you’re interested in mine, feel free to email me (email in profile.)
For others…honestly, I don’t really know. I worked at normal finance companies getting jobs in normal ways, and got a bit of a reputation for getting things done quickly because I was running experiments in a few minutes rather than overnight. I did ok, and eventually I started a company with my friends, where we could write code to our standards.
I often feel like the most clever code I can possibly write is the code that doesn’t need to get written.
Something that seems unbearably clever to me might be utterly mundane for you, and vice versa.
Being a bit of a C++ nerd, I seem to experience this often. But then I saw what I think would be considered basic pytorch tensor code at work the other day and got paralyzingly anxious.