251 comments

[ 3.5 ms ] story [ 298 ms ] thread
I’m not sure why this is #1... but since it is, both of these - duplication and wrong abstractions - are otherwise known as technical debt.
Not necessarily. Technical debt is when you do something quick and dirty to get a feature out in the short-term knowing that it won't be maintainable, scalable, etc, but you do it anyway with the expectation that you'll fix it later. Some duplication and wrong abstractions are caused by this, but definitely not all.
No, technical debt is a very general category that includes deliberate hacks, structural flaws, and small mistake bugs. It's anything that over time will damage the code base, duplications and wrong abstractions being very much included in that
You're welcome to your own definitions, but personally I keep bitrot, deferred maintenance, and "structural flaws" (which can be subjective and dependent on use cases and scale) out of the bucket of technical debt since it robs the metaphor of a defining aspect: intentionality. Debt is not something that happens passively as the world changes around you, it's something which you sign up for.
If you unintentionally destroy property and have to pay for it, you’re in debt.

We even have a concept of life debt.

Some debt is intentional, some incidental.

Most technical debt I’ve seen was not intentional, just a well meaning design that was created to serve a purpose that eventually outgrew it, and that’s when the interest started to pile up.

And happening passively is exactly what it does, interest rates change, your ability to make downpayments change. All part of the very well functioning metaphor in this context.

cc my know-it-all coworker
Why not simply duplicate the abstraction, refactor as needed, and adjust the necessary caller(s)?

Having to know, find and maintain the individual duplications feels dirty and its own way wrong.

Choose your wrongs wisely?

Every Line Of Business codebase I've worked on has been the worst "there I fixed it" copypasta spaghetti, and has never made it to the point where "maybe we shouldn't add a parameter to this existing, cleanly abstracted method to handle this new similar-but-distinct use-case" was anywhere near my radar for abstraction.

I would love to have developers where my problem was "maybe you piggybacked on existing code too much, in this case you should've split out your own function".

It’s been the exact opposite for me. The spaghetti code has always come from poorly conceived abstractions and the massive problem of inverting an API to reimplement functionality through the API that should be extensible within the API (but fails to be because of poor choices in abstraction or abstracting prematurely).

Later on that spaghetti code gets labeled as lacking abstraction, similar to what you are saying, despite the actual problem being too much abstraction and poorly designed abstraction that became load bearing in a way where everyone decides that living with API inversion as a reality is the lesser evil and figures they’ll probably quit the company and move on to greener pastures before it becomes their headache to deal with.

https://en.m.wikipedia.org/wiki/Abstraction_inversion

Absolutely this. I’d rather look at 200 lines of linear, inline documented code then a spaghetti mess of “helper” functions that do nothing better than obfuscate everything going on.

I’ve had a strict rule with my team of “1, 2, N”. I don’t want to see an abstraction until we’ve solved a problem similarly at least two times, and even then an abstraction may still be a poor idea.

Abstraction is an especially poor idea early in a project because often you only half know what you’re making (I’m in games). Requirements change, or a special case needs to be added, and all of a sudden you are trying to jam new behavior into “generic” helpers without breaking the house of cards built around them.

200 lines of code means that you have to comprehend all 200 lines simultaneously since any line could potentially interact with any other line in that code block. Using functions where the state is passed as parameters limits the potential for code interactions through functional boundaries. The point of abstractions are to limit complexity by limiting potential interactions. Helper methods do a fine job of this.
That’s a gross over-generalization to assume that 200 lines is always a self-referential mess. Functions fundamentally transform data, and often that transformation is a linear process. If it’s not, sure, break it up in a more sensible manner.

Regardless, helper methods have a significant cognitive cost as well. It’s nice to pretend that a four word function name can entirely communicate the state transformation it does, but in reality you need to know what it does and mentally substitute that when reading the function using it. No free lunch.

>That’s a gross over-generalization to assume that 200 lines is always a self-referential mess.

The point is that you don't know this until you look. You have to look at all 200 lines to understand the function of even one line. When you leverage functional boundaries you generally can ignore the complexity behind the abstraction.

You're fooling yourself, in a mature codebase, if you think you can modify code and not look past function boundaries.

That assertion would be more credible in a language that captures side effects in the type system, but that's not what most people use.

I'm not sure what point you're making. If you are just assuming that functional boundaries tend to not be maintained in practice then you're not contradicting anything I have said. Whether or not functional boundaries are easy/hard to observe depends on the language and coding conventions.
I worked on a webapp that our team inherited which had 400-800 line controllers (and one that was a little over 1200 lines). When I first started looking at the code I was horrified but then I realized that everything was self contained and due to the linear flow, pretty easy to understand. You just had to get used to scrolling a lot!

The issue that we started having is that pull requests, code reviews, and anything that involved looking at diffs was a lot of work. There were two main issues:

