"Clean" Code, Horrible Performance (2023)
computerenhance.com
computerenhance.com
On a long enough career path, eventually you will run into one Clean Code zealot who carries an air of superiority and nit picks every PR over things like a function having more than an arbitrary number of lines in it instead of reviewing the actual code. This is the point where most people come to hate Clean Code.
Clean Code is unhelpful to beginners too, though: misuse of industry-standard terms, shunning of comments in favor of tiny functions with long names, shunning function arguments in favor of mutating state, polymorphism obsession, etc. So much of the concrete advice the book gives is just plain bad.
The reason people get more pissed off at Clean Code than they would at any other book that gives bad advice is the preachy and authoritative tone it uses. It frames people who don't do "Clean Code" as unprofessional and lazy, and this framing is very convincing to some people, as evidenced by some of the replies in this thread.
> it's impossible to use the word dynamic in a pejorative sense. Try thinking of some combination that will possibly give it a pejorative meaning. It's impossible. Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities.
There is still good meat-on-the-bone in the book, and especially interesting if you’re working in a legacy system from that older time and place.
Without fail, if a developer is "pissed off", it is because they are judging something from the past by ignoring the conditions of the past.
I really think it was just one persons opinion that got published. I started in the 80's and at each software company I worked at they had standard styles that I think we're very clean and organized without being overly dogmatic in any one direction.
What alternative is there? Obviously very few of the ideas in the book were conceived of by Uncle Bob himself, but his editorial opinion is what chose which ideas to include. If that weren't the case, his name wouldn't be on the book.
Well, isn't that the whole reason for the profession? If you want to be professional and hardworking, why are you instructing a computer to do your work for you? If you aren't being unprofessional and lazy, you're in the wrong business.
Even Robert Martin, very often in his videos and blogs, espouses "engineering judgment" and is quite fine abandoning advice in his book when the situation calls for it.
If performance is important and clean code is impacting it, he won't object to your breaking the rules.
It's mostly with his TDD evangelism that he goes (a little) crazy.
I really like that he brings attention to the idea that code can be beautiful. But judging by his examples, he just seems to have no idea how to actually write beautiful software himself.
I wish he went off and learned some functional programming. Haskell, Erlang, Clojure, F#. Something like that. Really go deep. If you want to know what really beautiful software looks like, that’s the place. Those communities know beauty.
From what I have seen, his ideas were formed in a vacuum divorced from real coding. You can see it in the small amounts of open source he has released. The kind of guy who will always prefer 50 classes to 5. Who clutches his pearls at an if statement.
I remember he was invited to give a talk at Bloomberg and the majority of us were simply disgusted that an obvious hack like him was lecturing a group of software engineers who had really been there and done that.
On the other side, I still consider McConnell's Code Complete to be a gem.
A good teacher needs a deep understanding of their topic, often deeper that that required to be a do-er only.
Fyi.
Maybe we'll see an updated version some day, with better examples. It would be valuable if only so people would stop trying to defend his old, bad advice.
You see this clearly if you ever teach. I would give all my students the same spec. Some students submitted small, simple programs which passed all the tests with flying colours. Some students would submit huge programs which barely worked.
As Alan Kay said once, the right point of view (on a problem) is worth 50 IQ points. At the margins there's subjectivity and tradeoffs. But lots of programs are more or - more often - much less beautiful.
The bureaucrats who above all value process over outcome.
Those 2 years were to do the data migration and of course there were different priorities, if that would be priority we would do it in 1 month, but we liked to spread risk over time.
Reason was of course performance issues and not really needed joins, where normalization didn't bring any benefit.
If you ever find a job in an ideal world, hold on for dear life and please accept my CV for consideration.
Pragmatic approach: generally end up with an average of around 2.72 normalization across all tables.
Functions always being under 10 lines just means you've got functions everywhere, which can be mentally exhausting to follow logic, if you aim for like 40 lines tops you can write better "stories" with your code that are easier to follow and more expressive.
I also have to think about whether there are any other areas of the code that might be calling your helpers, and whether they might break if I change the helper. Seeing everything inlined makes it absolutely clear from local reading that modifying the code only affects the local functionality.
I'm not saying go insane and copy/paste the same thing multiple times, just that 1k-line functions are sometimes the least of all evils. I liked what John Carmack had to say on this topic: http://number-none.com/blow/john_carmack_on_inlined_code.htm...
Another point from that post that I try to take to heart: if it can be a pure function, it should be a pure function (even in C). Bob Martin's style is the opposite.
I've definitely drifted towards longer code, if nothing in that function is used elsewhere. Some tasks really are just lists of things to do (especially in something like image processing), and I think that sometimes it doesn't make sense to put lists of lists in your list of things to do.
On top of that, the default place for a console in VS Code is at the bottom, now I'm down to 25-30 lines if I have that open.
And then there's heavier IDEs like IntelliJ, Visual studio, etc.
They might have two or three tab lines at the top, a row used for class navigation (that I've just realized I've never, ever used), an extra row or two of quick action bars, a row of extra tabs at the bottom for navigating between consoles/call stacks/locals/error lists, 2 info bar rows at the bottom, and sometimes two or even three scroll bars stacked on top of each other.
All of a sudden you're down from 30 lines visible to 17, which is my actual visible lines of code when I have debugging running.
Instead of // do the thing followed by 5 lines of code to do the thing. You're supposed to put those five lines in a function named DoTheThing(). That doesn't seem better to me.
I'm a bad programmer though and nothing I do is particularly important enough to optimize.
I have seen very clean codebases with a handful very long functions, but they were no issue she nice they only did one thing.
I personally write quite short functions but I have never understood why people take issue with large functions. Those are one of the easiest things to fix in a bad codebase. It is much harder to clean up after someone who used too small functions.
wing-_-nuts says (emphasis added) “My personal benchmark for 'MAYBE this function is too long' is when it doesn't fit on the page.”.
I think that’s a fine heuristic. Long functions can be fine, but longer functions tend to be less testable, so you should try to avoid them.
On the other hand, it can take lots of thinking to properly decompose functionality, and that decomposition can easily change when requirements change, so spending that time may not be worth it.
depends on what the function does, most likely the best decomposition into functions isn't simply splitting the function in to n sequential parts
> I have seen very clean codebases with a handful very long functions, but they were no issue she nice they only did one thing.
one thing usually consists of multiple other things
imho length should correlate negatively with cyclomatic complexity - it's ok if you write 300 locs if all you do is fill a map with trivial entries
I can remember as a novice that I would write an entire program in a single, many-thousand line function, unable to see where the boundaries between functions should be. With experience and expertise in the domain, it becomes easier to see where those should be.
Except the only real rule is that rules are wrong.
All there are is different and actually contradictory pressures for different and actually contradictory priorities that are all true and valid at the same time even though many contrdict. The correct thing in each given moment is whatever makes the shortest rubber band lines between all priorities.
Sometimes that will be a very large single function even if some other times that will be a bunch of 10 liners.
I worked with a guy who would constantly drop niche jargon and quotes from famous engineers and then kind of smugly look at you. He could not write a function without proudly saying what principals it was following. He was a horrible programmer, ended up getting laid off.
Every time you over scope a function signature, because you want to handle that other case, you add mental tax to the next person. This accumulates, burns time, and now confuses agents, which is time and tokens ($).
No one wants to work with a dogmatic individual but I’d rather a nit picker than a human or agent slop machine.
Clean Code "says" keep it short and simple but following the advice that Bob lays out does not produce short and simple code
If you don't use those rules, you'll argue about something else in the code reviews. Likely something even more ambigous that wasn't explicitly written down for everyone as a baseline.
There is nothing wrong with having procedural code with a switch case, as there is nothing wrong in having global variables, in having even goto, depends on how you use it.
I think most people aren't aware of the alternative, which is: A function that can call different implementations based on some other variable.
E.g. instead of having RealDB and MockDB type have a createUser() (method), you have a createUser() (function) that switches part of it's logic based on what DB is selected.
That's the prodecural way of achieving the same thing without needing a concept for virtual functions.
Casey explains this in the long discussion with Uncle Bob.
Unless you're doing something really stupid, nothing other than the DB access is going to be worth optimizing. If those two options are accessing the DB in exactly the same way, then they will probably be within 1% of each other in performance.
That's by far the easiest place to apply the "write something simple and readable and then measure and see if you need to change it" approach, so it just plainly doesn't work as argument against that approach.
def createUesr(db):
if db is type1:
behaviour1
if db is type2:
behaviour2An aspect of this that I wish Muratori had touched on when he wrote this in 2023 is how each of these tenants he has issues with in Clean Code are just trading complexity. All four of the structural rules that Muratori demonstrated issues with generally don't reduce complexity. At best, each trades one type of complexity for another.
There are some great ideas in Clean Code, but outside of DRY, the structural recommendations tend to be more harmful than good.
A tried and true way solve problems is by adding more layers of indirection, starting with an interface makes it trivial to swap things out. I just did a rewrite of some old sound tool that was hard coded to OSS and Alsa. Now i wanted Pulse and Pipewire, this ended up requiring basically a rewrite because there was a lack of a good interface and assumptions everywhere. Instead now I have some good interfaces and adding whatever the next Linux audio stack comes in - it likely won't be a problem.
Like a door, your software should have hinges (interfaces) in the places it needs to be able to change. And it shouldn’t have hinges in places where it won’t change. Rigidity allows for simpler code and better performance. Flexibility allows for changing requirements and modularity.
The mark of an experienced software engineer is having the judgement to know ahead of time where your code should be flexible and where it should be rigid. A good rule of thumb is to only add an interface when you have 2 or more implementations you want to code up. Until then, just call methods directly. If you don’t have 2 different case studies, you’re going to design the API badly because you don’t know the real requirements.
For your point, what part of the design shows claims that shapes are to be added/removed by outsiders? You should design for what you know and can reasonably predict. Nothing in the article seems to claim that this problem is situated on outsiders adding their own shapes?
Let's ground the example. Suppose I was writing some 2D collision checking library where these operations we're useful. Now I did Triangles, Rectangles and Circles. If I predict that arbitrary shapes should be added, how should I go about it?
The vtable way could work, but as the author showed, you're likely going to get hit with a fairly significant performance impact. Now if you can reason about your use case and see that its not in a hot loop, then the vtable way should be good to go. But if it was called a lot, then you want that to be performant and find a different method.
Some thinking can lead you to the fact that you don't need a new class at all, you just need a general Polygon object, and use the switch method. Or going by the article, you can precompute the information you need that is constant, area, # of points and add those to a dynamically allocated array (or large enough statically allocated one), and have the best of both worlds.
My point is, you can't really say which one is better until you actually know what your use case and the constraints on your system/users. We need to know how the code is used. People complain about this being a simple example, but its an example that was in the "Clean Code" book. What's important is to realize that the Clean Code version might not be worse in terms of hard to measure things, like maintainability or eligibility, but it is empirically worse for performance, and that trade off matters for many use cases.
I had to track down a copy of the book because I didn't have one on hand (thanks internet!) but that example is from chapter 6. The first listing is actually close to Muratori's code (except using classes instead of a tagged struct for dispatch but still using a procedural approach rather than dispatching off of methods), the second listing is the OO one that Muratori starts with. The point being illustrated is summed up in the book in these two quotes:
> Procedural code (code using data structures) makes it easy to add new functions without changing the existing data structures. OO code, on the other hand, makes it easy to add new classes without changing existing functions.
> Procedural code makes it hard to add new data structures because all the functions must change. OO code makes it hard to add new functions because all the classes must change.
And amusingly, given that this whole thing is meant as a criticism of Martin and Clean Code he has this right after those two statements:
> Mature programmers know that the idea that everything is an object is a myth. Sometimes you really do want simple data structures with procedures operating on them.
So at least in the book, he has right here, after the "bad" code Muratori is criticizing, addressed the fact that you need to choose your representation based on your circumstances.
He also could have showed the if-statement version, and it wouldn't have some of the performance impacts, but there's a big chunk of the article that's independent of that. There would still be performance benefits, since the article isn't purely switch statements vs vtables. It went through a series of clean-code tenets that were shown to cause performance problems. That's the authors point, performance deteriorates when following those principles. Even in real world examples this will happen, are you claiming otherwise?
I feel like everyone is just talking over the article, unless you disagree with the actual thesis, that the clean code tenets listed cause bad performance, then you don't really disagree with the author here right? You can argue in spite of the performance decrease, the clean code method is better for real systems, which is fine and I have no issues with that, but that's a separate claim you should prove, and state clearly to who ever is working on the code you're writing.
> but it was not meant as an example of high-performance code
That's part of the point, the clean-code version can't be high-performance. The tenets of it contradict how the hardware works, and causes slows down (not necessarily all the time, but it does typically.)
You just explained why the piece comes across (when taken as a criticism of Clean Code) as a strawman. Muratori explicitly ignored the example in the book with the better performance and Martin's statement that the second way (using method dispatch) wasn't always the right way.
That is exactly what a strawman argument does. It ignores parts of the original statement to argue against something not claimed. Muratori exaggerates the idea that Clean Code says you must use the second (slower) approach even though the book itself says that you should use your judgement and pick the correct style based on what you need to do. While not explicitly addressed in the book, this means that if you need performance, then the book is not objecting to the first (or Muratori's) style.
If the author was purposely mischaracterizing what clean code was advocating for, arguing against the weakest version of what Martin was saying was clean code, I can see that being an issue. But he took a section of the code that Martin claimed was clean code, and arguing against the provided example being good code despite it fitting Martin's idea of clean.
The book says to pick the best version, and maybe it was improper for the author to omit the other version, but even the other version has issues that the article addresses. You can use the more performant switch case version and see how omitting other principles of clean code cause gains from even that version.
Again, the claim in the article was not purely vTables vs Switch statements, there several other claims that have nothing to do with that, for example the reliance on not using internal details of a class, or DRY which appear in both the OO and procedural versions of Martin's code IIRC.
The book actually makes a stronger claim than the author's IMO. The books claim is that there are principles that make clean code, and a person should follow in order to make their code clean. The implication being that not following these rules makes your code unclean (but Martin doesn't explicitly say this iirc, so this may be too strong of a statement). Martin doesn't really provide useful metrics to back up this claim either, so its hard to tell what parts of it to take as sage advice, and what really doesn't work. The author of the article at least provides empirical data to back up the thesis, which is that this "Clean Code" has terrible performance. It doesn't matter if Martin doesn't argue that it is performant, the fact (as proven by the data shown) that the code has worse performance than other methods is enough to prove the author's claim, and is not a strawman.
The article is titled "'Clean' Code, Horrible Performance", that's the argument being made. Why is it a stupid conversation? If you think the trade-offs are necessary, then fine, argue that. But that doesn't change the objective measures that the author did to demonstrate the thesis of article.
Why have you drawn the conclusion that the author is against this? A function with a switch-statement can do this.
the better approach would be to use implicit control flow using class hierarchies, interfaces, and such and rely on class behavior, polymorphism and runtime dispatch, instead of explicit switch() which tends to multiply itself across the codebase
When working on large applications, by far the single most important factor in performance is having simple and understandable code.
Understandable but slow code can be fixed. Incomprehensible code can't, so it either stays slow or gets worked around with caching/async processing/etc.
If you want fast software, you should write the simplest thing that isn't obviously stupidly slow, then measure and see what parts you need to change. Occasionally you need to make pieces less readable to make them faster, but it's going to be 5% of the application, not the whole thing.
Truly fast software is made by thinking about data flow from the start. If you use the right data structures, the code takes care of itself.
But this is far beyond Clean Code. The examples in that book are neither readable nor performant. He uses bad data structures and hidden mutation everywhere. In the large, that approach leads to a buggy, fragile mess.
I disagree with much of the advice in Clean Code, but it has nothing to do with performance. Clean Code is bad because it produces overly-complex unreadable code. The reason that it produces poor performance isn't because the code is too readable; to the contrary, if the code was more readable it would be more obvious that it's using the wrong data structure.
I'm not saying that you shouldn't think about performance from the beginning. I'm saying that you shouldn't sacrifice simplicity and readability for the sake of performance until you are sure it's necessary because those things are rarely in opposition to each other on the macro scale.
Nothing is worse for performance than doing work you don't need to do and unreadable code tends to do a lot of that if it has been actively maintained for more than a year or two.
I’ve done a lot of work optimising text CRDTs. There, the simple data structure is (essentially) a list which contains metadata for each character. But you’re constantly scanning and inserting into the list. You can improve it in two ways: first, make each list item store the metadata for a connected span of characters. Second, use a b-tree for fast insertion. Make the b-tree store aggregate metadata in internal nodes. That gets you orders of magnitude better performance - O(n) per keystroke to O(log n). RLE gets ~10x lower ram utilisation. It’s only the obvious data structure when you’ve thought about the problem a lot. And you have to write your own btree - there are no libraries for this. At least, none I have found.
> I'm saying that you shouldn't sacrifice simplicity and readability for the sake of performance until you are sure it's necessary
It really depends on the domain. If you’re making a note taking app, you probably get good enough performance by doing the obvious thing. If you’re making a browser, database, llm inference engine or 3d game engine, it pays to think about perf from the start. But my impression is that most people on this site aren’t doing that sort of thing.
The vast majority of applications are better off using one of the many high-performance, battle-tested implementations of b-trees that already exist, which, for users of those implementations, is one of the simplest and most commonly used data structures; we just call them databases and filesystems instead of b-trees.
Every rule has exceptions but you should know the rules before you decide to break them. For anyone other than an experienced expert, writing your own b-tree implementation in a production system is an extremely foolish decision (if it's for fun or learning, do whatever you want).
I think I broadly agree with your overall point. I’ve just spent a lot of my career working on niche problems like this. And there are a lot of people working on systems software. Windows, Linux, macOS, chrome, postgres, etc don’t write themselves. But unless you move in those circles, you can spend your whole life never interacting with any of those engineers.
> we just call them databases and filesystems instead of b-trees.
The b-trees I’m talking about are in memory. Btrees often outperform other kinds of in memory tree structures (avl, rb, binary, etc) because you get fewer dram memory stalls.
Clean code like approaches have a very real cost for users (even in languages with good optimizers) and is usually unfixable after the fact.
No. You may be sacrificing end user experience, but it's not guaranteed. You have to examine the system under development to determine which style is appropriate.
If you actually have to process huge numbers of these objects, then yes. But if you don't, if whatever the actual real-world object is trickles in at 10 per second, do you need to worry about performance and cache misses here? You're already going to suffer from cache misses because the processing rate is so low.
So you get to make an engineering choice based on circumstances. If you need high-throughput, use a design that satisfies that requirement but maybe forfeits flexibility and maintainability. If you don't, then you can lean towards a design that forgoes a bit of performance in favor of flexibility and maintainability.
Use your judgement, don't follow any rule blindly whether it comes from Muratori or Martin.
Polymorphism won't get rid of the 23 if statements, it will just replace them with 23 method implementations. Then when you try to serialize that "conceptual entity" to a file or network socket you'll yearn for the if statements once more.
The main benefit of polymorphism is that it allows you to modify one part of a program without recompiling the other parts. In the absence of pre-compiled modules, polymorphism is isomorphic to branching/switch statements:
those apps tend to be vastly more architecturally complex in almost every way compared to your average corporate or web app too.
Consider how the workload is now dominated by the core task of actually calculating the area, reducing the impact of struct usage.
Consider the diffs required to make this change.
It's not like Clean Code should be taken as gospel but this micro-benchmark is not a realistic example of what CC is trying to solve.
Occam's razor applies to all domains. Don't use confusing implementations until there are no good options left.
But most code is still nowhere near the Pareto frontier. Lots of code can be improved on one or multiple axes without sacrificing anything. For example, making functions pure when you can often results in easier to read code, better readability and better performance (with other changes). This is my main gripe with “clean code”. His examples are full of hidden side effects and latent performance problems. He over relies on classes, inner mutation, virtual functions and tiny functions spread out everywhere. It’s a pity, but he doesn’t seem to know how to actually practice what he preaches.
HN post for original article on 2023-02-28 (https://news.ycombinator.com/item?id=34966137), 739 points, 914 comments
Discussion between Casey (author of this article) and Uncle Bob (author of _Clean Code_, whose programming patterns Casey is critiquing), posted on HN on 2023-03-11 (https://news.ycombinator.com/item?id=35105528), 223 points, 213 comments
"Horrible Code, Clean Performance", a "homage" to Casey's original article, posted on HN on 2023-04-19 (https://news.ycombinator.com/item?id=35596069), 121 points, 114 comments
But the argument is you're trading some of that performance optimization for maintainability. None of this is exactly news. And while I'm here ranting: I never understood why shapes are the canonical OOP example. Shapes are a closed set of types (yes I'm sure GPT-324 invented a new one) with an open set of operations. There's always going to be one more thing you need to do with those shapes, but you'll never be adding new shapes down the road unless you are still in Kindergarten. OOP is useful for the exact opposite case, where there is a relatively fixed set of operations and you routinely introduce a new subtype that needs to perform all or most of those operations.
I've noticed that most courses that introduce the concept of OOP do so in a way that (perhaps unintentionally) emphasizes the false notion that everything should have an 'x-is-a-y' taxonomy before actually asking the question if that is appropriate. Putting the Cart extends Vehicle before the Horse extends Animal.
To sharpen your statement, the cost is missing the CPU caches, which is often caused by failing to pool allocations and reading indirectly.
> But the argument is you're trading some of that performance optimization for maintainability.
Right, but exactly how much? I would argue "very OOP" design styles neuter your ability to optimize the system, and sometimes necessitate that you are kept at arms-length from the system, only capable of "customizing" it via more abstract API layers. I do believe certain OOP practices can make maintaining software easier, but I also believe we have not figured out how to retain control over the computer in the face of these abstractions.
As an example, Clean Coders advocate for "separation of responsibilities" and often speak in terms like "ownership" or what a function/class "knows about" or "should have to know about." When different classes are given different data-fields in the pursuit of making it clearer (what should exist in that scope,) you are creating a constraint which is virally spread through the codebase which runs counter to what the CPU wants. The CPU wants an array, but you can't have an array because the FileManagerFile can't "know about" the FileManagerFileCache, and the FileManagerFileCache can't known about the FileCache, so now each FileManager "owns" its own cache, which is an entirely separate heap allocation.
That said, double dispatch as in the visitor pattern is often too hard to analyse for optimisation and I think humans frequently get a bit lost with it as well. Fortunately pattern matching is doing away with it. I think it's one of these gang of four patterns that has a lot of people scratching their heads and wondering if the open/closed principal is that worth sticking to if this is the outcome.
Is the most non-sensical thing I've seen. So of course the junior dev parade thinks it's the gospel.
Had a terrible manger who would swear by this book but couldn't code his way out of a paper bag.
This is often a trap for performance. Sure, it looks nice on a screen but calling a function to return a variable is usually epic waste of performance unless compiler will save you by inlining the function into your code or architecture you are using has a magic instruction for that (call vs fcall - which compiler has to recognize and use) which is just fancy "goto there, mov r1 <- *var, goto back"
What is a problem is large functions. I have seen functions that were over 60,000 lines long (and few comments or other excess space takers). I will take a 5 lines max rule for functions (this is nearly straw man levels of short!) over that. Functions that are 50 lines long start to get annoying to read but are not a problem. Even 100 lines functions I can handle. However the extreme of long functions is much worse than the extreme of short.
That can't possibly be from a serious person.
The C was almost always written by EEs who learned that function calls were expensive and so they minimized their use of them (this was their stated rationale, not me guessing). What amused me was that every time I tackled one of those things I'd reduce the line count by 70-90%, and usually at least double performance, by using a bunch of small functions to encapsulate the repeated logic. Compilers inline well, and have for quite some time.
That, spoken by Rutger Hauer.
Worse, it was a giant switch, and the target system didn't have enough memory for all the code so there were different builds and the user would select which to load.
There was code like
case foo:
doSomething();
#ifdef build_two
doSomethingElse();
break;
case bar:
SomeThing();
#endif
MoreThings();
break;
Try to follow that mess.Fun thing: he was like that all the time - it felt like his language cortex was just wired differently.
That's precisely what a compiler should do. Your code should be easy to read and understand. Let the compiler inline calls and unroll loops (until the I1/L2/L3 cache starts becoming a problem, that is)
programming in general is waaaaaay bigger than what the book covers.
It's way bigger than any book covers. Clean Code has some useful things, but if anyone actually reads chapter 1 they'd see that Martin even addresses the idea that you should not just read Clean Code and use it alone, or even entirely. It's a collection of one person's judgements (some good, some bad), just like all the other books like it.
Would I see the same kinds of performance gains or losses avoiding or using certain patterns in Go or Rust or Java? Are they the same examples as in C++?
What about dynamic languages like ruby or python or javascript?
If you are writing code for embedded devices where every cpu cycle counts, I would indeed trade a bit of the maintenance for some cpu cycle.
If I am writing a huge web app that has to be maintained years by a large team of devs, I would prefer a more simple/maintanable code over a fast one (+ in such scenarios the real bottlenecks are often your I/O, not the raw CPU perf).
This is for the same reason you usually write code that needs to be fast in low-level programming lng like C and huge web app in Node.js or Java.
Back then computers were far less performant than they are today, so the first languages (e.g. SmallTalk) had to be compiled into a bytecode VM that ran on a Xerox PARC. Other efforts included hardcoding some of the constructs into the ISA.
Also, In real-time simulations (ie games) often then way you write code can be the bottleneck. In web services the bottlenecks are more often network calls, database model, etc.
What did Bob ever ship that gives him any gravitas or authority in this area?
What a muddled bunch of gibberish.
Whenever I run a thing and it's unbearabily super duper slow, when you look at the process lists the thing will have spawned bunch of chromium instances - on top of probably making bunch of internet connections. Delegating some of the work that can easily done on my PC to "cloud" instead.
What we have now is way worse - it's electron and webshit technologies on desktop. Like you couldn't make software of worse quality even if you tried. The performance way worse than PCs of 1990s. It's almost like using software that's running from a floppy disk.
And now this trash is probably getting generated with LLMs.
This sounds like tackling the problems of C++ in the early 2000s.
1. Casey Muratori also that DRY shouldn't doesn't have to result in non-performant code.
2. Smaller functions, functions that do one-thing: Modern compiler can inline those. There are some edge cases where inlining may make less efficient use of states and loops but I don't think that's a main problem nowadays. I also wouldn't say the extreme version of this idea (very small functions) is still popular. The strongest proponent of this was Uncle Bob, and the last time I've heard him speak about code, he said he now lets the LLM write everything and he only reviews the module hierarchy and maybe the modules' public interfaces.
3. Polymorphism instead of ifs and switches was a big fad in the late 1990s until the late 2000s and had some holdouts in the 2010s. It was only ever popular in the Enterprise Java and C++ world (and maybe in Enterprise Smalltalk, never hard). Overuse of runtime polymorphism widely considered bad form in newer static languages like Go and Rust and in most dynamic languages there was always a tacit understanding of "use mostly conditions, add polymorphism if you need extensibility".
In functional languages (or languages heavily influenced by functional programming like Rust, Swift and Kotlin[1]), the classic approach for the type of scenario in this example is to use a sum type, and run a safe exhaustive match/switch on all the variants.
4. Hiding internals: The sum type example is telling of modern best-practices. Sum type fields are generally made public. Some languages (e.g. Rust and most pure functional languages) do not support private fields in sum types at all! Other languages (e.g. Kotlin) but immutable, so it's easy to maintain invariants without hiding information. Sometimes we do want to hide the type details and wrap it with public-facing type (this is a common pattern with internal error enums in Rust for example). Even in this case, there is no impact since we do not use runtime polymorphism or indirection (that would be Box<T> in Rust).
Due to compiler optimizations, hiding internals has marginal performance cost (if any) unless you require runtime polymorphism to achieve it. But why should you?
I feel like the performance costs lamented in this article mostly have to do with runtime polymorphism in static languages. And I fully agree here: runtime polymorphism is something that should be avoided when you don't need it[2]. But that's the thing: if you're looking at modern static language codebases, runtime polymorphism is not as hyped as it used to be in the past. Some languages still require heavy use of runtime polymorphism (Go is a good example of this), but other languages more often rely on static polymorphism (Rust) or compile time duck-typing (Zig and you could argue C++ template meta-programming used to do that, albeit quite awkwardly).
Even with all the issues you get with polymorphism, I don't think it's the main cause of slow application performance. It be very much the culprit in tight loops inside games, but if you look at the performance issues plaguing everyday apps, I think the two major culprits are endless layers of abstraction (the most quintessential example is basically every sluggish Electron app out there) and blocking the user on slow actions (like network loads).
---
[1] Even Java had sealed record types for a while now, and I'm sure will see Enterprise frameworks encouraging them in 20 years, when the rest of the world has moved on to spacefaring super-intelligent LLMs. But Enterprise frameworks also don't encourage you to write DRY code or keep your functions short.
[2] But do keep in mind that in Java it could be almost zero-cost in many cases. The JIT will monomorphize or bimorphize your classes if you always use the same class at the same callsite. The pointer indirection is not an extra cost, since every non-primitive that doesn't undergo Scalar Replacement[3] lives on the heap, and has a pointer.
[3] https://shipilev.net/jvm/anatomy-quarks/18-scalar-replacemen...
https://www.youtube.com/watch?v=zHiWqnTWsn4
1:00:00 - Open/closed principle and 1:13:52 - Liskov substitution principle.
Both are given in terms of Shape, but it's to paint the picture that things are more complicated than you thought, even with something that should have been as simple as shapes. (As opposed to "shapes are easy, just model the world like that and it will be easy too")
If you care about performance, you don't use OOP, you don't use if/else, you don't use switch{case}, what you do is you write the hot parts in assembler.
If you aren't writing it in assembler, you're writing slow code.
But that code is still not optimised until you've implemented it in an ASIC.
Depends in part in how good you are at writing assembler.
But you're still throwing away so much time on things like bounds-checking memory accesses that never need it.
Are you? C++ doesn't check bounds by default, and Rust only checks in certain situations and you could opt out if you wanted to instead of switching to asm
Such as? I don't believe any C++ compilers are producing extra machine code just for the fun of it.
So, don't use std::variant? To produce performant output from a C++ compiler, you have to make the same sort of informed decisions that you would if you were writing assembler. Possibly not using the standard library at all.
I cannot stop being surprised by how ridiculously short-sighted developers are - and how you continue to believe in golden hammers and silver bullets. You want to build a car, so you take the “Clean Code” hammer and try to build one with it. Then you say, “Hmm, I built a car using the Clean Code hammer, but it cannot even reach 100 km/h. Therefore, Clean Code is bullshit.”
This is ridiculous.
The same applies to blind followers of Clean Code and SOLID who build systems without any high-level understanding of the system they are trying to create. The result is almost always an unreadable, unmaintainable pile of shit. In fact, they are all in the same boat.
All of these principles are just that: principles. They are not specifications to be implemented. Moreover, they are LOW-LEVEL principles. So, they cannot be “bad,” “good,” “slow,” or “fast”. Your code is bad or slow - not the programming principles.
Until you understand what you are trying to build and how it should work, you cannot decide whether Clean Code, SOLID, GoF patterns, or any other principles are appropriate. Once you have a solid architectural backbone that satisfies the required system characteristics, you can apply the principles that help you implement that design in the simplest and most effective way.
And each principle has its own trade-off with other principles! --- too much DRY -> dead coupling (all these “cores” and “libraries” that team leads cobble together at night and proudly turning a distributed system into monolith) --- too loose coupling -> excessive fragmentation -> low cohesion and broken incapsulation --- excessive SRP -> low cohesion and so on and so on.
So it is not Clean Code bad - you just not understand what Clean Code and other principles are.