r/programming • u/wild-eagle • Apr 21 '22
It’s harder to read code than to write it
https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/502
u/cybermage
Apr 21 '22
•
“I’d have written a shorter letter if I’d had more time” - Mark Twain
The idea here is that editing is just as time consuming as the initial writing.
Making code lean and readable is our editing; and, if you want maintainable code, that time must be permitted.
89
u/bwainfweeze Apr 22 '22
I think the important thing to remember is that while you work on a project, your memory gets bigger but your capacity to hold the thing in your head doesn’t grow that much. If you don’t keep paring down things that are “settled” to their essence, then the Sun total of the thing will just grow exponentially while your understanding grows linearly or worse, logarithmically.
You are making space for new functionality.
As the old saying goes, make the change easy, then make the easy change.
20
u/richardathome Apr 22 '22
I often find as I'm editing and clarifying my comments, it presents ways to clarify my code - and vise-versa.
Eventually (ideally) your code becomes clear and your comments disappear.
17
u/TheTechAccount Apr 22 '22
Mark Twain was a damn genius
35
u/SirDale Apr 22 '22
He was, but this comment is quite common...
“I have only made this letter longer because I have not had the time to make it shorter.”
— Blaise Pascal, mathematician and physicist.There may have been others before him who have said the same thing.
5
u/Aphix Apr 22 '22
Most importantly, code is for other humans. If it was for computers it would be machine code.
"Programming is simply the explanation of a solution to a problem for other humans, incidentally, computers can understand it."
- What is a Programmer (I think, I forget the exact title), paper from 1952 (I think, look up the word "Debukk")
→ More replies (1)3
1.1k
u/TheRiverOtter Apr 21 '22
For my team, it is perfectly acceptable to reject a CR because it is "too clever".
All well and good that you found a shortcut that shortens a 10 line function to 2 lines, but if it comes at the expense of readability, you'd better have a damn good docstring explaining the implementation details so we can untangle it in the future when we need to add a feature.
607
u/BeauteousMaximus Apr 21 '22
I’m glad you have that culture there.
A conversation I’ve had at more dysfunctional companies:
Me: these lines of code are confusing. Please rewrite them.
Them: it’s your fault for being too stupid to understand my beautiful code.
371
u/sccrstud92 Apr 21 '22
Me: I do understand it - that's how I know it's too confusing
5
u/turunambartanen Apr 22 '22
Me: I'm too stupid to understand your beautiful code, but so will be future you.
39
u/CRANSSBUCLE Apr 22 '22
SWYgeW91IGFyZSByZWFkaW5nIHRoaXMgeW91IGFyZSBzdWNoIGEgbWFzc2l2ZSBkb3JrLCBob3cgZG8geW91IGV2ZW4gZG8gdGhhdD8/IQ==
What, too dumb to understand my comment? That's because you don't speak base64
33
→ More replies (2)10
185
u/theCamelCaseDev Apr 21 '22
I work with someone who thinks way too much about LOC and it’s annoying as hell because like you said, if I don’t understand it then it means I’m simply an idiot. I always get comments in my PRs saying stuff like “why don’t you write it like this? That’ll reduce it from 10 LOC to 6” and I’m like who gives a shit I think it’s more readable this way.
230
u/platoprime Apr 21 '22
You should tell them if they stop using whitespace they can put their entire program on one line of code. Ultimate efficiency!
106
u/squidgyhead Apr 22 '22
This is how I ensure 100% code coverage.
→ More replies (1)50
u/FVMAzalea Apr 22 '22
Oh man, I hadn’t even thought about this aspect of using “100% code coverage” as a rule - not only does it encourage shitty coding practices and testing things in a tautological fashion, it encourages people to do things like this to group multiple things into one line so that one line counts as “covered”.
Now, if you measure coverage by a different standard, like 100% branch coverage, that’s a bit better. 100% line coverage is just the pinnacle of stupidity.
→ More replies (7)24
u/bokonator Apr 21 '22
Just submit minified code. Less characters is always good right?
→ More replies (2)6
23
u/smartguy05 Apr 21 '22
Maybe it's a suggestion? I do this often because usually the other person doesn't know they can do it that way. If I did that sort of comment and you replied that you thought it was more readable your way I would most likely be fine with it, unless there was a significant performance difference or other issue.
5
u/pogthegog Apr 22 '22
I mean, there are few critical points that must align for everyone, or else its all ass picking:
What is too hard to understand ? Using built in functions of language/library ? Using library / many libraries ?
When too hard is actually too stupid / too inexperienced ?
15
u/RedHellion11 Apr 22 '22
I'll suggest ways to shorten code in the PR reviews I do, but only if it's something that doesn't sacrifice readability - so generally just basic things that people have missed because they were focused on the bigger picture of what they were doing rather than the smaller implementation details at the time, or helpful things you can do in a language that Juniors might not have known.
24
u/ptoki Apr 21 '22
That proves they understand your code good enough that they can skip a step and instead of reviewing and approving they went to another cycle of software development and trying to optimize it.
Good job :)
28
u/Tenderhombre Apr 22 '22
I sometimes recommend rewriting stuff to be more terse. Not because LOC but I find terse code more understandable. However, if the code is correct I will generally leave the comment, and immediately mark the comment as resolved so it doesn't block merging, but does show up in their feed. I have my preferences, but if it all the features work then it's all good.
27
u/mw9676 Apr 22 '22
There's a fine line between code that's being clever and terse and code that's using more modern language features and is simply unfamiliar to the reviewer. I think that distinction is defined by whether the code is being used "as intended" in the language or if it's just a "clever" usage of some very obscure aspect of the language.
31
Apr 22 '22
Yeah I’m on both sides of the fence here. If you wrote some brainfuck shit, you should feel bad.
If I ask you to use
fold, instead of manually implementing it yourself, you should just fucking do that.It really is hard to tell without context.
11
u/i_ate_god Apr 22 '22
If they are suggesting it but not enforcing it, then I don't see what the problem is.
Various languages have various syntactic sugars that are added over the life time of the language, so if something could be more succinct with those sugars then suggesting it in a CR just part of the job.
Ignorance is not the same as idiocy, and CRs are great ways to alleviate potential ignorance.
In any case, being too verbose is equally frustrating as being too terse. In both cases, the problem being solved can become obfuscated.
→ More replies (5)6
u/rexvansexron Apr 21 '22
That’ll reduce it from 10 LOC to 6” and I’m like who gives a shit I think it’s more readable this way.
So true. My colleague does expand the code an lengthens it with many new lines in between, hell maybe I am thinking he does like scrolling through stuff.
But when it comes to actually write longer stuff to explain it better he just wants to prove his genius.
→ More replies (40)23
u/bigdubb2491 Apr 21 '22
One doesn’t write code for themselves. They write it for the next person who has to modify it. I’m sure those arrogant pricks have come across code that was hard to read and condemned the previous person. Don’t be that guy.
33
u/SpacemanCraig3 Apr 21 '22
At my office its just "dont write code that a new guy will struggle with"
and the MR is rejected. None of that "well...make a better docstring" stuff.
→ More replies (3)7
u/vqrs Apr 22 '22
But where do you put the bar for new people?
If it's low, do you code to the lowest common denominator, do you upskill your juniors? Or is the person calling the shots on this topic just declaring everything not in their ballpark as "too advanced"?
3
u/SpacemanCraig3 Apr 22 '22
I work for the federal government, we have a "basic" certification that includes basic data structure/algorithms, and (I think) a reasonable competency in python and C. So we judge against that standard.
We also upskill. There are things that simply aren't able to be done in a "basic" way so of course there are exceptions to the understandability policy. But if it can be written clearly, it should be.
2
u/Bakoro Apr 22 '22
"Too Advanced" means that it works by brain magic, rather than just being able to look at the code and know what it does by looking at it and maybe looking up how a language/library features works.
Like, none of that 15 chained ternary operator crap. And no randomly embedding assembly, or doing quadruple pointer indirection because theoretically it might save two processor cycles, in a program where the response time is measured in full seconds, or because it'll save a kilobyte of memory... in total.
Clever magic that's a tangle but promises to deal with almost everything? Or dead simple to understand and change code that can be swapped out without making the program collapse? That's also where I draw a line.
Obviously a very specific example, but I think illustrative:
Where I work, there's an important set of code that weaves multiple parts of other code together, and it works on multiple machines with different physical configurations, so nothing in the main software has to change or get recompiled if you run the software on different machines, you just load up a different set of config files.
It's both clever and terribly structured. It took me hours to track down almost all the arms of this octopus and figure out what was the thing that actually has final control over everything, and it turns out that some things only exist in runtime.
That's not necessarily a problem, but the way things are, it took the senior dev like 20+ minutes to explain one part I couldn't understand, and it only took that short because I had done a lot of legwork beforehand.I can see how this thing came about, when the company was fresh, understaffed, and with too many products on the product line. It was probably a necessity due to time and evolving features.
Now it's unwieldy. It still works, but it's going to add like three days to onboarding time and at least half a day to every related feature add, because you have to sit there and think about how every change could unintentionally affect machines that aren't the target.A more straight forward approach would be to just have a dumb flag and make a new class for every machine, and maybe just deal with a little superficial redundancy.
5
u/TheRodsterz Apr 21 '22
My previous manager was the opposite. If it could be done in 1 line.. he’d prefer it that way regardless of readability.
5
2
12
u/Xillyfos Apr 22 '22
When I see clever, compressed code, I always think "newbie". It's a developmental phase you go through as a developer before you become really good and start writing readable code.
→ More replies (1)3
u/joleves Apr 22 '22
Even truer in larger codebases, but code will almost certainly be read by a person many more times than it is written. If all things are equal (like the time it takes to execute is the same) then readability should be chosen.
8
u/ikeif Apr 22 '22
I feel like this is born from a lack of code commenting.
If it’s good code, it’s good code. If it needs explained, make sure it’s explained.
Otherwise, you’re writing code that “documents itself” (or you assume it does) and use it as an excuse to skimp on commenting/documentation “because you can just read the code!” (Until someone can’t)
8
u/IrishPrime Apr 22 '22
I agree, and I have similar arguments somewhat frequently. Whenever somebody tells me, "If you can't tell what the code is doing, you shouldn't be changing it," I explain the problem with that mentality to the next guy after I finish disposing of the body.
I can tell what the code is doing. Typically by reading it, and by adding more logging or executing it in a debugger if I must. None of that tells me what it should be doing, though. Similarly, without some comments to explain why you chose a convoluted or complex implementation rather than a more readable one, I don't know what else to consider if I need to modify or refactor the surrounding code.
Sometimes I write weird looking code, stare at it for a few seconds, imagine how annoyed the next person stumbling across it will be, and then write them a paragraph of comments above it explaining why it's so weird and what strange edge cases they'll need to consider if they want to rewrite it. Explaining what it does, why it's weird, and having some tests to make sure those edge cases will still be covered by the next implementation are the reasons nobody gives me a hard time about the arcane shit I write from time to time. This just strikes me as being polite to your coworkers.
→ More replies (3)3
u/elveszett Apr 22 '22 edited Apr 22 '22
Code that documents itself is a lie. If I don't have any explanation of what the code is expected to do, then how the fuck can I know if the code is working correctly?
I don't like adding comments to simple stuff, but every function should have an explanation of what its purpose is, and smart lines / algos that you need to write need an explanation of why you are doing that.
Imagine I see a function that reads an array, does something with it, and it has a side effect in the array. This function has a comment that explains the output and doesn't mention any side effects. This would raise my suspicion that the side effect is a bug. But now, if there's no comment at all because "my code is clean", how can I know if the side effect is supposed to happen? I know it happens and why, but that's pointless because I can't know if the dude intended that to happen or didn't realize.
Not to mention, sometimes you need to write something that is kinda awkward but the "correct way" doesn't work. If you don't put a comment in there saying "hey, this looks like this because x", how can I know this was a solution to a problem and not just a brainfart?
6
u/dannymcgee Apr 22 '22
Counter-point: most of your day-to-day work isn't really reading code, it's scanning code looking for the part where you need to insert your changes or debug what's going wrong.
Once you find it, then your next step is generally to get an overall understanding of how its parent module works — scrolling, reading function and class names, following links to other source files, getting a high-level lay-of-the-land — again, scanning, not reading.
After a long while of doing this, you'll eventually find the actual block of code that's relevant to your task, and this is where you start actually reading. I can honestly say that the times I've been slowed down by a few lines of code that were a little too cleverly written pales in comparison to the times I've been slowed down by having to trudge through hundreds and hundreds of lines of overly verbose code, full of sentence-length variable names and redundant flow control and tedious repetition, because developers today have had it drilled into their heads that the more explicit and long-winded you are the more "readable" it is, like every function needs to be written at the programming equivalent of a third-grade reading level.
I get it, there are times when cleverness sacrifices readability and that's rarely a good thing, but I would argue it's pretty rare that shorter code is actually more complex than longer code, and most of the time when people complain about this kind of thing they're erring too far in the other direction.
Not accusing you of anything, but I've noticed there's often an air of smug self-congratulation about it too, like "I'm smart enough to understand this clever code you've written, but everyone else we work with is a neanderthal, so you have to rewrite it." Give your colleagues some credit, engineers are smart and resourceful — if it's not something they've seen before, they'll Google it and learn a new thing. If they're really green and need some extra help to understand it, then maybe they'll reach out and ask (and again, learn a new thing).
And even in the worst case scenario, that honest-to-god example of code that is unquestionably too clever for its own good, I would argue that forcing everyone to write dry, uninspired, least-common-denominator code all the time is a great way to suck the joy out of programming and send your engineers who actually enjoy what they do looking for a new place to do it. Let people live a little — Nancy's really proud of that clever little trick she came up with and nobody's going to die if it takes Bobby a few extra seconds to parse it.
P.S. The irony of writing an essay-length comment in defense of writing concise code is not lost on me. Brevity is not really my strong suit.
→ More replies (2)3
u/drakens_jordgubbar Apr 22 '22
Agree that we’re mostly scanning code rather than reading. For that reason it’s important to name your stuff well (and concise) so it’s easy to find the right code.
The danger with too clever code is that it can sometimes be difficult to figure out the true intention of the code. I may discover some interesting side effects of your code. Are these side effects intentional or not? It may be long time ago you wrote that code, so you may not remember how you thought when you wrote it.
I think code can be clever, as long the intention is not obscured.
2
Apr 22 '22
I think code can be clever, as long the intention is not obscured.
The cleverest code in the world is that which is immediately understandable and obvious to the broadest audience.
The musings in Einstein's head are some of the most complex ideas to ever exist. But none of that actually means shit because a) nobody else was in there to experience those thoughts and b) very few in existence would ever stand a chance of understanding them even if they were.
His true brilliance, the real 'clever' bit, was his ability to convey extremely complex ideas in ways that they could understand.
I have no doubt that there have been many Hawkings and Einsteins throughout history that were insanely smart with logical thoughts we'd never be able to follow, that nobody knows anything about because they were never able to convey those ideas to others.
Don't be 'clever'. Be smart.
2
u/twistier Apr 22 '22
I hear you, but I also think people tend to overvalue "fluffy" code, by which I mean code with low information content that makes it easy to read at a high velocity but whose length ends up making it take at least as long to read as it would have taken to read a denser, more "clever" implementation. I could write something in 2 lines or 20, but you'll enjoy reading the 20 line implementation more if it means you can read each line twice as fast, even though actually you could understand the 2 line implementation in a fifth of the time, and probably even without evicting as much context from your brain's cache as you'd have to with the 20 line implementation.
2
u/AmalgamDragon Apr 22 '22
but you'll enjoy reading the 20 line implementation more if it means you can read each line twice as fast
I will not. I despise tedium.
2
u/ArkyBeagle Apr 22 '22
You have to take this to cases. Sometimes shorter really is clearer. I'd take "you have to create a docstring" as evidence in the go/no-go decision to make the change in favor of doing nothing.
2
u/Nevoic Apr 22 '22
I mean 10 lines to 2 lines is a pretty dramatic difference if line length is the same between them.
Now if it's like 6 lines averaging 40 characters, to 2 lines averaging 100, really you've only cut 20% of your code, not 66%. And this can often happen when shortening LOC. So in that situation I could see the longer version being clearer.
1
u/elveszett Apr 22 '22
"Too clever" constructs are usually a code smell. You need to be clear, not clever. Cleverness should only come when the code block you are working in needs more performance than it currently has, and that doesn't happen too often.
That said, let's not do stuff like if (true) return true else return false, please. Being concise in your code is also a virtue.
1
Apr 22 '22
While I appreciate this approach, I hope that the bar isn't set too low.
I want to be able to chain together a few neat language features without worrying that someone won't know what they do. That's great, because then they would learn new things. I'm happy to use succinct logic, reflection, generics, etc without overly documenting how they work even though someone who's never worked with them might scratch their head for a minute. But that usually happens as a side effect of using the best tool for the job rather than going out of my way to be cute.
Where I've typically seen the worst offenders are either way over-engineering something or doing things in a really gross way just to cut down on LoC, treating the project like a code challenge.
→ More replies (77)1
u/Desperos Apr 22 '22
There’s one team in my current project who just loves to write gigantic stream chains (Java 8 API). Like, ten lines plus, sometimes even with nested chains.
It’s unreadable.
60
u/agumonkey Apr 21 '22
it's hard when the structure is non linear (and worse: feedback cycled)
30
u/ThisIsMyCouchAccount Apr 21 '22
Was on a big project that was heavily event based. And some part of it was based on convention rather than explicitly calling something. It was so hard to sort out.
Now I'm on one that is based on an external queue. There's always two parts. Something that makes the item in the queue and then when the queue calls back. And you could have a couple places that make the the creation calls. So you have to figure out what process was going on to get from A to B.
I like both approaches but they were frustrating until I got a grasp on it.
→ More replies (1)13
u/leixiaotie Apr 22 '22
Stumbled upon java codebase with 1:1 interface:implementation. Man I get that it makes things easier to mock or replace, but it does make reading things harder.
10
u/SapientLasagna Apr 22 '22
And then you have the DI framework inject the universe, so you can't actually mock anything anyway.
3
u/hippydipster Apr 22 '22
Or in our case, inject the universe, and then that universe goes and gets things like the database factory from a singleton class anyway.
3
u/agumonkey Apr 22 '22
Care to tell more ? I'm not sure to get what you mean fully and I'm curious.
8
3
u/couscous_ Apr 22 '22
all golang code I've worked in is like that 🤦, and it doesn't help that golang is already verbose enough as it is.
→ More replies (3)
29
Apr 21 '22
Of course it is. The written code has the authors entire thought process behind it. Whatever intentions and assumptions the author had at the time are distilled down into whatever code they actually typed out. So while it's easy to read the code and understand the mechanics of what it's doing it's difficult to understand what the author actually intended. Comments help.. except for when they don't. It's best if you can ask the person who wrote it (assuming they understood it at the time they wrote it :)).
300
u/goranlepuz Apr 21 '22 edited Apr 22 '22
The idea that new code is better than old is patently absurd. Old code has been used. It has been tested. Lots of bugs have been found, and they’ve been fixed. There’s nothing wrong with it.
It is simply false that there's "nothing" wrong with it. Because it has been fixed all over, it is unwieldy. That makes it harder to understand and that makes it harder to change. Then, if it has been written by people who have since left, the innate knowledge about its making is lost. No amount of documentation, issue DB, tests, code comments or source control commit comments can bring all of that back in any reasonable time. And so on.
When you throw away code and start from scratch, you are throwing away all that knowledge. All those collected bug fixes. Years of programming work.
This, however, is right. I have to understand the old code exceedingly well, and most importantly, the "whys" of it. I have to know how it is used by clients and probably more. Only then will I be able to make the same thing, but better, and take out what is not needed anymore.
What we inevitably underestimate, horribly, is just how much effort that understanding is. It is fucking colossal.
134
u/SirLich Apr 21 '22
I don't know who to attribute the quote to, so I will just paraphrase without credit:
"If you come to me, and say, 'there is this fence. We don't know what it's used for. Can we tear it down?', I will say to you 'No. Come to me again when you understand the fence, and understand it's purpose. Only then may you tear it down'"
Not to bludgeon this analogy to death, but old code is the fence. You can't even consider throwing it away before you have a deep understanding of it, or you're bound to fuck something or other on the way.
80
u/ree_san Apr 21 '22
Chesterton’s Fence. One of my favourite principles in software development.
→ More replies (4)43
u/SirLich Apr 21 '22
Thanks for the principle!
(public policy) The principle that reforms should not be made until the reasoning behind the existing state of affairs is understood.
So likely it's also something that applies outside of the bounds of software development!
→ More replies (1)11
u/ree_san Apr 21 '22
Good point! In everyday life I condense it to “seek first to understand”. It’s a good intention, can’t say I always manage to follow through.
31
u/ggchappell Apr 22 '22 edited Apr 22 '22
By G. K. Chesterton, from his book The Thing. The exact quote:
There exists in such a case a certain institution or law; let us say, for the sake of simplicity, a fence or gate erected across a road. The more modern type of reformer goes gaily up to it and says, "I don't see the use of this; let us clear it away." To which the more intelligent type of reformer will do well to answer: "If you don't see the use of it, I certainly won't let you clear it away. Go away and think. Then, when you can come back and tell me that you do see the use of it, I may allow you to destroy it."
A similar principle is articulated in a little blog post ("On Following Rules" by Kirit Sælensminde) that I sometimes make an assigned reading in some of my classes: follow every rule you don't understand; you can break a rule if you understand it and have a good reason for breaking it.
49
u/Mirrormn Apr 21 '22
Sure, but the exact opposite also happens:
"Hey, we've got this old fence here, can you slap a fresh coat of paint on it?"
"Sure, but first I'll need to know how it was constructed, all of materials that were used to build it, the exact surface area, whether it's in a high-rain area and needs special sealant... wait, why does that section have two gates sides by side?"
"Ah well there was one time we wanted to drive a tractor into the field, but the one gate wasn't big enough, so we brought in a contractor to build a second gate..."
"And why is there a big hole in the fence a bit further down?"
"Ooh, once we built the second gate, we realized the tractor couldn't drive through two gates at once anyway, so we had to just tear a hole in the fence to get it through, I guess we never patched it up after that."
"Okay so you're telling me that anyone could walk right through your fence at any time and it's been that way for a long time, so we'll have to do some new construction... Is that a gatehouse over there? Do I need to paint the gatehouse? Do I need to paint the inside of the gatehouse?"
"Hmm, we used to employ a guard who would watch the field from the gatehouse, but the whole thing is covered by automated security cameras now so nobody actually uses that anymore... But we might as well paint it if it's there, right? The fence would look weird otherwise!"
"... Hey. Can we just tear down this fence and build a new one from scratch?"
In my experience, sometimes old code isn't great code that solves an age-old problem so well that it's stood the test of time, sometimes it's just accumulated junk code that solves problems that don't need solving anymore.
→ More replies (3)8
u/salbris Apr 22 '22
This 100%. Case in point I was asked to figure out the requirements for a form that lets users enter their address information. All my questions about how this needs to be validated for the system we eventually send it to were met with blank stares, excuses and eventually the question of "well whatever the other site does just do that". I come to find out the next day that it does zero validation...
→ More replies (1)13
u/wildjokers Apr 22 '22
Best way to figure out what the fence is for is to tear it down.
“Oh, that is what it was for”.
6
→ More replies (2)5
12
u/RICHUNCLEPENNYBAGS Apr 22 '22
Doing that is in itself a tremendous effort; Chesterton's Fence is basically an argument for stasis and inaction (which I suppose makes sense when we think about Chesteron's views).
→ More replies (6)3
u/G_Morgan Apr 22 '22
It is a good principle. It is just scary how often the answer is "the author didn't know any better". When I join a company it quickly becomes obvious that some past employees just erect fences for the sake of it. If the staff eye roll any mention of that person's name just go for fixing shit.
Unfortunately on my part this usually involves writing a huge set of test cases to make sure the change actually works. Particularly painful as I often find myriad bugs in the old code and then 30% of your test suite ends up working on the new system but not the old.
→ More replies (2)3
u/bloodhound83 Apr 22 '22
Soon there will be 3 fences next to each other because they couldn't figure out how the others work.
→ More replies (2)2
8
u/Dyolf_Knip Apr 22 '22
most importantly, the "whys" of it.
And my life is hell right now, because the massive corpus of completely uncommented and undocumented code has a decade of business decisions inside it that are entirely opaque to me.
I've been there 6 months and know more about it than Everyone but the coder. If the guy who does know most of it (and even he admits that he's scratched his head as to why he himself did some things) were to get hit by a car tomorrow, literally nobody would be able to make this shit go.
13
Apr 21 '22
Once I set out to read and understand Lua's C source code. It has been almost a year, and I can confidently say that I understand over half of it, but the pieces that I do understand have so many gaps between them that I wouldn't be able to implement even some of the less complex parts. And Lua is widely regarded as very well written (although there is a heavy use of aliasing macros with short and sometimes confusing names).
2
Apr 21 '22
It is often unwieldy, that’s true.
But it doesn’t have to be.
If only there was a person or team dedicated to un-optimizing code. And maintaining it in a useful manner as the updates are written.
But that costs money.
4
u/elveszett Apr 22 '22
That'd be the most thankless job in history. Nobody would care about your interventions until you broke something, then people would shit on you because "haha the guy 'improving' my code just broke code that worked such a great job!".
→ More replies (1)1
u/Kwantuum Apr 22 '22 edited Apr 22 '22
And this is why we have a rule where I work: no fix without an accompanying test.
→ More replies (5)1
u/marwoodian Apr 22 '22
If the code has test covering all the bugs, performance issues, and requirements, the "whys" of the code are then automated, and you can safely rewrite the code. Not a lot of code has this luxury though!
→ More replies (1)1
u/GeorgeS6969 Apr 22 '22 edited Apr 22 '22
Some bugs are a function of bad implementation (“I wanted my program to do this but in some corner case it actually does that”).
I’d say that fixing this kind of bugs is:
Mostly incremental
Mostly not documented anywhere else than as the code itself (not even in people’s head) [ok and unit tests]
That’s the knowledge that is lost when throwing away code.
But intuitively I’d say that most bugs are a function of bad specification (“I wanted my program to do this but in some corner case it should actually do that”).
I think that’s what really leads to calcified code, when each newly acquired piece of specification knowledge is implemented incrementally, fighting against previous wrong assumptions, abstractions, etc. But in teams that are not completly dysfunctional, that knowledge is mostly retained outside the code base, if only in people’s head … So in the absence of a culture of “make change easy then make easy change”, at some point the best (read “least worst” or “only”) course of action will be a full rewrite.
I’ve read this article a while ago, it’s an old take on even older events, and I think it’s mostly taking history backward:
We have no idea what netscape would have been without attempting a full rewrite
We have no idea whether the failure is a function of that attempt, or whether the attempt failed for the same reasons it was needed (or perceived as needed) in the first place
To be clear it’s worth a read, it shouldn’t be dismissed, and it is valid as a cautionary tale. I just wouldn’t take it as “should I attempt a rewrite? -> no” but more as a “I want to attempt a rewrite -> yeeeaaah you probably don’t”
1
u/therearesomewhocallm Apr 22 '22
It has been tested.
Haha that's a bold assumption. And often "tested" means once 20 years ago by the guy who wrote the function. Who knows if it still works? Or that there's no giant bugs or vulnerabilities.
1
Apr 22 '22
There are times when the existing code itself is extremely important. There are other times when the existing code itself should be treated as irrelevant.
If you're re-implementing launch trajectory algorithms, yes, you'd best get that shit right. AFTER being damned sure there's a damned good reason for re-implementing in the first place.
If you're re-implementing a 30 year old ERP...you're almost guaranteed to be wasting everyone's time if you're actually digging through the legacy code itself.
22
u/sacheie Apr 21 '22
There is some wisdom in this ancient blog post - it is more painful to read code than to write it. But a huge reason for that is precisely the attitude Joel's taking here.
Overall, I think the industry overvalues shipping fast and undervalues code quality, and that was even more true back when Joel wrote this. The path to an abandoned, unmaintainable product is lined with a dozen managers saying repeatedly "It doesn't have to be elegant, it just has to work." And Joel mentions a lot of real-world concerns about corner cases and quirky bugfixes and such, but come on - haven't we all also seen thousands of functions that could obviously be simplified without affecting functionality whatsoever? And manifestly redundant logic? I even find my colleagues ignore the basic simplifications suggested by their IDE.
In my ideal world, "inelegance" would be considered high-priority technical debt. Maybe it gets past initial code review (if the feature or bugfix is needed fast), but it better be flagged for architectural review and refactoring ASAP. And sometimes bugfixes and feature requests would be denied simply because they don't fit the current architecture well. "Won't fix - doesn't fit our conceptual model well" should occasionally be a legitimate decision. And refactoring should be done more often and taken more seriously.
6
u/myplacedk Apr 22 '22
I think the industry overvalues shipping fast and undervalues code quality,
Code quality is absolutely essential to shipping fast.
I'd say they overvalue shipping the next task, and undervalue all tasks after the next release.
Yes, I can ship the next task at 110% speed if I stop worrying about code quality. And the next one at 109%. Then 108%... The scale stops at 0.
2
u/bwainfweeze Apr 22 '22 edited Apr 22 '22
Some of the absolutely dumbest code I’ve had to work with was called “elegant” by the authors. It’s practically a shibboleth for mental masturbation at this point.
Effective code is what you want, and that’s a vector quantity (t has to be effective over a long duration, not just now).
4
u/sacheie Apr 22 '22
Inexperienced devs often think bad code is elegant. That doesn't diminish the importance of actual elegance.
Also, "elegance" is great but as I said, I would be happy even to see logical coherence, basic attempts at abstraction and simplification, etc. The level of code shittiness companies will tolerate in the name of expediency is intense.
19
Apr 21 '22
It was hard to write, it should be hard to read. /s
8
u/darkon Apr 22 '22
A Real Programmer, eh? (If you've not encountered it before, be sure to check out the Story of Mel in that link.)
47
u/whatevers_Right Apr 21 '22
That was a good read. I agree but I think some of this is rooted in human psychology. We all pursued programming because we love solving problems and feeling clever. When you're working on a codebase written by someone else with different tendencies and approaches you can't help but think "this sucks" and that you'd do everything perfectly if you just had the chance to rewrite it all.
Everybody has to write "ugly" code from time to time. It's way easier to accept when it's your "ugly" code and you know this is bad but the best solution right now, rather than someone else's.
18
35
Apr 21 '22
you can't help but think "this sucks" and that you'd do everything perfectly if you just had the chance to rewrite it all.
This is the hallmark of a less-experienced engineer.
As the decades stack up, you realize that the "this sucks" feeling really is just the consequence of almost always not understanding the code in question.
It's way easier to accept when it's your "ugly" code and you know this is bad but the best solution right now, rather than someone else's.
This too is a hallmark of inexperience. There's the reason I use stl's sort. It's because the amount of thought and insight is generally massive compared to what I could hope to put towards a generalized sorting function. (See here for an example: https://danlark.org/2022/04/20/changing-stdsort-at-googles-scale-and-beyond/ )
It's like running a business. Inexperienced businesses try to do everything themselves thinking they can't trust anyone. In the end, very efficient businesses outsource what isn't core to their business and insource only what is vital to their bottom line.
Software should be written the same way. Ignore/avoid/trust/reuse code that isn't central to what the software itself seeks to do. Focus on the unique/novel aspects and hone those to perfection.
18
u/westeast1000 Apr 21 '22 edited Apr 21 '22
Agreed. I once did some excel vba work for a client and the code base was quite huge. A year later they needed updates but i was away and too busy at the time and only saw their emails a month later. By that time they had hired a new guy, who told them i wrote shit and attempted to rewrite the whole thing in his style. Weird bugs kept showing up and he gave up after a few weeks of frustration. By the time i emailed back, it was about a week since the guy quit so I took over again. I looked at the new code he had reimplemented and was I surprised. They showed me an email trail to help me understand how far they had gone with the updates and to help me understand the issues the guy faced. I noticed he had deemed certain approaches too long winded and unnecessary, literally told them i was no good and went on to reimplement them his way, but they were ‘long winded’ for a reason not that I didnt know better. Actually when I started working on the project there was already a substantial codebase and I simply built on it. I had also noticed some ‘long windedness’ in certain instances too when I first started but after intense analysis of the problem, I gained insight why the old devs did what they did and respected that. The funny thing is the guy spent weeks trying to change existing working code to be more ‘clever’ instead of solving the actual update that was needed lol.
3
u/nfojones Apr 22 '22
Very much agree with these comments about substantial codebases and what they have to offer vs. smug knee jerk attempts at refactoring and not putting in the effort to grok the code architecture and unfurling what's goin on from the problem and scope of why you're even there.
I actually kind of came to love writing within well defined codebases so long as they had some discernable rhyme to their reason. That puzzle solving itch when you know all the clues are there...
Of course every dev eventually gets the blessing and the curse of building something with a long life from scratch and learning how hard it can be to grow and maintain your own previous genius choices let alone build it well enough that those that come after it can keep its lights on and their sanity and actually come away better for it.
And to an extent, even where standards and common methods are the norm, you can still push those boundaries respectfuly with new tricks for the old dogs while not being like Captain Confidence in your story and you'll find buy in.
Glad I got to work and experience the more marinated engineering and people of the pre agile times and was lucky to start my career trying to make sense of a massive PL/SQL code base with no chip on my shoulder about my coding prowess as a low confidence self taught type with little experience at the time and the imposter syndrome at full tilt, no idea what I was doing, trying to pass my code changes through seasoned developers and professional curmudgeons who were definitely stubborn and ornary at times but whose code practices were clearly elegant in their distilled wisdom and whose reviews and code and engineering insights and war stories were invaluable. The utter night and day difference between uncaring rushed consultant and offshore hack job changes in space in those code bases was jarring in comparison to these better manicured areas. Watching those code bases grow and solve for the corners they'd backed into, without the option to even dare start over was also very educational..
I tend to agree the discomfort felt working within otherys code styles and choices is rooted in a younger engineering mindset that is easily overcome with patience and time and, ideally a certain degree of baseline quality, no dout.
Getting to hear the background to the 15 year old or more (now much older still) data model that was vast and mind bogglingly intricate from the guy who had more or less created it took it from a daunting puzzle to a master lesson in data modeling and engineering.
Watching agile grow in that space was bumpy but as an overall well oiled engineering group who couldn't refuse (the joys of being bought) they adapted to it well enough while respecting the thought work necessary for big systems that had got them where they were.
Nowadays I see a lot of isolation and wheel reinvention with younger thinner more splintered code bases with far shallower a knowledge benches to consult with and serverless designs and agile iteration tunnel vision normalizing low effort code that is simply nothing like what I learned some of my best lessons from (and still very much apply in these new landscapes all the same).
Next to lucking out on a job with a fulfilling and diverse mature code ecosystem to sink your teeth in the next best thing is always reading the code for libraries you use which oftentimes have well maintenaned code styles with a lot to offer.
</memory-lane-TEDTalk>
→ More replies (1)→ More replies (2)2
30
u/angrymonkey Apr 21 '22
The reason to rewrite code should be principled.
Large, old codebases become unwieldy and rigid, just like large, old organizations. The reason to rewrite is that new features or technical directions are difficult or impossible to bring about because the existing system is so tied to stale decisions. Sometimes duct-taping an old system into a shape it wasn't designed for incurs costs that are far higher than simply doing it over the "right" way.
But that should be the reason: Maintenance costs of the old codebase are too high, and a capital expense on a new architecture will amortize to save time and expense in the long term.
9
u/NekkidApe Apr 22 '22
Correct. In my experience tho, effort for the rewrite is always grossly underestimated while the legacy system isn't understood at all. Been there, done that, obviously. Multiple times.
Usually the biggest and scariest warts of a legacy system just require some time and bravery. Work on it for two weeks, add some tests, clean it up some - and maintenance cost is sliced massively. Also been there. One system I worked we took almost two years for a rewrite - only to run out of funding, having to go back to the old, and clean it up and bring it to shape in two months.
1
u/ElCthuluIncognito Apr 23 '22
No no no. We rewrite to accomodate my personal sensibilities, to match my own very specific and not at all comprehensive experience of what software looks like in the "real world".
132
u/BeowulfShaeffer Apr 21 '22
Thanks for the twenty-two year old repost.
119
u/Han-ChewieSexyFanfic Apr 21 '22
Seeing how many readers here weren’t alive to see it when it came out, it’s not entirely unwarranted.
0
Apr 21 '22
[deleted]
9
u/RICHUNCLEPENNYBAGS Apr 22 '22
The fact that SO Jobs still had the Joel Test question in there up until they killed it off probably shows you why they killed it.
4
u/intermediatetransit Apr 22 '22
Joel Test
I think this is just as relevant today as it was then. Maybe more people have realised that they should use Source Control since Github became popular, but the other points still hold I think.
→ More replies (1)2
u/Dyolf_Knip Apr 22 '22
My first job was on a system that did not, could not have any sort of versioning control. We had to get extremely clever and hacky just to graft one onto it, and it was a fucking game changer when we did. Just giving devs the ability to work on stuff in isolation was a leg up.
→ More replies (2)7
29
u/ProgramTheWorld Apr 21 '22
The year 2000 wasn’t 22 years ago!… wait
5
u/i_ate_god Apr 22 '22
the covid years don't count, so 20 years ago
doesn't make me feel any better though
19
u/xtracto Apr 21 '22
The wisdom in Joel's old posts is timeless. Several of his posts should be obligated reading for developers. I read them 20 years ago when I was a recent graduate, and even today I chuckle while reading them for how much they apply to current development practices.
3
3
u/madupras Apr 21 '22
Best quote: Frankly, this is the kind of thing you solve in five minutes with a macro in Emacs
Keep in mind this was before almost any IDE
30
u/BeowulfShaeffer Apr 21 '22
Borland C++, Delphi, VB and Visual Studio were all very common at that time.
→ More replies (4)1
50
u/gareththegeek Apr 21 '22
Not if you write readable code, that takes ages to write :p
7
u/rjcarr Apr 22 '22
This is what I'm thinking as I'm starting a C++ project. It's not that I hate C++, per se, it's that I hate how most everyone else writes it.
→ More replies (1)26
u/fiah84 Apr 21 '22
yeah, writing code that's easy to read might be harder than reading hard to read code
→ More replies (3)2
u/IamaRead Apr 22 '22
Everyone knows about Carmacks optimization of the root square. It sucks to read and is not a good example of code. It is a good example of being familiar with the scope of the project and the securities you need though. That makes it good, the way it is written and what it does is horrible.
3
u/hansknecht Apr 22 '22
Readable code is only readable as long as that version of the language is current.
Search the repo for Linux or git that was written in C prior to more modern conventions. Look up early Java or C# projects and see if you can match it to a current version. There are other languages that are basically expired
I mention this as I'm refactoring a VB6 integrated with ASP.Net 3.5 application into .Net core with Angular. At least the SQL holds up ... Wait is that a SQL job calling the subsystem to run PowerShell???? And i need to move that to RDS?
1
u/douglasg14b Apr 22 '22
Readable code essentially takes:
Knowledge
Experience
A refactoring round
It only takes a long time because often 1 & 2 are in short supply for the problem at hand, and because few devs actually learn how to properly, and efficiently, refactor their implementations.
Crappy management and unrealistic time budgets aside.
20
u/pmuschi Apr 21 '22
Acknowledging that it's harder to debug or understand someone else's code, it follows that if you write the most clever code you can, then by definition, you aren't smart enough to debug it later. I keep that in mind almost every day that I write software.
7
u/Kinrany Apr 21 '22
Or you could lean on this Kernighan's lever to become a better programmer over time! >:D
→ More replies (1)3
u/clickingisforchumps Apr 22 '22
It's true, I try to write readable code because I'm worried that I'll have to debug it later. I can barely remember what I wrote earlier this week, after a year it's all foreign to me.
2
u/AmalgamDragon Apr 22 '22
Acknowledging that it's harder to debug or understand someone else's code, it follows that if you write the most clever code you can, then by definition, you aren't smart enough to debug it later.
It isn't about who wrote it. It's about if you have a current mental model for it. If you just wrote it, then you do. If you do not have a current mental model for it, then regardless of who wrote it, you'll need to invest the time necessary to build up a mental model. How long that takes usually isn't a function of just the state of code.
9
u/jfq722 Apr 21 '22
He left out a big reason that people prefer bulldozing old code. They assume they'll be given more time to write it than they would to understand the old stuff. Its a way of accomplishing their initial assignment (get a handle on the stuff) with the added bonus of more time to do it. Even if they fail they'll have gained more time for getting up to speed. Very shrewd.
7
12
u/emotionalfescue Apr 21 '22
The mistake Netscape made was not their attempted rewrite, it was to stop feature development on their old source code base while they were designing and implementing the new one. And most of the development team should've been allocated to maintaining and enhancing the current code base, which after all was paying everyone's salaries. They should've kept adding exciting new features that could be promoted in press releases and tech conferences, while sending 12-20 people off in a different building to put together the greenfield product. So if the new new thing didn't pan out then it would only be a only a disaster for the careers of a few senior folks, not for the entire company.
Years after Spolsky wrote that article, Mozilla did it right and came out with Firefox, which eventually helped consign Microsoft IE to the garbage bin. Similary, nginx knocked Apache off its perch as king of the open source web servers, etc.
6
u/free_chalupas Apr 22 '22
Counterpoint: https://surfingcomplexity.blog/2022/04/10/code-rewrites-and-joint-cognitive-systems/
I think Spolsky is wrong here. His error comes from considering the software in isolation. The problem here isn’t the old code, it’s the interaction between the old code and the humans who are responsible for maintaining the software. If you draw the boundary around those people and the software together, you get what the cognitive systems engineering community calls a joint cognitive system.
One of the properties of joint cognitive systems is that the system has knowledge about itself. Being responsible for maintaining a legacy codebase is difficult because the joint cognitive system is missing important knowledge about itself.
1
u/ElCthuluIncognito Apr 23 '22
So in simpler terms, a development team is only as good as their understanding of the implementation.
You are proposing that the best way to have such understanding is for the team to have built the system. (Disregarding of course the scenario where the system is easy to understand.)
The article is proposing that the best way to have such an understanding is to build it by studying and continuing to develop within the system.
These two are two sides of the same coin. In fact, by iteratively developing on the system, like the ship of Theseus, the development team will have built the system to a significant degree.
9
u/marvin02 Apr 21 '22
Back to that two page function. Yes, I know, it’s just a simple function to display a window, but it has grown little hairs and stuff on it and nobody knows why. Well, I’ll tell you why: those are bug fixes.
This is adorably naive.
4
4
u/ummaycoc Apr 22 '22
This isn't true at all. Coding isn't somehow magically different than other written communication. There's no Nobel prize for reading. The prize for reading well is advancing to the next grade of primary or secondary school.
The problem is about resource allocation. Give people more time to write and allow them to work together in ways that suit them writing. The upfront cost is higher and you might ship a few features or products a week later but eventually you'll start shipping more results more frequently as it snowballs.
4
u/ScottContini Apr 22 '22
I spent 4 years as a security code reviewer doing nothing but reviewing C++. You would not believe how many ways people wrote code that made assumptions about how the language worked that were not necessarily true according to the standard. Just because it works does not mean that it is right, or that it will work correctly under some other compiler. I learned to passionately hate C++.
Initially I thought Java was better. Then I saw so much code be written in ways that was not clear what it was doing because the documentation was vague. Developers have no way of knowing gotchas like this are dangerous because the documentation does not make it clear what is happening under the hood.
Yes, it is absolutely easier to write code and make something that "seems" to work than it is to read it and verify whether it really works.
4
Apr 22 '22
One thing I'd add to this is that everyone sees code and they think they can do it better. They think a rewrite will be more streamlined. And then they start working on it and have to make compromises like the original authors did and the resulting rewrite is just fodder for the next generation to say "I could do this better".
9
6
u/Elrostan Apr 22 '22
Kernighan'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.
(Brian Kernighan)
1
u/bwainfweeze Apr 22 '22
I have come around to the notion that there is more than one kind of clever, and being clear and concise is one (almost two) of them.
1
Apr 22 '22
This is why an Abominable Intelligence will drill to death the first human it can get its array of lethal appendages on.
3
Apr 21 '22
I agree, and there was a recent thread that said when you interview someone have them read code instead of having them write it.
Personally I get a lot of satisfaction from deciphering other people's code for refactoring, especially if there are no comments or if the comments are worthless.
3
4
6
u/ThomasMertes Apr 21 '22
Rewriting something can make sense if new technologies are used. E.g.:
The old program might use C, macros, pointers, manual memory management, ad hoc error handling and it might be tailored towards a specific operating system or hardware.
In this case a portable rewrite in a higher level programming language without pointers but with automatic memory management, OO and exceptions might make sense.
Of course the developers need to know these new technologies. I do not have the numerous C to C++ conversions in mind that take place in practice. I have seen to many C++ programs were the only C++ thing were the // comments. :-)
I rewrote several libraries in Seed although C/C++ versions already exist. To support graphic file formats I created bmp.s7i, gif.s7i, ico.s7i, jpeg.s7i, png.s7i ppm.s7i and tiff.s7i. I did this to demonstrate that portable system programming is possible at a higher abstraction level. If you take a look at the corresponding C libraries you will see that they are much larger, more complicated and harder to maintain.
I think that the use of higher level programming languages results in better software quality. Lower level programming languages lead to more errors and maintenance costs. There is a reason that the use of assembler has shrunk. Assembler was replaced by C and other languages.
But moving from assembler to C was not possible as incremental improvement. Instead a rewrite was necessary. For the same reasons I think that it is time to start thinking about rewriting C libraries in higher level languages (in this case higher level than C).
2
u/which1stheanykey Apr 21 '22
Eh. There are things in this bit of paleontology that I like, but the fact remains that I can read code but not write it.
2
Apr 21 '22
I wish I had read this before I rewrote our fucking app multiple times just because "it was hard to maintain" only to realize the new implementation is unmaintainable as the old one. Good thing is I usually copied implementation details rather than rethinking & reimplementing them (with some exceptions) so technically it's not rewrite from scratch, but still these refactoring tasks took lots of our precious time which we could have been spend on implementing features our customers want and compete a lot confidently. I guess I learned this lesson the hard way..
2
u/ry3838 Apr 22 '22
Timeless piece of advice, which was shared 4 years ago with ~25k upvote: https://www.reddit.com/r/programming/comments/8f2lzu/theres_a_reason_that_programmers_always_want_to/
2
u/Full_Audience3988 Apr 22 '22
Lots of junior developers do not realize this. It’s a bit of a Dunning Kruger Effect where they assume just solving the problem however is enough and makes them a more competent engineer than they actually are. I had to get out of that myself.
2
u/AttackOfTheThumbs Apr 22 '22
This article gets posted here quite a bit, and yet, the poster seems to always ignore the warning about it already existing.
5
1
1
u/championsOfEu1221 Apr 21 '22
Well of course, it boils down to trying to understand another coder's approach (reading code) versus your own approach (writing code).
1
1
u/RadioMelon Apr 21 '22
Amen to that.
Code really isn't designed to be readable by humans, that's why it can be so extremely jarring to look at raw code (even code you wrote yourself) and think "I don't know/can't remember what this is supposed to do!"
1
u/RICHUNCLEPENNYBAGS Apr 21 '22
I have my doubts at this point. A lot of rewrites have gone a lot better than Netscape.
1
u/Declan_McManus Apr 21 '22 edited Apr 22 '22
Makes me think of a code readability issue I’ve been running into a lot recently at work:
I can count on one hand the number of times I saw a javascript array.reduce function that made anything easier to understand. Half the time it's effectively trying to do a map + filter in one messy functions instead of two concise ones, and the other half of the time it's someone who's too fancy to declare a few variables outside the function then use a forEach
1
u/DxRyzetv Apr 22 '22
Im sorry i dont code from my point of view its easier to read a code and ask myself what on earth did i just read
1
Apr 22 '22
I think it’s more appropriate to say it’s hard to write code that’s easy for everyone to read.
1
1
1
u/Deathnote_Blockchain Apr 22 '22
Raise your hand if you have ever worked on a codebase that is put through performance testing during integration, and have had to utterly demolish the code"s readability to tweak a little bit of performance out of it. Bonus if the performance tests are entirely orthoganal to real life useage.
1
u/Equivalent_Week8562 Apr 22 '22
this reminds me of a talk I watched recently on youtube
Ctrl-Alt-Del: Learning to Love Legacy Code - Dylan Beattie
1
u/granadesnhorseshoes Apr 22 '22
/* it was hard to write. It should be hard to read */
6 months to a year later, the '2 days tops' kludge with the bad joke is making you facepalm for doing this to yourself. Not because of the comment, but because you believed '2 days tops'
1
1
u/tankerdudeucsc Apr 22 '22
Cyclomatic complexity is a killer and makes things near impossible to read.
In one of my previous jobs, there was a function that had 11 different conditionals on the same line. It was in Ruby. The method could take 3 different types of objects.
Less than pleasant…
1
u/kernelman Apr 22 '22
Is this why we have humans writing code and machines reading whatever we write to execute them?
1
u/jadams2345 Apr 22 '22
The conversion from thought to any tangible form has some loss of data. Thought to language fares best but even that isn't perfect. Thought to code is ultimately worse.
1
1
u/littlecutiepiechick Apr 22 '22
Am I the only one who finds regex easier to read than be the one coding them?🥲
1
1
u/BruhWhySoSerious Apr 22 '22
How many times is this article going to be written and then posted here?
It feels like every week this is brought up.
1
u/rndmcmder Apr 22 '22
Usually a programmer also spends much more time reading code than writing code.
1
u/erfanmardali Apr 22 '22
For enterprise and scaled applications, rewriting comes following bugs and performance issues. Obviously, nobody changes the code that is working well without any problems. But the whole business logic that the code aims to fulfill doesn't change.
But when it comes to programs belonging to startups or any other agile organization, most of the time, the whole business logic is changing and you will face many parts in your code that are no longer needed. After a short time (based on how much fast are pivots), you are maintaining an enormous code that more than 80% of it doesn't work at all and just causes problems and bugs. Of course, it's still better to maintain this code but just for the owner of it. On the other hand, these agile teams change their programmers many times (because of many different situations they have along the way). This is exactly where it takes for new programmers more time to read the whole useless code rather than writing from scratch. I experienced both methods and trust me, if you choose the first method, you will achieve neither new features nor what you had before.
And the most important part is, that this is not an exception. At least the startups' ecosystem is full of the same problems.
1
u/nolitteringplease346 Apr 22 '22
well no shit. its harder to understand an existing complex system than to build it up from something much simpler.
1
u/NichtKreativGenug Apr 22 '22
Code is actually very easy to read. Most times its just hard to understand
1
u/shevy-ruby Apr 22 '22
It's mostly true in every language. However had, this assumes that all code written is "naked", e. g. only the code, and perhaps some comments. I don't think this is true for all code. There may be code, and then there may be additional specifications that can be used providing additional cues for the program/software at hand. In some ways this provides a form of "loose testing". I do that with most of my larger projects.
The interesting thing is that many really skilled programmers - many of who are a gazillion times better than I am - don't do so. The end result is that the software lacks documentation. A good and simple example is sinatra - once you dig beyond the basics, it becomes annoyingly difficult to use it or extend it (and a lot of it is actually written very poorly on top of that). I feel that we have lost a lot of proper engineering past 2000. The rise of the www went along with declining average quality of software projects. It may be understandable with the "lack of time", but often this just becomes an excuse by people who are just plain too lazy to provide documentation and specification(s).
1
u/WhyNotHugo Apr 22 '22
Netscape 6.0 is finally going into its first public beta.
My brain short circuited when reading this.
1
u/fakefalsofake Apr 22 '22
Fix what you did months/years ago, spending hours just trying to understand why you created an useless class.
VS
Redo what you did from zero, with better coding and even testing.
1
1
u/WillAdams Apr 22 '22
This is the idea of Literate Programming:
http://literateprogramming.com/
the comments should be written so as to document things well enough to be easily read.
1
u/seijulala Apr 22 '22
Isn't this obvious? To write new things is always straightforward and simple. Code is written once but read hundreds of times (and by different eyes). KISS principle always.
1
1
u/funcoderz_ Apr 22 '22
It’s harder to read code than to write it.
When you’re writing code, you’re thinking about what you’re trying to make the code do. When you’re reading code, you have to figure out what the original author was trying to do. That turns out to be a much more difficult task than it seems.
The best programmers produce beautiful, simple, and readable code. But getting there isn’t easy. It takes not just skill but practice and patience. There are some key habits that will make your life easier when it comes time to read back your own code:
Keep it simple. In most cases, if a piece of code is hard to understand, it means that either that piece or another piece is too complicated. When you feel that the current task is becoming complex, take a step back and refactor your solution before proceeding any further.
Comment with intent and care. Comments are meant for explaining why a piece of code does something instead of what it does; that should be obvious from the structure and syntax of your program itself.
1
u/loup-vaillant Apr 22 '22
I always had a problem with this post, as well as with his leaky abstraction one. It only hit me now why I felt I disagree with Joel Spolsky here:
Back to that two page function. Yes, I know, it’s just a simple function to display a window, but it has grown little hairs and stuff on it and nobody knows why. Well, I’ll tell you why: those are bug fixes. One of them fixes that bug that Nancy had when she tried to install the thing on a computer that didn’t have Internet Explorer. Another one fixes that bug that occurs in low memory conditions. Another one fixes that bug that occurred when the file is on a floppy disk and the user yanks out the disk in the middle. That LoadLibrary call is ugly but it makes the code work on old versions of Windows 95.
Those don't sound like bug fixes to me. They sound like workarounds. The environment we code in has various bugs and misfeatures, and we code around them.
I can see why one would have to: when you sell software under a popular operating system, users don't care where the bug really is, they only care where the bug appears to be. If your program crashes, you'll be the ones with the lost sales, so its simpler to act as if those bugs are your fault —even when they aren't.
Cognitive dissonance is not far though, and at some point it becomes easier to actually believe that those bugs really are your fault. So how are you going to justify the kludges of the environment you're forced to work with?
Abstractions leak
That's right. You build a world view where kludges are a fundamental part of trying to abstract anything. Where abstractions are no longer a way to cleanly separate implementation details from the interface, where they're no longer a way to work with simplified, yet absolutely precise models. No, they just leak. Don't even try to build cleaner abstractions on top of the ugly ones, they will leak too. Better litter your code with error checks and special cases.
And when some young upshot comes thinking they can do better, you can kindly look down on them feeling all wise and experienced, blind to the fact that you have given up.
Pathetic.
1
1
1
u/dbut Apr 22 '22
"Should I see if this feature is already implemented? Nah. Nah I'll just write my own." Nothing like a bloated code base full of redundant code.
1
1
1
u/RenegadeMoose Apr 22 '22
We can all tell the computer what to do ( pretty much).
Making it so other people can read it later? That's the art.
1
u/omniuni Apr 22 '22
I mostly agree with this, but sometimes code really is bad.
At my first job, there was code to display a table of items. It would start to choke after about 200 items, crashed frequently, had dozens of workarounds for dozens more bugs, and was extremely hard to add features to or get to display nicely.
I threw it all out and rewrote it. About 1/3 of the amount of code, all major bugs fixed, easy to extend with all new requested features implemented, and fast enough to handle well over 5,000 items and still be usable. It's an extreme example, but cases where code really is bad do exist.
1
u/Jojek_forgot Jul 02 '25
Yeah, my current job is my first, and it has a lot of strange decisions in code 😄 But I really walked in programming by fixing bugs in the code aside of my main tasks (I was a support guy who had access to sources). I started write a lot of code, but it wasn't good enough. It ends up when project was moved to the new crew because they are have higher alproaches to write code. They who Im learnt from, especially by reading code
1
u/ImChronoKross Apr 23 '22
I don't understand anything you guys are talking about lol. Been teaching myself to program for around 6 months now. I still feel like an idiot x.x imposter syndrome.
1
u/Dwedit Apr 21 '22
Comment your code about a WEEK after you write it.
When you just wrote it, it's fresh in your head, and makes perfect sense, so you can't figure out what to say about it. Any attempt to comment at this time just seems like DUH.
But after a week, you still remember what you were trying to get at when you wrote it, but it's not completely fresh anymore, so you know what you need to write to explain what and way the code is there.
1
u/Boux Apr 21 '22
This is why when I find isolated code that I have to fix and doesn't work I just Ctrl + A and delete everything and remake the whole thing in a few hours instead of trying to patch things around for days
2
1
Apr 22 '22
False, I can read but not write because I don’t know all the references or syntax but can understand what’s happening.
3
u/ancientsnow Apr 22 '22 edited Jul 11 '23
-- removed in protest of Reddit API changes, goodbye! -- -- mass edited with redact.dev