1) Inadvertently creating a giant diff with a minor change that affected indenting, such as adding or removing an `if' statement.

2) Creating diffs that had insufficient context to understand: if your function is large enough, changes can be separated with enough other lines of code to make the diff not be standalone. You end up having to read a lot of unchanged code to understand the significance of the change (it would be an ideal way for a malicious developer to sneak in security problems).

I agree that over-engineered helper function hell can be a real problem.

I disagree strongly with strictly enforcing the 3x rule. The right abstraction can be helpful even if it is used only once. The right abstraction will communicate its purpose clearly and make it easier to reason about the program, not harder. Obfuscating implementation details is a feature not a bug, as long as the boundaries of the abstraction are obvious. Another benefit is it makes it easier to test the logical units of your codebase.

"It’s nice to pretend that a four word function name can entirely communicate the state transformation it does, but in reality you need to know what it does." Are you suggesting you are cognizant of every line of code of every library you use in your work?

Actually yes, you should know to at least depth=1 what your magic incantations are doing when you call them.

And that’s part of my point, if you go that one level of depth and find an excessive amount of DRY, you’ll find it that much harder to know what the hell is going on.

Yes, you should understand what a function does when you call it. Not everyone who looks at a codebase is modifying the codebase or adding new function calls. The person referencing the code may already be 1-level deep in parsing the implementation.

Not all abstractions will seem like a magic incantations when you use them. Something like "convertToCamelCase" conveys its purpose clearly enough that the reader can assume what the low-level operations are. They don't need to look at these operations every time they need to reference the code.

wow, just reading that term "line of business" makes me anxious. I used to work on a global payments platform that supported "multiple LOBs", and it was a nightmare of ifs and switch statements all the way down. The situation was made more difficult by the fact that our org couldn't standardize the LOBs into a common enum.
The business codebase I'm working on now was written by OOP crazy people who thought inheritance was the solution to every line of duplicated code. When they hit roadblocks, they filled the base class with things like if(this.GetType() == typeof(DerivedClass1)){...

I would do anything to have the duplication instead.

Very relatable. And they even have the guts to call this code "SOLID"
Once you ask what the class is you're no longer even "OOP crazy".

You've just capitulated to the complexity and do whatever it takes.

I don't want to sound (too) condescending. I know how easy the best intentions can lead a project there. This job is hard.

If you're truly OOP crazy you will always find ways to avoid resorting to branching on types or even avoid branching altogether (just on the language level of course). "There's a design pattern for that" :-)
Checking for the type is the exact opposite of OO.

The correct OO would be to think about what the check represent, maybe abstract it in a base interface with pure abstract methods and derive from that interface.

What you describe is what people without understanding of OO do when they come from a language without OO.

> they filled the base class with things like if(this.GetType() == typeof(DerivedClass1)){

That defeats the purpose of polymorphism.

Then the very same people learn that inheritance bad, composition good, and they'll create abstractions with no meaning on their own, which call 10 vague other abstractions (but hey, no inheritance!). Figuring out what happens there is even worse than with inheritance. Some people grow out of it, fortunately (mostly after having to deal with shit like that once or twice).
> ...they'll create abstractions with no meaning on their own...

As if that doesn't happen with inheritance!

The dark pattern is using inheritance as an alternatve way of implementing composition. Anyone who thinks that "inheritance bad, composition good" is the proper response to this is probably as confused about the issue as those making the mistake in the first place.

To be clear, you are clearly not making that claim yourself, but you are invoking it to make a straw man argument.

In contrast, every junior developer I've ever worked with has wanted to abstract too early and often, and been slow to recognise that abstraction has costs too (often far higher over time than is initially obvious).

There are costs to copying code, and costs to abstraction, and there's a balance somewhere in between where the most resilient and flexible code lives. The costs of both are paid later, which makes it very hard to judge when starting out where that balance lies, and hard to assign blame later on when problems manifest. Was it too little abstraction, or too much, or the wrong abstraction?

Note that the article claims that duplication is cheaper than the wrong abstraction. The problem is not abstraction in itself, but that abstraction is very hard to get right and is better done after code has been written and used.

What I run into with juniors is that yes, they want to abstract the new problem, and that's good... But they show disinterest in learning the existing abstractions and the existing problems and how their new code would fit into that. Given that approach, you end up with a million individual "frameworks", each only solving a single specific case of a series of overlapping similar problems.

Because reading code is harder than writing it. And the only thing worse than "there, I fixed it code" is "there, I fixed it with this massive cool new framework I've built".

yes, they want to abstract the new problem, and that's good...

I'm not sure that is good. I started off this way too, but now I like to think carefully about abstractions and avoid introducing them till I'm sure it will not hinder understanding, hide changes/bugs, bury the actual behaviour several layers deep, or worst of all make things hard that should be easy later (the problem in the article).

Building abstractions is world-building; it's adding to the complicated structure other developers (including your future self) have to navigate and keep in their head before they can understand the code. So perhaps because of your second point (that people rarely like other people's abstractions), it's better to keep abstractions simple and limited.

Every failed IT project that I have worked on in the last 20 years (except those where the cause was non-technical such as bad planning/ bad requirements), failed because it used too many layers of abstraction.
Tnere is truth in this! I've also seen that some of the most successful projects with the highest performers are the most full of duplicate code.

The operating theory is to be first to market in order to capture the largest market share and be the market leader. Programs are just tools that can be rewritten later. That's similar to any large tech company today that "innovates" then apologizes later.

If a company has been running long enough to be making money, chances are their codebase will be crap.
Counter: Every failed IT project that I have worked on in the last 20 years had too much code. Code is bad. Delete code mercilessly.

Seriously though, the problem are bad abstractions, not just abstractions. A total lack of abstractions is typically a spaghetti you need to read fully to understand.

When I read these threads I feel like I must be working on another planet to the people commenting in them.

In almost every front-end project I join, there's a positive correlation between number of abstractions and code size. Everything is so "best practice one size fits all"-y that you can usually start with halving the size of the code base by removing 50% of the dependencies.

Even once you've done that, you can usually speed up development by cutting 50% of the remaining dependencies. All the ones where the API surface area is more complex than the bloody implementation. Code is bad, sure, but at least it speaks for itself. A lot of the time the choice is between 3 lines of code that are well written and self explanatory, or 1 line of code that is incomprehensible without trawling through 800 lines of documentation first.

I agree that code size is probably the most important metric for measuring complexity, but it's not an absolute thing. If you're too merciless with culling code, you can easily code yourself into a shitstorm of required context that makes hiring and onboarding impossible. Having said that, I think the problem is mostly contained to using other people's abstractions. I can't think of many times I've walked onto a project and gotten lost in the mud because someone there had coded up something that was too convoluted. Only one springs to mind and it was a back-end system.

And that probably gives some clue as to why nobody can agree on this stuff. I'm guessing different ecosystems lie on different points on the scale, and so different approaches are going to be more successful. I've seen probably 20 projects grind to a halt because of overabstraction, and none because of code duplication. But I'm sure there's other programmers involved in other communities and industries that have seen the opposite. So if we're talking to a faceless crowd on a forum, we're going to give vastly different advice, under the assumption that the people we're talking to are somewhere around the average of everyone we've ever worked with.

I think that it depends on what you define as an abstraction. I think we're often just counting wrong or plainly heavy-handed abstractions here.

There are many abstractions which you can cut and reduce code size, e.g.:

* Complex frameworks which do not fit your case * Overused GoF-style design patterns which have no place in this day and age * Magic ORMs generated with annotation processors * Universal Tool Factory Factory Factories[1]

The thing is, you're usually not replacing these abstraction with plain old code duplication (let alone the dreaded "fixed A here, fixed B there" copypasta). You usually replaced dependencies (frameworks, ill-fitted libraries and factory-factory-factories) with your own implementation which is a better fit for your needs, and that can be viewed as duplication - sure. But you'd usually still only have ONE implementation in the code base.

In short, in most cases I've seen where we eliminated bad abstractions and save on code, we replaced them with good abstractions, not (a lot of) duplication.

[1] https://medium.com/@johnfliu/why-i-hate-frameworks-6af8cbadb...

> there's a positive correlation between number of abstractions and code size

What really matters to me is how much code I need to read to understand how it works. I prefer to work in codebases where I need to read 100 lines out of 1200 instead of 1000 of 1000.

Good abstractions are not about code duplication - they are about simplifying conceptual models - so I don't need to understand these details of everything, but I can still understand the system as a whole. And this is the hard part to get it right.

Many developers often mistake indirection for abstraction. The worst codebases I worked on had plenty of indirection, many components and many dependencies (often cyclic!), but they actually lacked abstraction or mixed different abstraction levels. A component that is so universal that it can render webpages, solve differential equations and wash the dishes all in one function is not a good example of abstraction.

I just had to debug code that had seven layers of classes on top of dapper to call a stored procedure in SQL server.
I have had exactly and overwhelmingly the opposite experience. I wonder if it's a function of our fields, or what...
So much this. I've encountered many codebases (in science and in tech) where the coder did not even use basic abstractions. In one case there was a lot of

    plot('graph1')
    plot('graph2')
    ....
    plot('graph100')
because somebody didn't know how to create strings at runtime in C++. Another codebase did complex vector calculations in components, I was able to reduce a 500 lines function to 50 lines (including comments, and with bugs fixed).

I can sympathize with this a bit, I started programming with BASIC - you could not return structs, you could not use indirect variables (no pointers/references)... but at least you had the FOR loop :-P

People get often called out for over abstracting (rightly so), but I've rarely seen somebody critisized for copypasta or for overly stupid code. Probably because we're too accidentially afraid to imply somebody can't code.

> I've rarely seen somebody critisized for copypasta or for overly stupid code.

Do you think that is in the realm of what the article is concerned with?

    plot('graph1')
    plot('graph2')
    ....
    plot('graph100')

I've done a lot of that myself. What you might not be seeing is the for loop in a scripting language that was used to generate that text. It probably took less effort than looking up and implementing it the "right" way. It might make your eyes bleed but if you need to change "plot" to another function, that's just a find-and-replace-all away. Most importantly, the code works fine and doesn't actually need abstraction.
> the code works fine and doesn't actually need abstraction

Well, maybe it works fine. We didn't see the other 97 lines to verify that they actually include all the integers from 3-99 without skipping or duplicating any. (NB with a loop this verification would be trivial.)

Maybe they deleted 57 because it triggers an edge case. Put it back if you dare. ;)

(no, that's the bad kind of tech debt that's unfortunately common and I actually hate)

Yes, writing a for loop in another language to generate code instead of just writing the same loop in the language you're already using? Common technique, nothing wrong with it whatsoever.
Yes, a lot of scientists use their computers in ways that horrify software developers. For example, learning exactly enough of a compiled language to do some wicked fast integer / floating point arithmetic, and not bothering to waste time on the mundane crap you find obvious. And that might mean falling back to a familiar language that makes string formatting easy.

If it ain't broke, don't fix it.

> If it ain't broke, don't fix it.

But scientific programming is deeply broken. Code presented along with publications often doesn't work, or is an incomplete subpart/toy example that's supposed to be invoked within some larger framework. That sounds great until you realize that "some larger framework" doesn't refer to a standardized tool, but some deeply customized setup (a la the one you're responding to, that uses e.g. ad hoc code generators across two--or sometimes more--languages because the original authors didn't know how to format a string in one of them).

Even if you do get lucky enough to find a paper with all requisite code included, in many cases it was only ever invoked on extensively customized, hand-configured environments. And that configuration was done by non tech folks with a "just get it to where I can run the damn simulation" attitude, so configs are neither documented nor automated. And when I say configs, I'm talking about vital stuff--e.g. env vars that control whether real arithmetic or floating point is used.

Often as not, you hack your way to try to get something--anything--running, and it either fails catastrophically or produces the wrong result. Now you have to figure out which of several situations you're in: is the research bad? Were the authors just so non-technical they accidentally omitted a vital piece of code? Was the omission deliberate and profit-motivated (e.g. the PI behind the paper plans on patenting some of the software at some point, so didn't want to publish a special sauce)? Was the omission deliberate and shame-motivated (i.e. researchers didn't want to publish their insane pile of hacks written to backfill an incomplete understanding of the tools being used)? Is it an environment-dependent thing?

And all of that is just as pertains to code in published work--usually the higher-quality stuff. Assuming ownership of in-house code from other scientific programmers is much, much worse.

This isn't abstract moaning about best practices. The failure of labs, companies, publications, and universities to combat this phenomenon has direct, significant, and negative effects on the quality of research and scientific advancement in many fields.

TL;dr it is "broke". When programmers complain about reproducibility crises in soft-science fields, they're throwing rocks from glass houses.

You're bringing in a whole host of issues inapplicable to the snippet OC found questionable. Don't disagree with ya, but "lack of obvious abstraction" isn't one of these "extreme sensitivity to environment vars" cases.

In fact, vociferously complaining about such cases is a great way to turn scientists away from code review as a concept. Fold the code away in your head (or edit your local copy), and dig for subtle issues like numerical sensitivity, environment, etc. That's the way to bring actual value to the process.

For the code in question, "oh by the way this can be done simpler", with the simplified snippet, is an appropriate approach to the review. But in my experience it's best to save your breath for actual problems.

(comment deleted)
This is fine for code that belongs in the trash, ie. just testing stuff, prototypes, debugging, learning the language/framework, etc.
Code like you describe is of often the result when a program is written by someone that does not have programming as their main profession. I have seen code like you describe in code written by scientists (in other disciplines than computer science).

They may have very deep knowledge in their field, and have written a program so solve some problem they have, but are unfortunately not very good programmers. This often results in quite naive code that still try to solve an advanced problem.

In code written by professional programmers, I have seen the pattern described in the article far more often than the naive style you describe. After all, programmers are trained to avoid duplication and finding abstractions, and will often add one abstraction too much rather than one too little.

This comes up very often and is probably a big part of the distaste many people have for jQuery. You see so much copypasta $(selector) that queries the entire DOM over and over again instead of storing the intial query in a selector, querying children based on a ParentNode, etc.. This duplication is wasteful at best, and can hurt performance at worst.

But as others noted, this is usually the sign that the creator is either green, or puts little focus in furthering their programming because they normally do other things--not malice or carelessness.

I saw a post on here recently about the “proportionality of code” (I think this was the term used) - as in, how much one line of code translates to in terms of work for the machine. Python was used as an example, in contrast with Go (list comprehensions vs Go’s verbose syntax).

I think a similar line of thinking is applicable here. $ hides a lot of work behind short syntax. The syntax isn’t “proportional” to the work. Not only that, but the amount of work depends on the argument. Perhaps it’s better that we’re forced to put the effort in and type out “document.getElementById” - it makes us think about what we’re doing.

> but I've rarely seen somebody critisized for copypasta or for overly stupid code. Probably because we're too accidentially afraid to imply somebody can't code.

It's because it's a far more benign problem than too much abstraction.

Sure it's easy to poke fun at that code and lol at how the programmer can't even use the most basic kind of abstraction, but that code is still clear and easy to read. More importantly, it is trivial to fix that kind of error.

I would take code like this any day over code written by an experienced programmer too keen on abstraction.

Nothing I hate more than seeing two files or more, sharing 90% of the same code. No matter what justification one attempts to use, there's a mistake somewhere in the design / development process.

I can see a case for what the OP is saying, but I feel it should always be seen as a temporary measure.

I'm skeptical because it is really easy to un-share code by copying it into multiple places but it is very hard to unify duplicated code. So I prefer to err on the side of sharing.

But yes, you should be ready to change sharing into duplication if you realize the code is just "accidentally similar" and need to evolve in separate directions.

In practice I have seen a lot more pain due to duplicate code compared to the issue of over-abstracting code, because the latter is much easier to fix.

On the other hand, it's really difficult to know who is using that shared code. If you make an innocuous change in a shared method, it could affect someone else you don't know.
Outside of publishing a public API almost any modern language and enviroment should make this easy.
It's a million times easier than figuring out if those minor differences in duplicate code are accidental or on purpose.

As bad as a flag-laden method might be, you know the intent of all callers.

I find it much easier to find the call sites for a function than to find code that’s duplicating or a variant of the code I just fixed a bug in so we can figure out if the same bug is latent in the duplicates too.
Not in any modern language or IDE. Not to mention that would indicate a hole in the test suite
It doesn't have to be that way, it's just because our existing language facilities don't have support for what we need them to do:

"Names are regularly repurposed to point to new definitions, even when the old definitions are still perfectly valid. For instance, a library author might make a function a bit more generic by adding an extra parameter, or decide to switch the parameter order. That's fine, but the old definition was not wrong, so should users be forced to upgrade? No.

Repurposing names is fine; it's hard to come up with good names for definitions, so using an old name for a related new definition often makes sense. The trouble is that existing tooling doesn't distinguish between repurposing a name and upgrading a definition. Unison changes that..." https://www.unisonweb.org/2020/04/10/reducing-churn/#incompa...

Depends on a specific codebase? I found exact opposite to be true - very hard to reuse code that was abstracted too soon, and abstracting copy&paste the right way is actually easier if you have it in multiple cases and can see how it was used.
My experience lines up with yours. Working in overly and poorly abstracted codebases dramatically hurts productivity. Poorly duplicated code increases the chance for missed patches, but poor duplication has, in my experience, been vastly easier to fix. One codebase comes to mind. Twisted Python. Multiple layers of inheritance, multiple mixins, and major overloading of methods. Just navigating the code was pain.
How is it harder to copy/paste the helper method and modify as needed, vs tracking down and unifying multiple instances of the same code written slightly differently?
Because the multiple instances are concrete while the unified code is abstract.

In general it is more difficult to read abstract code than concrete code.

Also code written using the wrong abstaction can get hairy very quickly (lots of "if" statements for various cases).

In Java, when I hit a bad abstraction, I hit the inline shortcut (command-alt-n) and then evaluate the resulting code with git diff. Other languages may be more manual, but, at worst, you just use ripgrep or similar to find all the relevant use sites and then manually expand the abstraction: this is only really a problem it the function is used hundreds of time: but, in that case, you can always duplicate the abstraction and rename.
> it is really easy to un-share code by copying it into multiple places but it is very hard to unify duplicated code

Code that already exists has a gravity, a presumption of correctness. That presumption is very difficult to overcome, especially for programmers new to the codebase. An abstraction you think of as temporary will be, to those who come after you, simply the way things are done; breaking it apart and re-forming it is, for them, fraught with risk. It's good to keep this in mind as you make commits.

Then the same would be the case for code duplication which really ought to be unified.
I don't think I agree. Identifying an abstraction as leaky and breaking it apart is substantially more difficult and riskier than identifying duplication and creating an abstraction for it.
Removing an abstraction layer can usually be done mechanically by inlining the calls. This is a trivial operation. Identifying duplication not trivial since there might be various differences and you have to investigate if they are inconsequential or not.
Brilliant insight. Always remember: (1) make it work, (2) make it right, (3) make it fast. 80% of projects get scrapped in between (1) and (2) because you end up realizing you wanted something completely different anyway.
On my projects code doesn't make it into the main branch until it gets to at least (2).
> (1) make it work, (2) make it right, (3) make it fast.

I've always disagreed with this. In my view you should make it a habit to write optimized code. This isn't agonizing over minor implementation details but keeping in mind the time complexity of whatever you are writing and working towards a optimal solution from the start. You should know what abstractions in your language are expensive and avoid them. You should know roughly the purpose of a database table you create and add the indexes that make sense even if you don't intend to use them right away. You should know that thousands of method lookups in a tight loop will be slow. You should have a feel for "this is a problem someone else probably solved, is there a optimal implementation I can find somewhere?". You should know when you use a value often and cache it to start with. Over time the gap between writing unoptimized and mostly optimized code gets smaller and smaller just like practice improves any skill.

> You should know that thousands of method lookups in a tight loop will be slow.

That's not always the case. Modern compilers do a lot of things like inlining and unrolling. These days I mostly try to write code that is easy to understand.

> Modern compilers do a lot of things like inlining and unrolling

Smart ones do, I've been writing Java lately and that behavior tends to be unpredictable and rare[0]. I'd use a inline keyword if I had one, or preprocessor directive of some kind if I had that but I don't. I agree it's harder to read but I feel like changing a JVM flag to get a behavior that I want is more inscrutable than having a long method with a comment noting that this in inlined for performance reasons. With modern machines and the price of memory I tend to lean hard to the memory side of the time-memory tradeoff.

[0]"First, it uses counters to keep track of how many times we invoke the method. When the method is called more than a specific number of times, it becomes “hot”. This threshold is set to 10,000 by default, but we can configure it via the JVM flag during Java startup. We definitely don't want to inline everything since it would be time-consuming and would produce a huge bytecode." https://www.baeldung.com/jvm-method-inlining

> In my view you should make it a habit to write optimized code.

It depends on your domain.

If you're writing for embedded, or games, or other things where performance is table stakes, then sure.

If you're writing code to meet (always changing) business requirements in a team with other people, writing optimized code first is actively harmful. It inhibits understandability and maintainability, which are the most important virtues of this type of programming. And this is true even if performance is important: optimizations, i.e. any implementation other than the most obvious and idiomatic, must always be justified with profiling.

You're mostly right, but even in typical LOB applications, there are some low-hanging fruits you should really pay attention to. One common example are N+1 queries.

And if you do find yourself writing an algorithm (something which happens more rarely in LOB applications, but can still happen occasionally), it's probably still good to create algorithms that are of a lower complexity class, provided they are not that much harder to understand or don't have other significant drawbacks. I remember that I once accidentally created an algorithm with a complexity of O(n!).

I find that first comment particularly insightful.

However, I am not sure about the order of state and coupling. To me it seems to depend on the language, as for functional languages, avoiding state is king and in object oriented environments, coupling could be a more important factor.

I wish this article was available two years ago when I tried to explain this to a bunch of juniors working for me...
“ Posted on January 20, 2016 by Sandi Metz.”
Damn, I wish I saw it back then :)
Junior programmers duplicate everything.

Intermediate programmers try to abstract away absolutely every line that occurs more than once.

Expert programmers know when to abstract and when to just let it be and duplicate.

The master never duplicates and all his abstractions are intuitive, readable and flexible.
I use DRY in two ways. The first is that I'm happy to make 2 or 3 copies of a snippet before promoting that to a new function.

The second is when I find a bug in a duplicated snippet. I'll mend the snippet and its duplicates, once or twice before promoting it to a function.

In the rarer (in my line of work) instance that a common snippet gets used with several intrusive variations, I usually document the pattern. It's tempting to use templates, lambda functions, closures, coroutines, etc but far simpler to duplicate the code. But again, if a bug (or refactor) crops up and I need to fix it in many places, then I'll spend some time thinking about abstraction and weigh the options with the benefit of hindsight.

You can’t plan for what you don’t know.

This is why I like the "Rule of three"[1]. Only once you've done it three times will you truly begin to understand what the abstraction might need to look like.

1. https://wade.be/2019/12/10/rule-of-three.html

Exactly. With experience, you learn not to abstract too soon.
Seems so counterintuitive, but it’s one of the most important lessons I’ve learned in 15 years of development experience.
(comment deleted)
Any advice on teaching this to junior engineers? Seems like folks with 3-5 years of experience keep trying to not only over-abstract but also keep re-inventing the wheel with abstractions (vs looking for existing libraries).
(comment deleted)
It's largely because they're dealing with an area with no theoretical tools. Any time you hit an area that are full of people "Designing" solutions/abstractions rather then "Calculating" an optimal solution/abstraction you know you've hit an area where there's very little theoretical knowledge and most people are just sort of wandering chaotically in circles trying to find an "optimal" solution/abstraction without even a formal definition of what "optimal" is.... I mean what is the exact definition of the "perfect abstraction"? What is bad about duplication what is a bad over abstraction and what is this "cheaper" cost that the title is talking about? It's all a bunch of words with fuzzy meanings injected with peoples biased opinions.

That being said theories on abstractions do exist. If you learn it you'll be at the top of your game; but it's really really hard to master. If you do master it, you'll be part of a select group of unrecognized elites in a world of programmers that largely turn to "design" while eschewing theory.

Here are two resources to get you started:

The Algebra of Programming: https://themattchan.com/docs/algprog.pdf

Program Design by Calculation: http://www4.di.uminho.pt/~jno/ps/pdbc.pdf

You will note that both of these resources talk about functional programming at its core which should indicate to you that the path to the most optimal abstraction lies with the functional style.

My favorite example of really bad abstraction is add/edit crammed into single popup/model. You know edit is basically a copy paste of add so "ding ding ding here goes DRY!" in a junior mind. But quickly enough it shows up that some properties can be set in add, whereas in edit they have to be read only. Quite often you get also other business rules that can be applied only on edit or make sense only when adding new entity. But when you create first version they look a lot like the same code that should be reused.

For me this is really good example of how similar looking code is not the same because it has different use case.

> But quickly enough it shows up that some properties can be set in add, whereas in edit they have to be read only.

So? Just put in some conditionals.

What is the alternative? Duplicate most of the code with minor, non-explicit differences? What's the benefit? You just moved complexity around, you didn't get rid of it.

The drawback is that now anything you have to add, you have to add and maintain it in two places. And since your "add" and "edit" are probably 90% the same, it's going to happen 90% of the time. It's very annoying during development and you're likely to fuck it up at some point.

This is a good example of how this overall topic gets reduced to "How much abstraction?" instead of "In what ways should something be abstracted?"

Obviously an Add/Edit field are operating on the same record in a hypothetical database, so it makes little sense to duplicate the model.

On the other hand, if the conditionals within the abstracted version become too complex or keep referencing some notion of a mode of operation (like, ` if type(self) == EditType && last_name != null` lines of thinking), that is sometimes another type of smell.

But say you make some kind of abstract base class that validates all fields in memory before committing to the database, and then place all of your checking logic in a validate() method. That sounds like pretty clean abstractions to me.

And moreover, this is probably provided by an ORM system and documented by that system anyway--so that's a publicly documented and likely very common abstraction that you see even between different ORMs. That, I think, is the very best kind of abstraction, at least assuming you are already working in such an environment as a high-level language and ORM. Making raw SQL queries from C programs still contain their own levels of abstractions of course without buying whole sale into the many-layered abstraction that is a web framework or something.

This question becomes more important when you aren't just updating a database though. If you're writing some novel method with a very detailed algorithm, over abstraction through OOP can really obscure the algorithm. In such a case, I try to identify logical tangents within the algorithm, and prune/abstract them away into some property or function call, but retain a single function for the main algorithm itself.

The main algorithm gets its definition moved to the base class, and the logical tangents get some kind of stub/virtual method thingy in the base class so that they have to be defined by subclasses. The more nested tangents are frequently where detailed differences between use cases emerge, which makes logical sense. It's not just that it's abstract, but the logic is categorically separated.

It's a very general pattern supported by many languages, so you see it all over the place. That organization and consistency in itself helps you to understand new code. In that way, it also becomes a kind of "idiom" which in a sense is one more layer of abstraction, helping you to manage complexity.

As a counter of that, you see code where `a + x * y - b` becomes self.minus(self.xy_add(a), b). More abstract, but not more logical; not categorically separating; not conforming to common idioms; obscuring the algorithm; and so on...

And then there is performance! Let's not talk about the performance of runtime abstractions.

I mean, aren’t we just bikeshedding inheritance at this point?
Each to his own. If I found that a junior had created two separate popups, one for add and one for edit, I'd want to look into the code with them to understand if that was a good choice, because usually it wouldn't be for anything with more that one or two properties.
I just had a case of this last week in a web-app I’m writing.

In the frontend code I decided to use an abstraction and parametrization in the backend code I kept the logic separated.

It really depends on context. Specifically on the layer you are operating on.

I think there are two parts to it. First, you want to push them to get into the habit of solving problems by expressing the question clearly enough that the answer falls naturally from it. That's so fundamental that every aspect of engineering benefits from it, but it's particularly important as a first step in writing code.

The second part is building the intuition for the abstractions themselves. That's tricky as they have to teach themselves. They need to build coherency in their internal mental langauge of abstraction, and the only way to do that is to work directly on real code, and work through the consequences of doing it one way vs. another.

That means you have to let them commit code you don't like. By all means, explain what your concerns are, but then let them see how it evolves and as it becomes more untenable, that's when you go back to rethinking it and trying to state the problem clearly.

Likewise, when they do it well, you can highlight that, especially drawing attention to changes to their code that worked nicely.

Teach them about cyclomatic complexity and then review their work in these terms. It gives them something concrete to target rather than trying to accomplish some ethereal notion of "proper abstraction".
Bring the idea that abstraction has a cost, like technical debt. It’s not something to be proud of, on the contrary, it must be justified and serve a true purpose and not be only an intellectual satisfaction.
I dislike any programming rule which includes a number.

The issue is whether sections of similar code implement the same idea or just happen to be accidentally similar. The number of instances does not really matter. If you have 100 lines of code which are almost the same two places in the program, then you should unify sooner rather than later, before they are allowed to diverge.

Rules are great because they can be broken, if you know when to do so.
The rule of three helped me get get over my initial abstraction issues, but I leaned much more towards a rule of 5 or 6. Around three you finally find an abstraction, but around six uses there is a good chance it breaks down. Making an abstraction saves you from having to make the same change to the code you copied multiple times. But the cost of repeating yourself is so low. With good keyboard mechanic repeating a change in four to five place take just a bit longer than doing it once since most of the upfront cost is in deciding on the correct change. It does feel a bit like drudgery, but it’s also very freeing to not think about abstractions and just make progress at all costs. It’s strategy can bite you if you don’t take the time to look back and make a refactor later, but I find the approach of churn out code and letting the patterns emerge then restructuring with hindsight much more fruitful than pausing frequently to think about it abstractions. They are really two different mindsets and best left for different sessions of work.
This quote from John Carmack speaks very succinctly to the problems that many abstractions in a code base can cause, and it's a constant reminder for me when building out business logic.

> "A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in."

https://www.gamasutra.com/view/news/169296/Indepth_Functiona...

But abstractions reduce possible state and allows you to specify that state in obvious ways, e.g. on function parameters. Do not underestimate the power of functional boundaries.
They also tend to impose a degree of discipline. I've often found myself wanting to shove a parameter in somewhere and realized I didn't need the damned thing.
This is one reason I love working in the Unity ECS framework. Your data is public and state can’t hide. Your systems are still free to contain a plethora of bugs, but they are easier to track down due to the functional nature of a system.

In the regular Unity OOP land, developers inevitably sprinkle state everywhere. Coroutines are by far one of the worst offenders. Good luck seeing the current executing state of your game when it’s hidden in local variables inside a persistent function body...

Reading that article and the context of the quote, it appears that Carmack is using that statement to extol the benefits of functional programming styles, not commenting on abstraction.
To me the quote speaks to the general problem of juggling state in your head when writing code. If an abstraction is an attempt to funnel a bunch of code through common logic, it can be hard to understand know what the state of your app will look like when someone else modifies that common logic.
(comment deleted)
Another tip is: if you're duplicating, and they're not lines of code that are visually obviously next to each other, then leave a comment next to both instances mentioning the existence of the other.

There's nothing inherently wrong with duplication, except that if you change or fix a bug in one, you need to not forget about the other. Creating a single function solves this... but at the potential cost of creating the wrong abstraction.

When you're at only 1 or 2 extra instances of the code, just maintaining a "pointer" to the other case(s) with a comment serves the same purpose.

(Of course, this requires discipline to always include the comments, and to always follow them when making a change.)

Would the risk forgetting to update the comments not be a reason for creating a wrapper method that handled calls to both and contained the relevant advice?
(comment deleted)
Mods this article is old, should be labeled 2016.
Early de duplication is the equivalent of early optimization: a bad idea that boxes you in.

Duplicate code is a sign that there could be a generalization missing.

"With C you can shoot your own foot. With C++ you can blow your own leg off". I feel the same is true here.

The abstraction may be right at the time of writing, yet further on it often becomes not only wrong, but a massive hindrance.

With time and effort, hacky code and be worked into shape. An eventual wrong abstraction normally means a rewrite.

This is so true, but so shallow too. I think the big mistake is to treat the code as "the main thing" when in reality it's just a model (a golem) mimicking some "other thing"

We're missing an entire set of code characterizations. Yes we have a "pattern language" but there's not much to characterize it structurally wrt "code distance" from one part of the code to the other (e.g. in call stack depth as well as in breadth).

And again all of this needs to happen wrt the "abstraction" not the code itself. Having 10 methods 90% duplicated in a single file with 10% pecent difference is many times better than trying to abstract it.

Having the same "unit conversion" function duplicated in 3 parts of the code can be disastrous.

These two examples are very easy to see and understand, but in reality you're always in a continuous state in between. And "code smells" like passing too many parameters or doing "blast radius" for certain code changes are only watching for side-effects of a missing "code theory". An interesting book on the topic is "Your code as a crime scene".

The bottom line is we're trying to fix these problems over and over again without having a good understanding of what the real problem is and this leads to too many rules too easy to misinterpret unless you are already a "senior artist"

> Having the same "unit conversion" function duplicated in 3 parts of the code can be disastrous.

This.

I feel like it's really about cognitive load to remember and recognize the differences.

Duplication in 3 distant files, places a heavy load on the developer to:

1. Discover the duplication 2. To grasp the reason for the differences in the 3 different locations. 3. Remember these things

Whereas when the duplication is in the SAME file, #1, #2, and #3 can become very manageable cognitively.

Now the question changes to..

Is the cognitive load of dealing with the different special cases in a single de-duplicated method GREATER than simply leaving them in separate methods?

Often the answer is duplication WITHIN a file is less of a cognitive load.

Whereas duplication ACROSS files is a heavy cognitive load.

Minimizing cognitive load minimizes mistakes. And minimizes developer fatigue. Thus boosting productivity.

At least, that's my development philosophy, even though I've never seen it in a design pattern or a book.

It just seems to make sense.

I find it interesting that comments on these articles mainly discuss 1 aspect about it. But rarely this part:

> Don't get trapped by the sunk cost fallacy.

In my experience, yes, programmers are hesitant to throw out an abstraction. Why not work to change this, rather than telling people not to abstract?

I don't think it's a sunk cost fallacy. I think the hesitation is more for social reasons, often not wanting to do a big pull request that's going to be scrutinized.
"Big pull requests" that are unannounced are always problematic because who wants to be the person saying "all of this work you've done is wrong"?

In such situations, it's good to get buy-in from other people before attempting to do such a thing. Make a proposal for a big change and discuss it. There's still a chance that, in the implementation it doesn't work as nicely as believed initially, but at least now it's less likely that the idea will be rejected wholesale during code review.

sometimes it's better to copy and paste some code only to make each copy diverge more and more over time (somewhat like a starting template) as opposed to introduction an abstraction to generalize some slightly different behaviors only to use said abstraction twice.

this makes even more sense when the code will live on in different programs

there's a point when incurring the cognitive overhead costs of the abstraction become worthwhile, probably after the 3rd time. but my point is that it's also important to consider that the abstraction introduces some coupling between the parts of the code.

I find it easier to read long functions of code than jumping around in helper functions or abstractions. Especially if I am not familiar with the code base and don't know common functions by heart.
Sandi mentions this during a talk she gave on refactoring a few years ago. [0]

It’s a great little video for showing junior developers how a messy bit of code can be cleaned up with a few well chosen OOP patterns (and a set of unit tests to cover your ass).

[0] https://youtu.be/8bZh5LMaSmE

“Premature optimization is the root of all evil”