12 ms·
What does code readability mean?
- tboyd47 9y agoThis is a thought-provoking and well-written blog post about programmer biases when it comes to reading, and judging, other people's code. The author is making the point that code readability is ultimately in the eye of the beholder. I've come to share the author's views, and I have to say I don't hear it said much in programming culture. At most places I've worked, there's this culture of constant refactoring under the guise of "continuous improvement," when really, if you look closely, it's really motivated out of disdain for the last developer's programming style, and in my opinion, a general aversion to reading code. Reading code is about 10x as hard as writing it. It takes more concentration, it's less fun, it's harder, and it doesn't impress anyone. You have to know the language better than the person who wrote it, because not only do you have to understand why the code does what they intended it to, but you also have to understand why the code does other things they didn't intend (a.k.a. bugs). But in my experience, you save your team a lot more time and energy in the long run by preferring to read and understand existing code.
- seanmcdirmid 9y agoThere is a lot the context you’ve built up in writing that code that could never fit in the comments (even if thoughts could easily be expressed in words, they would dwarf the code and not directly correspond to it; actually comments can actually make code reading harder in this way). It really isn’t about the language either, at least the programming language, but how the problem was defined and understood in the first place, how this understanding was encoded in the software. Reading code is basically trying to reverse engineer the thinking of the programmer by looking at second order output. Of course it will be hard! It isn’t just style, nor would I say mainly just style. Continuous improvement is often just a matter of rebuilding the context that was lost with the last programmer.
- onion2k 9y agoThere is a lot the context you’ve built up in writing that code that could never fit in the comments Isn't that precisely what Knuth was trying to resolve when he came up with the idea of literate programming[1]? The fact that you might end up with more words than code isn't a really problem if the end result is better (for some value of 'better') than just the code. [1] https://en.wikipedia.org/wiki/Literate_programming https://en.wikipedia.org/wiki/Literate_programming
- seanmcdirmid 9y agoYes. But those words don’t come for free, they could be much more expensive than writing the code itself, it’s like trying to teach something rather than just doing it.
- mannykannot 9y agoThis is not the right model for assessing the cost of documentation. If the program is in any sense designed (as opposed to being assembled and modified on the basis of hunches until it appears to work), then the ideas expressed by those words must have been known no later than the completion of the work. Therefore, the cost of documentation is that of writing down these ideas, and the cost of not documenting is the cost of repeatedly reverse-engineering them from the code. It is my experience that you can markedly improve the speed and accuracy with which a newcomer can understand a code base with supplementary documentation of considerably fewer words than are in the code itself - so long as those words are well-chosen, and focus on the programmer's intent.
- seanmcdirmid 9y agoYou mean waterfall right? Ya, then I guess. If the program is understood before it is written (waterfall), then you merely write down these ideas along side the code. If programming plays any matter into evolving the design (as you say, “hunches” that go into a feedback loop), then this will break down quickly. Edit. Never mind you mean afterwards. But is the assumption that design can occur independently of programming really true in practice? It depends on the complexity of the problem you are working on. Something well understood before programming starts has a better chance of being well documented with short prose (because it is well understood, a lot of shared universal context can be relied on). There are lots of things out there that don’t meet this criteria, however.
- maxxxxx 9y agoTotally agree. It's a lot of work though and can be humbling to find out that the previous people weren't complete idiots. Reading code also doesn't really get rewarded. It's easier to declare the work of people who aren't there anymore as bad and rewrite everything.
- gregjor 9y agoThroughout most of my career reading and maintaining code got fobbed off on the new programmers and the less skilled. Maintenance programming has a bad reputation, partly because it requires reading and figuring out someone else's code. Now I make a living reading and maintaining code no one else will touch. Lots of companies can't afford to rewrite a mostly-working system, or they can't take the risk. I found a niche doing maintenance work and now I enjoy fixing what other programmers have said they can't maintain. Freelance maintenance work pays just as well as green-fields development and has fewer customer hassles, too.
- larschdk 9y agoThe biases are real, but readability is perhaps less of an ultimate concern than maintainability and reusability. Both of these depend on the ability of yourself (and others) being able to understand and adapt the code. A bit of foresight in making the life of future you (or colleague) easier goes a long way. Technical debt is real too and the interest can be high.
- Clubber 9y agoI would say that readability is a facet of maintainability. If a good developer looks at code the first time and thinks, "WTF," it could use some better readability. That's about as nailed down as I can make it (because it's so objective).
- gregjor 9y agoI have a follow-on article about maintainability taking shape, still in the notes phase.
- ebiester 9y agoAlternatively, we refactor because the right abstraction for the previous phase of the project is not the right abstraction for the current or next phase of the project. While I do have a respect for Chesterson's Fence as a concept, sometimes the answer to "why is it this way" is "we were learning as we went, and if we did it again, we'd do it another way." I look at it this way: When you look at an older city built before the age of the car, they were built to be tiny to start, not more than a set of shacks. As the town built wealth, the buildings went to more sturdy, to multi-story, and to more ornate structures. Similarly, our code should start simple and dirty, then cleaned up as it has proved its worth, and then refactored to more robust patterns as the code has built the wealth (and demand) to justify it. We should consider rewrites, then, as a sign of value, rather than as a sign of the previous programmer's failure.
- tboyd47 9y ago> sometimes the answer to "why is it this way" is "we were learning as we went, and if we did it again, we'd do it another way." True, and that's believable when it's people rewriting their own code, but sometimes you'll have people who didn't even try to understand the existing code express a desire to rewrite it.
- pjc50 9y agoI suspect this is as culturally determined as the differing American, European, and Japanese attitudes to rebuilding buildings. European cities typically retain medieval street layout and as many buildings from that time as possible, sometimes even rebuilding to the original style after destructive events. Whereas Japanese houses have a ~30 year lifespan and are routinely rebuilt. And I'm looking up the hill at a castle that accreted between the 12th and 17th centuries. Just as the street layout will outlive the buildings, APIs tend to be extremely durable and intolerant of destructive rewrites. Consider the Python transition.
- dahart 9y ago> sometimes the answer to "why is it this way" is "we were learning as we went, and if we did it again, we'd do it another way." This is true! In fact there's a lot of that, in my own experience. Rewrites are probably most useful on code you wrote, rather than on someone else's, and right when you realize what went wrong, while you're still intimately familiar with the old code. I've watched two different companies follow the "things will be so much better if we rewrite" logic and rationalize large scale rewrites that cost millions, and years, and failed to achieve the aims of doing it better the second time. Rewrites should be considered a sign of value only if we actually learned from out mistakes, only if both everything wrong with the old code and everything right with the old code are well understood. If you rewrite anything substantial before that, you're just guessing, and you're most likely (in my experience) going to suffer taking longer than you want and making the same mistakes again. I've seen that happen to many very smart people. So there's a balance. Rewrites are sometimes valuable, but not automatically valuable. Sometimes rewrites are very harmful. The best chance you have of knowing which one is to read lots and lots of code before you start, to make absolutely sure that the code you're replacing is never being replaced only because the readers didn't understand it or didn't like it's patterns. OTOH, if you have complete test coverage in place before a rewrite, you can freely annihilate and redo large portions of code without having to study too hard.
- HeroOfAges 9y agoI'm of the opinion that companies should rewrite as much of their codebase as often as possible. Given the difficulty of trying to understand code written by someone else, why shouldn't production code be considered immutable?
- tigershark 9y agoOnly if you write shitty code it's 10 times easier to write it than to read. When I write my code I use much, much more effort to try to express clearly my intent and what it is doing, and in that case it's much easier to read it than to write. I think that we can easily say that good code is very difficult to write and very easy to read, bad code is very easy to write and very difficult to read. The code is written once and read n times by m different people, so there is a huge gain in spending more time in making it simpler to understand rather than spending the minimum time in writing code and leave all the effort to the readers. Readers that, very often, after they become too frustrated, want to rewrite it (and for very good reasons I'd say).
- gregjor 9y agoWe all think that we write our code so other programmers can read it, and we believe that because while we have the code in our heads we don't have any problem reading it. I don't question your intentions or abilities, but the fact remains that a whole lot of programmers find almost every piece of code they didn't write hard to read. Or they say that -- I think they mean they just don't like the look of it, or they can imagine writing it differently.
- pjc50 9y ago> By analogy, plenty of people find reading Homer, Shakespeare, or Nabokov difficult and challenging, but we don’t say “Macbeth is unreadable.” What of Joyce's Ulysses? The thing is, most authors do put considerable effort into readability, because it helps you get read, published and paid. There's an interesting parallel with this article - writer:programmer :: critique group:code review. > Programmers, prone to investing their ego in their code, worry about criticism from a lot of people they don’t know. Slurs about competency abound in programmer forums. Code samples out of context get critiqued and subjected to stylistic nit-picking. That process can prove helpful for programmers with thick skins who can interpret criticism as either useful mentoring or useless insults. Less experienced programmers can get misled and brow-beaten. Public code reviews create a kind of programmer performance art, when programmers write code to impress other programmers, or to avoid withering criticism from self-appointed experts s/programmer/author and it still holds. As does much of the rest of the article. I would say that programmer education really does underplay reading code. Students are taught to write small pieces and may never be shown a large novel-sized lump of code unless they go looking for it.
- olavk 9y agoUlysses is not unreadable, it just takes a lot of effort. For programming, the criteria is not if it is hard to read, but whether the same thing could be expressed in way that would be simpler and easier to read. But I not sure to what extent this could be applied to poetry, since the expression in language is in itself "the thing".
- pjc50 9y ago"Unreadable" in this whole discussion should be taken as meaning "requires effort that the reader is not willing to expend", not an absolute. There are very few things that are impossible to read at all, even the notoriously and deliberately unintelligible stunt languages like INTERCAL and brainfk.
- pluma 9y agoI'd even go so far to say that the only way something can be literally unreadable is if it is physically impossible to do so (e.g. unrecoverable data) or there is not yet any known way of determining the meaning of a given text (e.g. the Voynich manuscript). But of course that isn't what is meant when we say something is unreadable because humans don't deal in absolutes (though programmers sometimes do, which is why programmers are so fond of using overly noncommital language like "should" and "most likely").
- pkolaczk 9y agoThere is often a world of a difference between code hard to read because it tries to solve a complex problem or is written in a paradigm I haven't learned yet, and code hard to read, because its author was just plain sloppy, and didn't properly care about naming or decomposition. Distinguishing between these two cases is a matter of enough experience.
- iovrthoughtthis 9y agoThis is a fantastic post that asks a question that I think many people just jump over on their way to "being right". What exactly does the thing we are talking about mean? In this case "code readability". I would add to this that "code readability" only means something to me in the context of it's intended audience. Code is readable when it is simple to decipher by the people that the author intended to decipher it. For anyone else to hold it to standards outside of those agreed upon by the author and the intended audience seems silly.
- pkolaczk 9y agoA problem arises, if there exists no group of people that the author had in mind when writing the code. Some programmers really just code "so that it works" and don't care about readability at all. That's why we have code reviews - a code review is an attempt to read the code. If at least one reviewer understood the code, then we can assume it was not completely unreadable.
- Davisss 9y agoDraudzīgākais Kredīts uzņēmumiem tava biznesa izaugsmei https://www.cityfinances.lv/kredits-uznemumiem/ https://www.cityfinances.lv/kredits-uznemumiem/
- DavidWoof 9y agoThis reminds me of the discussion of "quality" in Zen and the Art of Motorcycle Maintenance, where the class finds that while nobody can exactly define quality, when confronted with high and low quality writing everybody could recognize which was which. As OP realizes, nobody thinks Knuth's ACP is poorly written even though it's hard. The elegance is obvious, even if the algorithm is hard to understand. On the opposite end, I've come across FizzBuzz implementations from job candidates that I've struggled to follow. I've often seen a 10-1 difference in code sizes for different implementations of the same problem, and while there's edge cases where smaller code can start to become confusing, generally every dev on the team recognizes which of the two is more readable. I have no problem with the idea that there can be subjectivity in discussions of readability. But the idea that readability is purely subjective, or only has to do with differing styles is ridiculous. In fact, I don't believe for a second that OP really believes this. He wants to make a point about subjectivity, which is fine, but for some reason has chosen to write it in this exaggerated clickbait style.
- ignoramous 9y agoI think you're right. And the OP is right, too. There are contexts that OP clearly lays down where they think that programmers are too dismissive and try to stroke their ego at every opportunity and so the excuse of readability needs to be called out for what it actually is. Its an interesting piece, if nothing, the quotes embedded in them are worth their weight in gold. I wouldn't call it clickbait, though.
- gregjor 9y agoI had Zen and the Art of Motorcycle Maintenance in mind when thinking about readability, because that describes one kind of quality we care about. I don't think I wrote that "readability is purely subjective," I certainly didn't mean to imply that. I did mean to make a point about subjectivity. Sorry you didn't like the style. I write articles because I enjoy writing and I think I have ideas worth sharing. I don't have ads or affiliate links on my site, so I have no incentive to post clickbait.
- virgilp 9y ago> “Good code is simple” doesn’t actually say anything. [...] What we call “simple” depends on our experience, skills, interest, patience, and curiosity. I like Rich Hickey's stance on this: "simple" is objective (antonym: "complex"), whereas "easy" is subjective (antonym: "hard"). Easy depends on skills, interest, patience, curiosity - but simple does not. Simple is about lack of intertwining of concerns. About writing code that can be understood without "bringing in" the entire codebase into your mind. Like, you can understand a pure function just by looking at it (it's simple). If it modifies or uses a global variable, now you have to look at all the places that "touch" that global variable, in order to understand what your function does; the code is thus much more complex. With that definition - it's absolutely correct to say that the code should be as simple as possible. And that writing simple code is typically very hard.
- artimaeis 9y agoPython's PEP 20 utilizes this view on simple v complex, and also covers the idea of complicated. > Simple is better than complex. Complex is better than complicated. I've stuck by those two lines of PEP 20 since I learned about them. The object is to write simple code, but it's okay to write complex code if your goal is to avoid complicated (unreadable) code.
- virgilp 9y agoThat is a strange and "unnatural" (for me) use of the word "complicated". Cynefin[1] defines 'complicated' as "known unknows" and 'complex' as 'unknown unknowns'. The idea is that complicated things are non-obvious, but they are understandable (with expertise, you get the relationship between cause and effect). With complex, full cause & effect cannot be known apriori, it's just observable after the fact. That somewhat resonates with the definition that complex (code) is about intertwining - 'complex' is problematic because as things get more and more complex, you can have only a local understanding, and can't possibly hope to grasp all the implications of a code change. This suggests that "complicated" is something that is "somewhat complex, but still manageable with sufficient expertise/domain knowledge". I tend to use "complicated" to denote something that has inherent complexities (due to the nature of the real world); and "complex" to denote something that is artificially complex, due to ... well, lack of thought into making it as simple as it could be. In that sense, I view "complex" as being definitely worse than "complicated" [1]https://en.wikipedia.org/wiki/Cynefin_framework https://en.wikipedia.org/wiki/Cynefin_framework
- tekstar 9y agoI once had a developer who consistently wrote unreadable code while trying to be clever. To give him useful feedback I needed to come up with a black and white heuristic for knowing if code is readable or not. The heuristic is this: Readable code can be explained in English sentences in one pass. Your code tells a story. When you read it do you introduce the characters in the right order? Halfway through a complex passage do you reference something out of context without explaining it? Give concepts valid names to help the reader build context on your intent. The best part of this heuristic is that you can get the code author to attempt to read back their own code, and trip over their own convolutions, and realize where there is opportunity to simplify. We all worked on the same codebase so a reasonable shared understanding of the concepts was assumed. This blog post throws various situations into the mix to try to be contentious or something but misses the point.
- deleted 9y ago[deleted]
- JoeAltmaier 9y agoFits with my thought: code should be systematic. A collection of unrelated bits put together as by a committee is hard to read.
- gregjor 9y agoThat's called the telephone test. From The Elements of Programming Style (referenced in my article): "Use the telephone test for readability. If someone could understand your code when read aloud over the telephone, it's clear enough. If not, then it needs rewriting." I agree that the telephone test heuristic gives you an idea of readability, but in 1974 Kernighan and Plauger assumed someone one the other end of the phone who knew Fortran or PL/I. Trying to explain a moderately complex class hierarchy or a factory function or a closure over the phone would prove challenging. I could explain the purpose of the code at a level someone else could understand, but they might not recognize the implementation when looking at the code. A few years ago, doing maintenance on an abandoned production system, I came across a function with the comment "Produce a unique six-digit identifier that doesn't start with 0". The original programmer could have explained that to me over the phone, but his implementation (in PHP) was not clear at first or second glance. I expected this: $id = rand(100000, 999999); Instead the function started with a loop to get the first digit: while (true) { $first = rand(0, 9); if ($first != 0) break; } I'm not making this up. Then another loop to pick five more digits in the range 0..9. Then a database query to see if that ID was used, and if it was the function called itself recursively. I'm not kidding. So while I would have understood the problem described over the phone, I didn't recognize the implementation at first sight. If the programmer had read the code to me over the phone I might have assumed I was missing some requirement that led to this overly-complicated implementation. Not all of the code looked like this so I don't know how the original programmer got wound around the axle on this function.
- dablya 9y agoThere is a difference between reading legacy code without empathy (sympathy? pretty sure it's empathy) and calling code equivalent of Macbeth as unreadable when Cliff's Notes would do...
- Quarrelsome 9y agoI work on a system where arbitrary property access results in database round-trips. So the following code: foreach(var b in a.Bs) { if(b.Data != null) { ThisIsInteresting(b); } } results in a.Bs.Count + 1 round-trips to the server and then database if these fields have not been accessed before. (a.Bs is one and b.Data != null is one as well). This is a fine example of what I'd call "unreadable" code because there is so much activity that is implied by actions that in other systems are completely innocent and well isolated. Also there is the point of cognitive load. If your entire application was simply one function it is technically "readable" but the cognitive load of trying to work out what is in scope and what might change a given variable is too high to read without extraordinary effort. When working in such systems (as I have before) you HAVE to rewrite it to even start reading it because a human memory cannot hold all that information at one time. I think brushing it all of this off as "the reader isn't reading well enough" is disingenuous.
- LanceH 9y agoYou'll know it when you see it.
- lambic 9y agoI often refactor code as a way to understand it; working through the logic and rewriting it in my own style helps me get a good grasp of what the original code was doing. Sometimes I throw away that refactoring if I realise that the code I was having trouble understanding was actually fairly well written and I just need to sprinkle in some comments.
- danschumann 9y agoSome good points. I think code-readability should be measured by people who are as accustomed as possible to the code base. IE, if you wrote all the code, how quickly can you refresh your memory ( 6 months later ), as well as trace down bugs.
- stinos 9y agoThe author is spot on for 'standard' code styles. However when you enter the realm of crazy code styles (say, all code of the program in one single line, obfuscated code not meant for humans to read and so on), wouldn't we all agree that is in fact, objectively, unreadable? Beacuse actually reading it is simply too hard no matter how skilled and knowledgable you are? (note none of the OP's points cover this, except for 'The code offends my sense of aesthetics' maybe, but by a stretch). And extending this somewhat further, I have already seen code written by humans which I am confident the vast majority of programmers would consider unreadable. Unfortunately including the guy who wrote it.. We're talking mixing indent witdhs/seemingly mixing all known code styles/complete lack of consistency/lines of hundreds of characters/big chunks of >20 newlines/... I think there is a point where this becomes unredable and it's not the reader who is to be 'blamed'.
- hashkb 9y agoHe doesn't need to say "btw there's still some actually really terrible code out there" for us to know he knows it's true. He's making a point that wouldn't benefit from going there.
- dang 9y ago> wouldn't we all agree that is in fact, objectively, unreadable No, because there's a rich body of counterexamples in the array-oriented languages (APL, K, J). Everyone who doesn't know these languages immediately dismisses programs written in them as unreadable, but that is far from the truth. If you spend some time in the alternate programming universe that such languages inhabit, you'll get into your bones the knowledge that readability is relative both to language and to reader, and you'll start to think about simplicity in a deeper way. (By "you" I don't mean you personally, of course, I mean everyhacker.)
- crdoconnor 9y agoOver time the first thing I've come to desire more than 'intrinsic' readability when joining a new project is a decent, up to date, hyperlinked glossary with all of the relevant acronyms and terms that will be used in the code. I've had variations on this conversation many times before: * New coworker (me): What's an XYZ? (some core thing in the system) * Coworker 1: An XYZ is [blah blah blah]. * Coworker 2: Actually, an XYZ may not be [blah blah] it could be [blah]. * Coworker 1: No! That's not right! * Me: ugh...
- bradfa 9y agoThe biggest helper for me when trying to read other peoples' code is having a document (or documents) which describe what the heck the code is supposed to be doing in human terms. This is especially true when I'm not super familiar with the business history, long forgotten bug fixes, and nuance which was previously worked around or implemented. Software documentation almost always sucks, in my experience. When I do find well written documentation that reflects the code, it becomes much easier to understand the code quickly so that I can make the changes I want to make. But nobody likes writing documentation.
- jasonmaydie 9y agoI don't like the shakespeare analogy because not every written piece of code is supposed to be a work of art. You wouldn't write an instruction manual like you would write Macbeth. Most of the time there's really no value in writing cryptic code
- Miss_Vee22 9y agoYou are saying that programming is the same as an instruction manual? Programming is art. Nearly every objective in programming will have over a million potential implementations. Personality, wisdom, and mood are in every program (obviously there are some Hello World exceptions) just like artistic writing and nothing like an instruction manual. Machine code is an instruction manual compiled by a computer, a program is a piece of art created by humans.
- jasonmaydie 9y agowell no. You can write artistic code, people do that in coding all the time (in programming contests, sample code, your own code etc) but the real goal of writing code is to perform a certain task. The execution of those instructions is what matters, not the style of how the code written. So yea not all code is art.
- catpolice 9y agoThere's a sense of "unreadable" that I sometimes use that means "the code does not contain the information that you need to understand how it will typically function". E.g. things that have internal control flow determined by complex input processing where the input is ill-specified. It can be essentially impossible to put together a mental picture of the operation of the program, because key parts are essentially unspecified. And there's a related sense that I occasionally use to describe code that's so difficult to follow (in the sense that the control flow or structure is needless obfuscated) that the process of trying to understand it doesn't really resemble simply "reading". Some examples: A function is called in many places in es6 code. I want to see its definition, my editor can't figure it out. I look at the import statement, it's imported from a file. I open that file, and all it does is export * from a dozen other files - so now all I know is that it's in one of these dozen files. I am reduced to doing something like grepping for the function name and looking for the case that looks more like a definition than a call. At one point I was reading the code, now I'm doing something related and more involved than just reading. Or, in this system components emit message objects with a "title" field. The messages are dispatched to dozens of functions across files that inspect the title field to determine if they do anything with it. Only they don't just do a simple comparison against a string literal, they check if the title meets a regex. There are many of these different regexes. I read the code that emits the message and I want to know what behaviors the message being sent out triggers - how do I track that down? I can't even grep for the message title. In order to make a list of things this message might do, I have to look through everything that might possibly handle the message and try to figure out which regexes are triggered. In this case, reading is involved in the same way that reading through a math book and solving the exercises does involve reading - that's not where most of the work comes from.
- tjwii 9y agoReadablility is definitely not similar to understanding. The problem I have with reading code from other codebases is not understanding the coherence. Naming of variables is a great deal here, one poorly chosen name can totally confuse me. And still it is highly subjective because an other developer might instantly see the relation just by chance. If you're unfortunate enough to code full-stack web apps then you'll likely be dealing with hundreds of npm libraries you've never heard of! How can you know all possible effects and side effects of 1 simple call to a method in some library? That alone would be a quite a study in some/most cases. It would be great if for any project you can find at least an overview and explanation of the coherence that the files and used modules have in relation to each other. But unfortunately that is often missing already to start with, so you end up with a vast and often unsolvable puzzle. Programming computers is still in its infancy. We definitely need better tools and structures to understand what's going on IMHO. It makes me laugh when people tell me they solve this with a linter.
- arkh 9y agoDoing a lot of code maintenance what is the worst is most "smart" things. Every time I get to some indirection to be smart and I can't just ctrl-click on some line to get to the definition I'm angry. I don't want to check what is there at runtime once the configuration has been loaded. I don't like going through 10 get("serviceName")->handleSomething() and having to check where those services are defined. I really don't like having to go through 20 abstractions trying to find who fucked some data on the way in my debugger. I know, your 3 loc per method codebase felt good to write. The added useless junk around the code (function definition and {} on their line) means even with a 4k monitor I can't see your full algo in one page. Using reflection magic? Please don't. I like dumb code which shows what it does and can easily be followed. And that's coming from someone who likes the ${whatever returns a string} method of defining dynamically named variables in php: it feels always fun to write. But it is a hindrance when debugging. And when debugging the less "small shit" you have to deal with, the more brainpower you have to focus on finding the problem.
- sigjuice 9y agoFor me code readability means that the code I write today makes sense to me next week :p
- sound1 9y agoTotally agree with thus one :-)
- harrisjt 9y agoClean Code I think is the best resource on readability. Your code self-documenting while following simple software principles is difficult but ideal.
- gabemart 9y agoThe author consistently compares code language style to literature language style, but I don't think it's a helpful comparison at all. Literature operates by an intractably complex interaction between the words written on the page and the mind of the reader. Exchanging a single word for another may totally alter the effect of a passage, based on factors like the meaning of the word, the associations the word has for each reader, and the aesthetic appearance and sound of the word. Moreover, we have no objective way of measuring the effect of literature. We don't have a test that can measure how much more empathetic I become after reading a novel, or how much more I understand the human experience. Computer code typically has measurable outcomes. While "readability" may still be a relatively subjective measure, we can at least say "these two versions of this function are equivalent" if the outcome is the same - the array is sorted correctly, the transaction amount is calculated correctly, the graph is rendered with the same pixels. This means that editing computer code is nothing at all like editing literature. The cliff-notes version of Macbeth can never produce the same effect in the mind of the reader as reading Macbeth -- but a function that is subjectively easier to read can be shown objectively to produce the same effect as the original function.
- ken 9y agoI don't think that software and literature are inherently different, but I do agree that this post tries to stretch this metaphor beyond its limits. The first 4 of 6 proposed meanings of "unreadable" are some variant of "It's objectively fine but I don't happen to like it". I wonder if his experience is one where one sees a lot of high-quality but foreign-looking source code. The article says: "By analogy, plenty of people find reading Homer, Shakespeare, or Nabokov difficult and challenging, but we don’t say “Macbeth is unreadable.”" When I say some code is "unreadable", I'm very much not saying "It's like that Scottish Play". Shakespeare had a reason to create a convoluted plot for his story. He specifically edited it to be like that. Unreadable source code is usually (IME) a historical accident, often caused by multiple programmers on the same work. Give 3 writers a copy of one of Shakespeare's plays and tell them to each, concurrently, add a new character to the story, and you're not going to end up with a play of equal quality as the original. I'm not sure I could name a significant program in use written by a single author (Redis might be the closest, in spirit), and some have dozens or hundreds, yet the average book on my shelf here has between 1.0 and 1.1 authors. It's not surprising, to me, that the average program is an incoherent mess, compared to the average book. Perhaps "Literate Programming" is a good idea, but we've been missing the point. What qualifies a work as Literature is not great typesetting and hardbound publishing and complete sentences, but something simpler: single authorship. "Should we strive to satisfy the Shakespeare for Dummies demographic?" My understanding (and I admit it's been a while since I've studied Shakespeare) is that Shakespeare was written for the commoner. The study guides I've seen for it are almost entirely spent defining words that haven't been in common use in 100+ years, and the occasional cultural note. (When's the last time you spoke a word that ended in "-'st" or "-eth"?) If you gave me some FORTRAN-IV code I would struggle at first to understand it, as I do with Shakespearean English, not because any of the concepts are hard but simply the dialect is unfamiliar.
- deckar01 9y agoTime is a commodity. The extra time spent reviewing or maintaining code that is difficult to read would be better spent writing the code well the first time. In open source development, a maintainer’s time is often extremely limited. If you can’t make your code easily readable for that maintainer, then your contribution is worthless. You have created an asset with a transaction fee that prices you out of the market.
- deleted 9y ago[deleted]
- tomxor 9y agoI think it's necessary to expand on the authors definition of "complex" vs "simple"... Things can be "complex" and thus hard to read for many difference reasons: At one extreme the reader is definitely responsible for things like understanding an underlying algorithm - the algorithm chosen might be a good choice, but it might also be very complex. It's not always possible to clearly convey an efficient implementation of a complex algorithm in code - It could be argued at the most that the author should name the algo in a comment, but litering the implementation with comments describing the algorithm would make it harder to read for someone who is familiar with the algorithm. At the other extreme there are all kinds of unnecessary complexity that make it hard to read, some by poorly suited forced design patterns, some by cruft that accumulates and some by un-refactored growth (big ball of mud). One of my pet hates is highly layered object oriented code where someone has gone to painful ends to generalise and modularise the fuck out of every single routine to the point that the overhead of traversing the hierarchy to determine what actually happens in what order with what side effects when you call one of the outer layers of that ginormous onion is humanly impractical. I'd call that unreadable code due to complexity that the authors are responsible for.
- bluesnowmonkey 9y agoThe article hints at it, but your sense of the readability of a codebase changes the longer you are exposed to it. Patterns that make it easier to become moderately competent in a particular codebase can actually make it harder to become expert. So if you want to maximize readability, you need to estimate how long future maintainers will live with your code. Will they drop in and do a single commit and never look at it again? Then make sure everything you need to understand a piece of code is right there next to it. Will they work on it for a long time, changing many parts? Then be very consistent with the patterns and idioms you use across the project, so that their previous experience changing other parts of it helps them understand how to make the next change.
- palakchokshi 9y agopublic class A { private int exid; private string M; public A() { M = "The result is:"; } public string y(int u, int v) { return M + (u+v).ToString(); } } public static void Main() { Console.WriteLine(new A().y(1,3)); } Now add hundreds of lines of such code and you'll get unreadable code. It is not in the eyes of the reader, some code is just unreadable. This is an extreme example though.
- aplorbust 9y ago"Greg Jorgenson is a typical programmer." Then who are all these commenters in mailing lists, forums, blog posts and source control systems who are proclaiming code they cannot read as "unreadable" or 'unmaintainable"? Clearly the author is aware these comments fall into the categories he mentions; they are reframing "I can't read this code" into some sort of pseudo-objectivity. If typical programmers are aware of this practice, then who are these commenters labelling things they cannot read as "unreadable" or "unmaintainable"? Are they "typical programmers"? Can we respond to those labelling code as "unreadable" or "unmaintable" by pointing out that they really mean "I cannot read this code"? Will they acknowledge, "Yes, what I meant was I do not know the language well-enough to understand that code, but others might be able to read and edit it."
- simonblack 9y agoCode readability is when you are able to pick up the source of a program that you haven't looked at in 10 years and instantly understand it without having to study it intently.
- yulapshun 9y agoTo read code is to understand it. It has little to do with style but more to do with program structure and abstraction layers. I've maintained a PHP codebase with some of the worst code I've ever seen. For Example: 1. A function with a few thousand lines of code, accepting dozens of parameter. The body is made up of some nested switch-case and if-else. 2. Instead of using constructors, every class has a static method that does nothing but initialize itself. 3. A class which queries DB and generate HTML, with nearly a hundred public variable. A few levels of sub classes with functions to update those variables. When a piece of code is not obvious in what it's doing, I'll call it unreadable. In some cases this is acceptable, for example in some clever algorithm (https://en.wikipedia.org/wiki/Fast_inverse_square_root https://en.wikipedia.org/wiki/Fast_inverse_square_root), but it is still what it is, unreadable.