16 ms·
Clever code is probably the worst code you could write (2023)
- beryilma 3y agoI would extend this to clever languages: "Clever languages are the worst languages you could write in". And I would put most functional programming languages in this category.
- Shorel 3y agoI think the obvious problem here is the manager's attitude: While I was proud of it, there was suddenly a problem when I talked to my manager about it. "While I understand how complex this was, when it comes to performance reviews, this code looks trivial. It looks too easy, too simple. I would recommend writing an implementation doc of this module just so we can demonstrate that this was actually quite complex."
- jawns 3y agoHere's an old joke about the progression from junior to mid-level to senior developer: Junior dev: My code is simple, straightforward, and easy to understand. Mid-level dev: My code is clever, innovative, expressive, hyper-optimized, and ingenious. Senior dev: My code is simple, straightforward, and easy to understand. In software development, "clever" solutions are like poems. In the best poems, there are usually multiple layers of meaning, nuances and subtleties, some harder to tease out than others. Sometimes you have to sit with a poem for a while before you are able to truly drink it all in. To mid-level engineers, writing this sort of poetic code has an intoxicating appeal. It allows them to flaunt their talents, demonstrate their mastery of the language, and impress their colleagues with their ingenuity. But more often than not, what is really needed is the code version of ordinary prose: straightforward, with a preference for clarity over succinctness, easy for others to understand, easy to edit, and with fewer surprises and deviations from convention than a poem. With prose, particular the sort of no-nonsense style found in wire news reports and explanatory journalism, the best work is easy for the reader to comprehend and lends itself to being edited. For instance, a skilled copy editor can condense it to fit, if need be.
- yieldcrv 3y agoI just say, bell curve meme
- dheera 3y agoReality: This is mostly because mid-level dev needs to justify their existence in order to not get laid off or PIP and is worried about losing their H1B and having to uproot their entire family in 60 days notice. Hyper-optimized, hard-to-read code that only they understand is one way to increase reliance on them while giving a reason that can be put into a promotion doc. Mid-level jobs are worried about maintaining their job. Junior dev doesn't care because they can go wherever, they aren't worried about the uprooting, and well-written code is a ticket to a multiple new jobs. Senior dev doesn't care because they have saved enough money, have permanent status, and if the company doesn't want them they aren't worried about there being better opportunities. They have enough online evidence of their competence and don't need to prove themselves.
- ern 3y agoThis is mostly because mid-level dev needs to justify their existence in order to not get laid off or PIP and is worried about losing their H1B and having to uproot their entire family in 60 days notice. Hyper-optimized, hard-to-read code that only they understand is one way to increase reliance on them while giving a reason that can be put into a promotion doc. Mid-level jobs are worried about maintaining their job. That seems to be a matter of survival overriding ethics and professional pride. I know I came up with some really cringeworthy and complex solutions as a mid-level dev, but I would never have done it deliberately. If people are put into a situation where they need to purposefully write substandard code to not get deported, it's something that needs to be fixed.
- strken 3y agoWhen I was a mid-level dev, the overly complicated code I wrote came about because I read an article on e.g. Ruby metaprogramming, got excited, wondered why we didn't use reflection more, and found a place where I could apply it. Perhaps you thought about job security, but that seems like part of your personal journey and isn't tied to seniority. I was just inexperienced and a touch arrogant, as mid-level engineers must be. At higher levels, the reason I don't write code like that is because I've been burnt too many times by the new hotness. It is slightly about job security, but only because I fully expect that any crazy shit I fling out today will eventually hit the fan and come back to me, probably at 3am during on-call.
- porphyra 3y agoI also find that, in C++, int sum = 0; for (int i = 0; i < n; ++i) sum += x[i]; return sum is a lot easier to understand than return std::accumulate(x.begin(), x.end(), 0, [](int a, b) {return a + b;}); Yet, the latter is considered more correct and better, with static analysis like cppcheck telling you to use the latter. It does have many advantages, like no mutable variables lying around, but gee it is annoying to read.
- constantcrying 3y agoThat is just a question of what you are used to. The "functional style" example is very obvious to a person who is familiar with that style. In fact if the rest of the code base is in a similar style it is the easier one to understand. There is nothing inherent which makes either better or cleverer than the other. (Also the first one is incomplete, as "n" is not defined, making the later more self contained)
- haolez 3y agoI like C++, but I don't understand this tradition of keeping these annoying namespaces prefixed to everything. Just get rid of those std::, foo::bar::whatever::, etc from your code and make it more readable. Use the "use" clause. It's very rare for such names to be ambiguous in the same file, unless I'm missing some bigger picture here.
- porphyra 3y agousing namespace std; is considered kinda bad since you don't want your namespace to be polluted with a bunch of std stuff. For example if you have `int count` lying around somewhere you'd want to be able to call `std::count` without fear of it being shadowed.
- haolez 3y agoBut ambiguity gives you readability. And if a "count" variable clashes with the function name, it's trivial for the compiler to catch this and warn you. It's a matter of preference, but I'd still risk ambiguity and name collision, especially when you go beyond std:: (like boost stuff).
- CodeWriter23 3y agoMostly true.
- haolez 3y agoThat's what I like about Go. It's easy to read and understand Go code from open source projects written in it (although Kubernetes is a notable exception, with a very convoluted Go code).
- zzz999 3y ago[dead]
- schwarzrules 3y agoAnytime I find myself being clever, I'm reminded of this deadpan exchange. Tyler Durden: How’s that working out for you? Narrator: What? Tyler Durden: Being clever. Narrator: … Great. Tyler Durden: Keep it up, then.
- readthenotes1 3y agoI wonder how old this advice is. I know that it predates the century but I'm not sure how far back. (A favorite quote of mine that I believe is from the 1970s says "It's easier to make working code fast then to make fast code work." Since the fundamental problems of programming have not changed over the centuries, I wouldn't at all be surprised if there's an anti-clever saying from the dawn of computing)
- tialaramex 3y ago> the fundamental problems of programming have not changed over the centuries It hasn't been a whole century yet. Grace Hopper's career started in 1944, eighty years ago.
- readthenotes1 3y agoAda Lovelace predates her
- tialaramex 3y agoAlthough it is very common for laypeople to be told that Ada is the "first programmer" in some sense, I don't find that very convincing at all. For Ada this was purely an intellectual exercise. Grace's machine really existed, and her insight really works, even if today we would not call what she initially built a "compiler". The machine processes data, the program is data, have the machine process the program. This is recursively meta-applicable, and it's notable that rather than being something higher ups or intellectuals had specified should be done, Grace was being entirely practical. When you write some typescript inside a C# program today and then somehow in a web browser the equivalent code ends up executed by its JS engine, that's all the fruit of Grace's insight just applied over, and over, and over.
- tehnub 3y agoThis is true, but in code reviews and such, it often boils down to familiarity above anything else, like someone preferring names = [] for record in records: names.append(record["name"]) to names = [record["name"] for record in records] Now, I might say something if I saw this: import operator names = list(map(operator.itemgetter("name"), records)) Seems a bit unidiomatic given that list comprehensions are in the language... but probably many disagree.
- akasakahakada 3y agolist-map-itemgetter is actually the fastest solution in Python. Should actually promote this.
- amanzi 3y agoGreat example. My personal preference is the first one, but I put that down to me being inexperienced and not working in a professional development environment. I've been using Ruff with most of the rules enabled, and they have a page for this scenario here: https://docs.astral.sh/ruff/rules/manual-list-comprehension/ https://docs.astral.sh/ruff/rules/manual-list-comprehension/ Another one that trips me up is the ternary operator: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp/ https://docs.astral.sh/ruff/rules/if-else-block-instead-of-i... I prefer the longer, more verbose version, even though the suggestion looks more clever.
- aidos 3y agoLet me see if I can sway you. The nice thing about both the ternary and the list compression is that they become statements of the form derived_thing = some_computation. The code flows better when you’re skimming it at a high level and thinking “then we get this”, “then pluck this”. You can think more about your reformed data and less about how it was reformed. The alternative is that the branching obscures what you’re trying to create at each step. Sometimes I’ll even use 2 list comprehensions instead of a loop (even though it’s slower) because it’s clearer to read something like: odds = […] evens = […] That’s my experience, anyway.
- Jagerbizzle 3y agoI’ve been a C++ dev for a couple of decades and know my fair share of unreadable code. I’ve recently started learning Python and holy shit, it’s like you get accolades in this language for doing as much as possible in as few characters as possible. Guess I’m getting too old for these young whippersnappers.
- JohnBooty 3y agoAfter spending six months with Python so far, the problem with the Python ecosystem is that you have a lot of really smart people (scientists, mathematicians) who are not software engineers by trade writing a lot of these libraries. I guess it's a good problem to have, in a lot of ways, because it's also why Python has that huge science/datascience/etc ecosystem.
- lopatin 3y agoIf you think Python is like that, I advise you to never look at Ruby codebase. But seriously, of course you can write Python one-liners or nested comprehensions, but I get the idea that it's not really Pythonic. They still want clear, iterative code. It's just more concise, but the idea is the same, but with less scrolling.
- JohnBooty 3y agoIf you think Python is like that, I advise you to never look at Ruby codebase. The codebase for Ruby itself, or the codebase of your typical Ruby app or library? I spent about a decade with Ruby and my general impression is that the community really moved away from overly-clever metaprogramming. The codebase for the Ruby language itself is definitely a challenging read.
- mostlysimilar 3y ago> If you think Python is like that, I advise you to never look at Ruby codebase. Like any other language you can write perfectly expressive and intelligible code in Ruby, and in fact it is quite common to do so. The first layer of a Ruby codebase tends to be approachable, it's only when you get into some of the bigger libraries that you get some tricky metaprogramming. Even then I don't often see Rubyists write tricky/clever code for the sake of it. The metaprogramming usually has utility and is often the "right" way to do something, especially in say the Rails codebase. Ruby is all about developer happiness. It's the founding principle and the guiding ethos of the community.
- jraph 3y agoYep. I now find it enjoyable to refactor my code to the point of making it feel obvious and straightforward. Not always easy. For me, it helps imagining some colleague read my code and judge me. And fortunately, I work at a place where I trust people to recognize when something that looks obvious is not actually dumb. Not that I'm so great at dumb but I try at least. Tooling that allows you to move classes, methods, rename stuff, inline or extract functions efficiently helps a lot. It pains me a bit to write this, as someone whose favorite code editor is a text editor, not an IDE. I find there's comparable joy in writing. Rephrasing and simplifying a text to find the most efficient / obvious phrasing. I suspect writing software might affect writing in such ways, though I don't think I would be able to tell a developer's writing apart.
- 127 3y agoSometimes clever code creates a good abstraction. Clever code that doesn't create a suitable trade-off with complexity isn't actually clever at all. Of course, never code golf outside actual code golfing puzzles.
- jbandela1 3y agoI think “clever” is more related to unfamiliarity. There is actually a lot of cleverness going on that people just become familiar with. Structured programming is actually very clever if you think about it. Function calls are, when you look at it closely, very clever. It encapsulates how to jump to a function entry point, how to pass on values in registers or in memory, how to adjust stack pointers, and all other sorts of cleverness. For loops are clever with different parts of the statement controlling and executing different parts of the loop. Compare that with BASIC A six year old child can understand: 10 PRINT “Hello” 20 GOTO 10 Going on to object oriented programming, dynamic dispatch and v-tables are clever. What you call and where you go to in your program are determined by the dynamic type of an object. This is very far from the simple BASIC GOTO What difference does looking at it like this make. First we don’t reject automatically reject new concepts just because they aren’t simple. While function calls are complex, they bring many benefits. In addition, this approach emphasizes the role of education to in taking useful concepts and making them familiar to a broader group of people.
- P_I_Staker 3y agoYes, but people are widely familiar with certain concepts. Hating "clever code" doesn't mean hating any abstraction or good elegant ideas (like function calls). The thing is that this stuff has already been in circulation for so long, and many of the good ideas have been found. If you tried to come up with new solutions for function calls, people would understandably be skeptical.
- psychoslave 3y agoCleverness is like connecting dots. It might be an instance that reveal a smooth curve that seems so obviously clear afterward but was unfathomed so far. Or it can cast a baffling intricated sequence of discrete points each generated at coordinates using the previous one in a well specified but completely ungrabbable way, the whole drawing a scary screaming face that any sane mind will flea away from.
- HarHarVeryFunny 3y agoI think there's a difference between "clever" and complex. You can express a complex algorithm or pattern with simple easy to understand code - complexity doesn't have to manifest itself as unreadable or incomprehensible code. To me "clever" code is more about they way you are doing something than the complexity of what you are trying to do. Clever is the opposite of straightforward and easy to comprehend without a detailed explanation. For example you might be "forced" to write clever code as an optimization to calculate something in a non-obvious way, maybe also based on some non-obvious pre-conditions that have been assumed and make this a valid approach. You don't normally want to write "clever" code - you want to write easy to understand straightforward code, and on the occasion when you feel compelled to a clever implementation, for the sake of future you or your teammates, you better precede it with a block comment prefixed with "here be dragons" and a detailed explanation of what it is doing and why it is doing it in this non-obvious way.
- fr4nkr 3y agoI would argue that what constitutes clever code varies a lot by language. There's always a "cleverness" threshold where being able to read or refactor the code becomes harder, but this threshold isn't universal. Python in particular makes it very easy to be too clever, since its extremely rigid syntax was designed specifically to discourage it, but it ended up giving the user the necessary tools to be clever anyway, and the end result is usually... not pretty.
- collyw 3y agoComing from Perl, Python made me write more verbose simple code. But I noticed that in Perl I would do something clever, then a few days later it would come back and bit me in the arse, when I was trying to debug it. Sure Perl saved a few lines of code over Python, but my Python code ended up more reliable. I do miss Perl though.
- morkalork 3y agoWhat would qualify as clever Python? These kind of broad and vague statements make me wonder if I am guilty..
- dijksterhuis 3y agoTL;DR - OOP obsession is a common python developer phase. it's a dangerous phase. - maintainable code is not minified code. minified code is minified code. - stoopid code is often stoopid enough when it satisfies real world / human concerns, not technical concerns. ---- I've done all of these, and I see other people repeating them. 1. hyper optimised and utterly fragile class based inheritance / abstractions. Not optimised in performance. Optimised in terms of minimisation of code. avoid ABCs like the plague. YAGNI so save yourself some heartache and keep it stoopid. 2. especially when ^ includes many static methods that could be standalone functions. a good sign the code can probably refactor to functional + objects/dataclasses (and probably be easier to test as a result). You didn't need it, go back to keeping it stoopid. 3. methods that call another method, that calls another method, that eventually calls one of the static methods. often when I see this, none of these child methods are called by anything else. someone wrote multiple separate methods because apparently we shouldn't write methods with more than 10 LoC. because that's how to write clean code apparently. just put it all in a single method so I don't have open multiple different browser tabs while sitting in the doctor's office responding to an incident on my phone. stop optimising for LoC and make it obviously stoopid. 4. hiding how the code will run away from main entrypoint by adding a `className.run()` method. yeah, cool, your main function has been minified. kudos. But now I have no idea what steps your script will run. I have to go and read something else. make it obviously stoopid to someone reading this for the first time. 5. using names of concepts from other languages. don't call classes an "Interface" or a "Controller" because it sounds better. This isn't Java nor is it Kubernetes. It's python. keep names so stoopid that I can understand when my phone has woken me up at 3 am. 6. functional is usually simpler, until you start turning in a mathematician. you are not a mathematician. and neither is the junior sitting next to you. don't overuse recursion or currying etc. keep it stoopid enough that the junior sitting next to you has a chance of taking over responsibility for it one day without going through a PhD in mathematics. 7. avoid using functionality from the last 3x minor versions of python [0]. slow down and let others catch up first so we can all be stoopid together. ---- caveat: experience will vary wildly between different hoomans regarding what is considered stoopid enough. [0]: a good exception here is something like case matching. this was pretty big so I would have allowed that, so long as everyone was aware it was a new thing now (I'd have done a post on slack saying -- Oi, go look at this, it's big)
- spullara 3y agoSome developers like to solve problems and some like to solve puzzles.
- dpc_01234 3y ago"Clever code" here means "code-golf-like code". "Clever" is too subjective to be used like this. One person's clever, is another person's mundane, and it varies across languages, ecosystems, teams. Also I'd like to point out that in this example, had that function had a comment and a couple of tests, then it wouldn't really matter much what the implementation is. If you don't like it, you can rewrite it your preferred way. Though as a dev I'd be too lazy to try to optimize code for code-golf-like properties in the first place.
- mvdtnz 3y agoThis is why I don't like working with Ruby teams. Of course you can write straight-forward Ruby code and I encourage it, but Ruby does seem to attract developers who like to write "dynamic" code and use "meta-programming" (what we would call "reflection" in other languages, where it's made intentionally difficult). I think it's mostly the influence of the Rails framework that leads developers towards "magic", although it doesn't help that Ruby makes this kind of programming especially easy.
- zb3 3y agoThe actual example'd make the post better, but I understand the author is not allowed to give more details on that one :(
- mcv 3y agoI've noticed I love the clever, elegant abstractions I invent, because I understand how they work and they give me a really neat and readable way to organise my code. And I hate the clever elegant abstractions others create, because I the code is so abstract I can't tell by looking at it what it does, and I don't have their mental model of the abstraction in my head. Cleverness is fine if you can make sure the reader gets the right mental model in their head, but not if not. And because nobody cares about your documentation, your options are to either explain it to everybody (sounds stupid but can actually work -- for a while), or to make your code explain it for you. And that limits how clever and abstract it can be.
- jasonpeacock 3y agoKernighan's Law: 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.
- vlovich123 3y agoUnless you got dumber between writing and debugging, it more likely means that it takes twice as long (or even more if you haven't touched it in a bit). It's unlikely that Kernighan meant it takes someone twice as smart to figure out what you were doing as that would be a nonsensical interpretation (someone twice as smart may not be able to figure out what the stupid person is trying to do in the first place if the code written was nonsensical).
- bluGill 3y agoMost of the problems I've had to debug the place to look is not clear. Sure I've had to fix "The is not spelled Teh", but most problems are it breaks in some weird situation - step one is figuring out where to even start looking. Once I narrow down the exact place to look it might be easy, but I have to hold a lot of different areas of code in my head while narrowing things down. Even when I narrow it down, sometimes the answer is make the code more complex, and if the code is already on the edge of how complex I can handle I won't know how to make it more complex.
- fargle 3y ago> It's unlikely that Kernighan meant it takes someone twice as smart to figure out what you were doing no, that is exactly what he meant. clever code means you are just barely able to understand it enough to write it yourself [in any amount of time]. therefore, you aren't going to be able to debug it at all, by a factor of nearly two. and if you are the "smartest" person in the org (which he often was), then you are really in big trouble. now obviously things in the real world like "smart" and "clever" are not one-dimensional quantities in neat categories, but he was making a memorable and funny quote, with quite a bit of truth to it, not a precise scientific hypothesis. see also: "too smart for one's own good" > nonsensical interpretation how so? > someone twice as smart may not be able to figure out what the stupid person is trying to do in the first place if the code written was nonsensical. true, but irrelevant, this is about clever code from a smart person, not nonsense code from a stupid one.
- nine_k 3y agoI keep to a simple rule: smart code is an asset, clever code is a liability. Smart code is usually simple and clear, while also being short and efficient. Achieving this is not easy, but reading, understanding, and using smart code is easy. (Otherwise it's not smart, but, well, ordinary.) An example of smart code for me would be the merge sort algorithm, or the Lisp interpretation loop. Clever code is usually some kind of last-resort hack, a trick, applied in dire straits, or to achieve a unique effect. An example would be the inverse square root hack, or the Duff device. Beside the actual writing time, code review time is good for making code smarter and less clever.
- jongjong 3y agoThis is true. That's why the software engineering recruitment process is completely broken... They select for people who revel in unnecessary complexity. What kind of person enjoys spending their time practicing many variations of pointless complicated coding puzzles instead of working on useful side projects or learning new concepts and technologies? The big tech recruitment process is all about puzzle solving under time constraints though. Pragmatic engineers have no chance of competing against the puzzle solvers.
- slushy-chivalry 3y agoA bit of a clickbaity title, but I'll bite I think "cleverness" is a function of your (and your team's) experience in a particular language / domain space I worked with teams where verbose Java is considered "simple, straightforward, and easy to understand" I also worked with teams where terse Haskell is considered "simple, straightforward, and easy to understand" and of course these codebases look nothing alike
- deleted 3y ago[deleted]
- fl0ki 3y agoEveryone thinks they're writing good code. Even many experienced seniors write code that they think is good code but others loathe. Best case, they can at least solve problems without introducing new ones; though more often than not, they're still making many junior mistakes while couching them in senior terminology. Aside: Do we really need to keep rewording this exact same essay every month since the first computer program was ever written?
- boxed 3y agoThis one was a bit different. It also featured an extremely dangerous and incompetent manager.
- 000ooo000 3y agoHey if no one is writing blogspam and posting it to HN, when am I gonna get to drop my hot take on what differentiates junior, mid, and senior developers? And what about my thesis that there is actually a huge difference between programmers, developers, and engineers? My identity is really wound up in all of this so it's important that I get an opportunity to put other developers down.
- stephc_int13 3y agoThere is always some part of subjectivity when evaluating complexity and clarity. But all things being equal, this point still stands and should be not being brushed off as "skill issue". Clarity is a difficult skill to acquire, but it pays off.
- boxed 3y agoIt's like no one in the comments here read the piece. Honestly, it's a bit like the author himself didn't. The big thing in this article is the dangerous and incompetent manager. People like that in a company could destroy the entire thing, and yet it's sort of just mentioned in passing like "oh that's funny". It's not funny, it's absolutely terrifying!
- bloaf 3y agoSo I’m going to play the devil’s advocate and say that concise code has a readability advantage in that you don’t need to keep track of intermediate variables or other state across hundreds of lines of code or multiple files. This was/is the promise of languages like APL; those willing to invest in learning arcane and terse symbols can move mountains in a few keystrokes. I know that for my part, when reading a language I’m familiar with, it’s usually much faster to puzzle out a concise solution than a verbose-in-the-name-of-simplicity one.
- mybrid 3y agoI follow Einstein's metric, "make something a simple as possible, but no simpler."
- alphazard 3y agoThe knockdown test for too clever is that the original author can't maintain or extend the code later on. You can use this phenomenon to prove to people that they were being too clever. "See? not so easy, and this is all your doing" Beyond that there is a a tradeoff to be had between utilizing powerful and expressive language features, and alienating less proficient programmers. In industry, redundancy and parallelism (of humans) matters a lot, and so the code has to be dumbed down quite a bit. If you're working solo or with a few highly competent peers, you can afford more cleverness.
- gregjor 3y agoI suppose every generation of programmers has to rediscover this and it can’t hurt to keep writing articles and books about it. From The Elements Of Programming Style , 1978, by Kernighan and Plauger, rule one: “Write clearly – don't be too clever.” The whole book, a short read, spells out principles and wisdom from experience that all programmers would benefit from.
- Aeolun 3y agoI like how there is a constant stream of people realizing and writing blog posts about this.
- matrix87 3y agoI don't think the python example is "too clever" though, the expanded version seems more convoluted
- deleted 3y ago[deleted]
- quantum_state 3y agoIn the spirit that Programming is Theory Building, one would want to keep it simple, consistent, and easy to understand with basic constructs defined in a somewhat irreducible (single responsibility) manner.
- doubloon 3y agoYou learn about this a lot in writing and humanities classes not so much in CS classes
- GuB-42 3y ago> Clever code is probably the worst code you could write But you should write it anyways. Preferably in a situation of little consequence (school, personal projects, prototyping, etc...) Otherwise, how do you make the difference between code that is simple and code that is just dumb? "not clever" code typically has: copy-pasting, no abstractions, hardcoded values, global variables, cascading "if"s... And sometimes, it is the right thing to do, but good, readable code is usually a bit more clever than that. But how do you know the right kind of cleverness? For me, the best way is to experiment. Sometimes, trying to be clever fails, sometimes, it really makes your code better, but if you don't try, your code will never get better.
- myspeed 3y agoIn reality, writing a code that is easily understandable for everyone is good code. Clever code is intricate and difficult to follow by many. Coding is done for a team of people and not to show individual preceptive of a business problem/solution.
- hackable_sand 3y agoCleverness is found in grokking a system. A system of simple code is more easily understood. It's easier to move and impress the system at high-level user interfaces. At what rational scale does the system become clever? How long is a system considered clever and how often? Can you use diff trees to infer high-level logical migration and evolution patterns within the source files themselves?
- dustypotato 3y agoNARUTO - Never follow Absolute Rules as Ultimate Truth Over practicality