• Please note that this criticism is from 2023, but the “Clean Code” book has a second edition from 2025, extensively revised to account for the many misconceptions which new programmers might have gotten from the old edition, such as interpreting rules too strictly, etc.
  • Yes, a toy problem only needs a simple implementation. This is a straw man. And I don't even like Robert Martin's Clean Code, but the author is not addressing where this style actually provides benefits. When you're updating 23 if-statements because you had to add support for some new business workflow, you'll wish you had a conceptual entity that encapsulated the operations on the type of workflows so you just had to implement them in one place.
    • Indeed. The problem is trying to apply the principles of "Clean Code" or more generally of OOP everywhere. There are surely cases where having an interface as an abstraction and multiple implementations makes sense. There are case where it doesn't, and if you take as a dogma "everything shall be the implementation of an interface" you get more complex code and performance penalty for nothing.

      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.

      • > There are surely cases where having an interface as an abstraction and multiple implementations makes sense.

        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.

        • Are you suggesting something like this?

              def createUesr(db):
                  if db is type1:
                      behaviour1
                  if db is type2:
                      behaviour2
      • The principle of clean code includes KISS, therefore complex code for nothing isn't clean code
        • Sure, but then Clean Code goes and directly pushes for polymorphism in an area (branching) where indirection and polymorphism is known to be costly for both complexity and performance.

          An 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.

    • > you'll wish you had a conceptual entity that encapsulated the operations on the type of workflows so you just had to implement them in one place.

      Why have you drawn the conclusion that the author is against this? A function with a switch-statement can do this.

      • switch is example of explicit control flow, which Clean Code argues strictly against.

        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

        • You accidentally used the phrase better approach, instead of Clean Code.
    • Thank you! I always see this stupid conversation about performance and nobody seems to get this.
      • It's much easier to optimise an easy to understand program than it is to debug a highly optimised one.
      • > stupid conversation about performance

        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.

    • > When you're updating 23 if-statements because you had to add support for some new business workflow, you'll wish you had a conceptual entity that encapsulated the operations on the type of workflows so you just had to implement them in one place.

      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:

      https://en.wikipedia.org/wiki/Expression_problem

    • It's a problem chosen by the author of Clean Code. How is it a strawman? The author of the article is directly refuting the style of the problem/solution that the original author chose, and arguably demonstrated a better approach. That is not a strawman.
      • Using `switch` is not a better approach if the design allows for outsiders to add their own shapes at a later time. Using `switch` probably is a better approach if the range is shapes is fixed and new shapes can't be added, especially if the language's `switch` statement requires that all valid cases be included.
        • Sure, but I don't see what this has to do with what I said? I was arguing against the parents assertion that the author's example was a strawman.

          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.

          • It's a strawman because Muratori took an obvious toy example meant to illustrate a concept (using classes and methods to dispatch on operations instead of using a series of if/else's as in Martin's prior example) and focused on what it did poorly (performance), but it was not meant as an example of high-performance code. It was an illustration of a concept that fit into a page. Attacking an illustrative example for not being realistic is kind of dumb.

            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.

            • An article proving its thesis that clean code can cause bad performance isn't a strawman. He wasn't intentionally using a weaker argument of Bob Martin just to find flaws. He was taking an example from the book to show where it failed.

              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.)

              • > 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.

                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.

  • I consider Clean Code to be in the category of books/styles that is helpful for early developers who need some structure, but harmful to late-stage developers who adopt it as dogma.

    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.

    • > I consider Clean Code to be in the category of books/styles that is helpful for early developers who need some structure

      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.

    • The function size is one rule from Clean Code I disagree with, it's silly. I love helper methods, but use them to a reasonable standard. I'd argue, if you cannot see it all on a 1080p monitor, that it might be getting a bit too long. I read PEP-8 religiously before I learned about "Clean Code" and it helped me to have sane standards in general. Methods that are roughly under 100 lines of code are okay, better is to fit it all in your monitor, 1080p being probably the most common resolution that leaves you with roughly 50 to 60 lines of code. If you have to scroll, you might want to consider helper functions to simplify and shorten logic.

      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 learned Clean Code at the beginning of my career, but I don't actually get it. Recently I know about "testable code" from Justin Searls. I found the "testable code" concept is more useful because we can monitor the effectiveness of the concept and I can see the actual benefits in my projects.
    • Adopting anything as blind dogma is Expert Beginner territory. See also: DB table normalization.
    • Well said. It is not without merit, but tends to attract the tedious killjoys and midwits.

      The bureaucrats who above all value process over outcome.

    • My personal benchmark for 'maybe this function is too long' is when it doesn't fit on the page.
      • I don't think any such benchmark should exist. As long as the function only does one thing there is no upper limit. Artificially splitting a large function only reduces readsbility. What would you name the parts? do_stuff1(), do_stuff2(), do_stuff3()?

        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.

        • > What would you name the parts? do_stuff1(), do_stuff2(), do_stuff3()?

          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

        • There aren't usually many domains where a process can't be described as a series of steps. Deciding what those are called, and structuring data in such a way that it each of those steps works sensibly can be challenging, but that is the process of making code comprehensible.

          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.

      • And that's why my monitor is 2560x2880.
    • [flagged]
    • > 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.

      As much as it pains you, that's exactly the feedback that should be provided to developers such as yourself, specially if you do not understand why it matters.

      Unmaintainable code is prevented at the PR stage. The likes of you need this feedback because you aren't mindful to the problems it reflects.

      The problem with a long function is not if it has N or N+1 lines of code, it's that length code with many branching conditions is prone to be untestable and introduce non trivial bugs. Once you start to refactor, not only is it easier to parse but harder to break. This fact is known for decades now.

      Your comment is really not about clean code, it reads like frustration for having team members point out the quality issues in the code you're delivering and your unwillingness or inability to understand why it's a problem and why you should correct your approach.

      There is a class of developers who are very vocal against established practices, such as OO, clean code, TDD, Etc. but ultimately when their complains are hold to scrutiny it's evident that the issue doesn't lie with OO, clean code, TDD, etc.

      • > The problem with a long function is not if it has N or N+1 lines of code, it's that length code with many branching conditions is prone to be untestable and introduce non trivial bugs. Once you start to refactor, not only is it easier to parse but harder to break. This fact is known for decades now.

        A function with too many lines is, most likely, doing more than one thing. Functions should do one thing, be easy to test (with few or no external dependencies whenever possible), be deterministic (unless required not to be), and so on. Excessive mocking is another code smell I look for - it often betrays poorly designed functions that can't be easily tested.

        • I once saw a professional software engineer try to refactor the spaghetti code in a complex bioinfomactics project written in python.

          It was a complete failure. That branch was abandoned and development continued off the spaghetti.

          There is a reason bioinformatics has its own set of viz charts that only they use.

          That's my anecdote anyway, it led me to the conclusion that sometimes things are continuous spaghetti and other than some small organizational changes, attempts to exhaustively discretize the code are a fools errand.

          The biggest benefits most projects like that are likely to see are performance and debugging improvements accomplished by factoring out recursion.

          Mapping to terrain is always the real effort in my opinion.

          • > It was a complete failure. That branch was abandoned and development continued off the spaghetti.

            It was considered too hard, most likely because the present state of the code already degenerated beyond recovery. It might be difficult, but it's never impossible.

            > Mapping to terrain is always the real effort in my opinion.

            Yes. The domain might be complex, and it might be possible that there are no simple ways to work within that domain. Irreducible complexity is, after all, a thing.

      • Fortunately we are humans, and professionally trained humans at that, and we can judge readability and comprehensibility of methods through better measures than whether it crosses a boundary of number of lines.

        There is absolutely a place for PR reviews, and I don't think the person you were replying to was against that, just that PR reviews would be better by actually judging things like readability directly rather than relying on measures that estimate those qualities.

        I can think of many times arbitrary rules like linting or Clean Code-esque standards resulted in a "solution" of making my code less readable.

        • > Fortunately we are humans, and professionally trained humans at that, and we can judge readability and comprehensibility of methods through better measures than whether it crosses a boundary of number of lines.

          It's very hard to make a function you need to scroll back and forth to understand readable. Break it into smaller ideas that are more easily reasoned about. We love to think we are too clever, but we are not and we always need to keep an eye on cognitive load - having epifanies when you finally understand how something works is a great feeling, but relying on epifanies coming to you when you are trying to figure out how something works because it's not working now, is a terrible practice.

          • I think the rule that "functions should be small enough that they should be easily reasoned about" is a reasonable rule, and it makes sense to follow it 95% of the time.

            "Functions should be 5 lines or less" is a measure that approximates that rule, but isn't exactly the same thing - I hope you agree we could both come up with 4 line functions that are impossibly complex or 6 line functions that are easily reasoned about.

            I think with Clean Code (and a lot of these kinds of things - Design Patterns is a great old example of this), people can get too dogmatic about applying these sort of approximated rules, when it would make a lot more sense for someone else (i.e. not the code writer) to use their best judgement and just directly answer the question "is this function easy to reason about?" rather than using the approximate measure.

      • There are way better metrics of function complexity, like how many branching points, how many loops, or even just how many levels of indentation.

        TDD, OOP, Clean Code, etc are an attempt to solve very real problems. They are then applied as dogma to places where these problems are not evident. That's the issue. Of course these rules have their place, but always with a caveat and never applied over all possible places where they might fit. Very often, a better solution exists, as well.

      • Clean code nitpickers mistake the map for the territory. The rules are the map, maintainability is the territory. The map is a model of the territory, but the territory always contains more detail, both zones of maintainability not covered by the rules and zones of unmaintainability covered by the rules. The rules are heuristics, and like all heuristics, they have false positives and false negatives. Being a mature developer means knowing the limits of tools including processes, style, and standards. When they nit to the rules and not to the goal, it doesn't contribute, it distracts.
      • It sounds like we have opposite programming styles!
    • So they hate clean code because they don't actually know clean code
      • Even the author of clean code would fall under someone who can’t program
        • what?

          I am talking about knowing the idea of clean code, which doesn't include dogmatically limiting #locs in functions to an arbitrary number.

          So if someone hates clean code for someone doing that, it's just dumb.

    • You mean people come to hate code reviews.

      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.

  • Ok now add a Path shape that has to calculate the area of a polygon with arbitrary complexity.

    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.

    • In that case, you'd branch into a separate function/block that runs the calculation. Sure, it's slower than a simple array index to find a coefficient, but you're only incurring that cost when you actually need it and it's still much faster than using polymorphism everywhere instead.
      • The problem in both of these cases is to how prioritize the complexity of the domain vs. the cognitive overhead of the implementation vs. the computational complexity. If the domain is complex and best represented by modeling the domain, model the domain. If the domain is simple and the the complexity is low, make it simple. If the computational complexity is high and the domain is complex, then all solutions will be bad so minimize the suck in the best way that you know how.

        Occam's razor applies to all domains. Don't use confusing implementations until there are no good options left.

  • Related:

    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

  • It seems like the main takeaway is that many textbook OO paradigms aren't the most optimized representations of the code. In this case, the cost is dynamic dispatch and pointer-chasing. This is a function of the Shape abstraction, but not the abstraction itself.

    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.

    • > In this case, the cost is dynamic dispatch and pointer-chasing.

      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.

  • How much of the performance differences come down to language or compiler choice in these examples?

    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?

    • I believe in Rust there would be almost no performance hit due to the compiler using monomorphizing everything via the "zero-cost abstraction" we love to brag about
  • I think performance generally trades along a different axis: open-world vs closed-world assumptions. There are many cases where closed-world assumptions may confer performance benefits, such as tree-shaking, whole program optimization, and using switch statements rather than a class hierarchy. Whereas designing for extensibility necessarily precludes some of those choices (though it doesn’t necessarily require OOP, for example registering a handler in a table). In other words, it’s easier to optimize a problem that is fixed and well-understood, versus one flexible and unknown. Take that ideas to the extreme and end up at ASIC bitcoin miners.
  • The only reason why your code is slow or bad - because you created it in such a way, not due Clean Code.

    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.

  • I'm not sure I follow the thrust of the article. The author starts off with talking about clean code, but then compares OO with procedural code. It's not the same thing, and of course we've always known that OO abstractions carry a performance penalty. Even the founders of OO (Alan Kay et al.) acknowledged the memory and compute impact, but thought it was a worthwhile tradeoff for clean abstractions in complex code-bases.

    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.

    • He states at the start of the article the tenets of clean code he's arguing against, not just the general OOP of it. Shows how ignoring a certain tenet leads to increase performance, that's the thrust of the article. He routinely in the article goes back to the tenets he's arguing against.
  • I'd say Clean Code is teaching many bad-practices. Too many to be recommended.
    • eh, when I read it as a newbie it was really helpful. still had to make my own experiences and judgments, but overall I think reading it made me a better programmer
      • at bast it makes to better at "Clean(TM) OOP code".

        programming in general is waaaaaay bigger than what the book covers.

        • > 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.

        • you realize reading books isn't a zero-sum game right? I can still read more books, it didn't end with Clean Code
    • > Functions should be small + Functions should do one thing

      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"

      • If your compilers is any good it will inline, and do a better job than you of figuring out what should be inlined. For that matter function calls are generally fast so long as the objects you copy as part of the function call are not slow to copy (which they can be). There are exceptions to the above, but in general small functions are not a problem.

        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.

        • > I have seen functions that were over 60,000 lines long

          That can't possibly be from a serious person.

          • I've seen 10k+ SLOC functions written in C, and 20k SLOC functions written in Fortran, so it wouldn't surprise me if people created ones as big as bluGill describes.

            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.

            • > I've seen 10k+ SLOC functions written in C, and 20k SLOC functions written in Fortran,

              That, spoken by Rutger Hauer.

          • Sadly it is serious and in production code. (I left there 15 years ago, I suspect it isn't in production anymore)

            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.
        • Manual inlining, like manual loop unrolling wants an explanation, why did you do this, why not let the compiler do it? If I see it with no explanation I am going to assume you don't know what you're doing.
      • > unless compiler will save you by inlining the function into your code or architecture

        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)

  • Make it work, then make it "clean" (that is, readable and maintainable); then make it fast, and only if measurement indicates that it matters.
  • "Code Complete" by Steve McConnell is a good option for those who want to improve their development practices.
  • I stopped reading as soon as I saw the shape class. This example (along with the proverbial animal) has done a lot of harm to OOP and programming. You need base classes (which are not always the right answer, but when they are) to be based on the abstract concept you need to model not something real that is easy to understand when someone isn't an expert in your domain.
  • Performance vs. Maintainability is the infinite debate, and it’s a mind numbing one because in the vast majority of professional roles you will have the opportunity to prefer neither.
    • And following Clean Code gives you neither. The book is written by someone with a very limited experience and the advice is either basic and obvious or harmful. People should just stop reading that book.
  • (2023)
    • Still true today.
      • I don't think it was true even in 2023.

        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...

        • This reads like contrarianism to me, like you have to oppose the article because you just do (maybe you dislike Casey). There's plenty of code written the way Casey disagrees with.
      • Nobody argues with that. But it's helpful to know right from the title that it's the original Casey's work and not something newer.
      • I wish we were at the level where some doofus has red too many "Gang of Four" "Design Patterns OOP" bullshit books and gone to town. Because that would be way better than what we have now.

        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 is just bloody stupid.

    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.

  • See also the more in-depth followup "Simple Code, High Performance (https://www.youtube.com/watch?v=Ge3aKEmZcqY)
    • Actually, that video predates the one on clean code.
      • I stand corrected. Still I'd recommend it as a followup for anyone intrigued by this post as it shows a real world, non-trivial example of removing abstractions in order to improve performance.