216 points · by soopurman · 5y ago · 233 comments
I’ve usually heard this phenomenon called “incidental duplication,” and it’s something I find myself teaching junior engineers about quite often.
There are a lot of situations where 3-5 lines of many methods follow basically the same pattern, and it can be aggravating to look at. “Don’t repeat yourself!” Right?
So you try to extract that boilerplate into a method, and it’s fine until the very next change. Then you need to start passing options and configuration into your helper method... and before long your helper method is extremely difficult to reason about, because it’s actually handling a dozen cases that are superficially similar but full of important differences in the details.
I encourage my devs to follow a rule of thumb: don’t extract repetitive code right away, try and build the feature you’re working on with the duplication in place first. Let the code go through a few evolutions and waves of change. Then one of two things are likely to happen:
(1) you find that the code doesn’t look so repetitive anymore,
or, (2) you hit a bug where you needed to make the same change to the boilerplate in six places and you missed one.
In scenario 1, you can sigh and say “yeah it turned out to be incidental duplication, it’s not bothering me anymore.” In scenario 2, it’s probably time for a careful refactoring to pull out the bits that have proven to be identical (and, importantly, must be identical across all of the instances of the code).
[1] https://news.ycombinator.com/reply?id=22022603&goto=item%3Fi...
When something like this is adopted, the average person will look at something then quickly throw up their hands and declare that they can't name it without really trying. Many things can be named well, but it takes 60 seconds of hard thought and focus to realize it.
IDataProcessor. And if you need the raw data it will be several layers deep in dataProcessor.data.data.data.
I misread that at first. At first I thought you were saying that there is no better abstraction than a bad abstraction. Gotta love the ambiguities in English.
On the other hand it is often possible to refactor and restructure code such that you no longer have to name something. Returning a closure rather than a value, or folding over a list, are two of my favourites approaches, since in many languages you then deal with the object symbolically, or implicitly through syntax, rather than explicitly or by named reference. Coroutines, continuations, and generators too.
You forgot the third most common case - 90% of those repeated methods will never have a bug and now you've got a code base that will start smelling bad and no one is going to want to work on it.
I agree with some of the things here, but allowing multiple places of repeated code unless there isn't a bug sounds like a terrible idea. Lot of these small methods will never have a bug and they'll continue to rot the codebase.
The former when something broke, I could just...fix it. And it would be fixed. Would other, similar situations, still be broken? Sure! And when those would be raised up we'd fix them too, and compare them with the other changes, and possible refactor. Fixing one bug = one bug less.
The latter? Oh God. Something is broken? We'd fix it. Aaaand, now there'd be two bugs. Fixing one bug = more bugs.
Perfectly balanced code, yes, fixing one bug = multiple bugs fixed. That's the goal. But you won't get it right if you do it pre-emptively. Which of those other two options would you prefer?
After you do something like that, tell me how much you love fixing bugs everywhere.
But the outcome that you're lambasting so rudely (really? "terrible idea" when we aren't even looking at code?) is still often the best outcome.
Some rotting, bugless, duplicated code is some of the easiest code to work with. It's the code you wish you had when you're debugging the complicated failing abstraction that GP wanted to avoid. The most damning thing you yourself could say about it is that it was taking up space.
In fact, you seem to be making the exact reverse argument of GP: that some duplicated, unabstracted, bugless code poses such a risk ("rot") that it's a "terrible idea" to not immediately merge it into one frankenabstraction.
When this happens in an argument, usually you both are imagining an absurd extreme that's opposite of the other's chosen extreme. And you actually are in agreement, as you'd both go "oh well yeah, if you go to that extreme, then I'd definitely agree with you."
If there is no bug, why would it continue to rot the codebase?
Later, the new use case would evolve and have some new requirements. Had we abstracted the functionality originally, we'd have to go back and make the abstraction handle both cases. As it was, we could just change the copy that needed to change, and know that we weren't going to break the other case.
This was also before the practice of automated unit testing was well understood and supported by development tools, so the motivation to "not risk breaking working code" was much stronger than maybe it is today.
In my experience, the biggest messes I’ve inherited were a result of not being DRY enough: the cases of incidental duplication I’ve run across have been comparatively easy to unwind.
This reminds me of Mike Acton's Three Big Lies of C++, specifically Lie 2: Code should model the world. [0]
> A chair is a chair, in real life. But in terms of data-transformations, in terms of what we do, these classes are really only superficially similar. In the context of a game, we have a Chair, a PhysicsChair, a StaticChair, a BreakableChair. These things are not at all similar. There's almost nothing that's the same between these contexts. How they're handled, how the data is managed, how the data is transformed, there's virtually nothing that's the same here, and yet the tendency would be because they share some world-modelling similarities, their similarities in the real world, they ought to be connected somehow in the code hierarchy, which is non-nonsensical. World-modelling leads to monolithic, unrelated data-structures and transforms. [...] You can't make a problem simpler than it is.
I feel like that comment either takes a very literal and naive analysis to the problem or fails to identify the objects being used.
Just because the word "chair" pops up in a few objects that does not mean they are supposed to be the same thing, and thus modeled as specialization of a common Chair class.
For example, PhysicsChair makes sense as a specialization of a physics-related class, not a Chair-related class. Breakable hair would also make sense as a specializationof a physics object, which might be comprised of multiple discrete elements or track damage to generate new particles when a threshold is reached. If we take the single responsibility principle seriously, it makes sense to have specialized physics and graphics classes that implement the functional requirements of handling a chair.
This by no means implies that class Chair should be a superclass of all these other cases, or even that it makes sense to even consider them to be related at all. A failure to identify the models and their functional relationships doesn't mean that your domain has to include relationships that don't really exist nor make sense.
You agree with his point that class hierarchies shouldn't necessary model reality.
> For example, PhysicsChair makes sense as a specialization of a physics-related class, not a Chair-related class.
Right, that's his point.
> A failure to identify the models and their functional relationships doesn't mean that your domain has to include relationships that don't really exist nor make sense.
Again, that's the point he's making. In terms of modelling the world, they're all just different kinds of chair, but that's doesn't mean you should model it that way in code, with object-oriented types.
https://en.wikipedia.org/wiki/Rule_of_three_(computer_progra...
Code that looks the same but is used for different purposes / has different meaning? Keep it separate. They may diverge in the future.
Code that truly means the same thing, but may or may not look the same? DRY it up, any variation is probably unintended and will surprise people later when A doesn't behave like B.
Once you start getting it you tend to go too far (everything is a nail when all you have is a hammer) and experience helps you learn to judge when to use it - but it's an invaluable tool and you need to use to get the experience - so I would suggest extract shared code by default - inline when it gets too complicated.
One good example of this is paths in makefiles. It's so much easier if you just make all the paths relative to the root of the project, but people have to either over-abstract or under-abstract everything or both.
$(CC) -o ../build/foo foo.o $(BARDIR)/bar.a ../bletch/bletch.o $(BAZLIB) etc..
why not just: $(CC) -o $ROOT/build/foo foo.o $ROOT/build/bar.a $ROOT/bletch/bletch.o $ROOT/baz/baz-2.0/bazlib.a
this goes for all sorts of things. Yes, you might build a directory from somewhere else or might, might might. But why not make it clear what you are doing, not unclear depending on what you might do?What if the flaw is not the initial deduplication, but the flaw was to continue to use it by adding additional responsibilities?
When I think of the incidental type, I think of things that just happen to be alike, a contrived example would be ENUM value that happens to be 3 used in different places ands that works because both happen to use 3.
That sounds great in theory, but how long is your evolution time and do you keep track of the changes in practice? I would assume a good evolution time is 3 to 6 month. I would say half the time I work on a story i face that decision. If you close 1 to 3 tickets a week you have to track a lot these decisions [1]. Now add that you work on a team of 5 and you have 5 engineering teams overall.. it seems to me that this approach does not scale.
[1] granted not all tickets will be new decisions in new places of the coffee base and you do come across some of your old changes and do the actual evolution.
Write Everything Twice, then DRY it later.
Locality encompasses multiple concepts, one of which is what you mention. Another is the ability to look at any section of code and understand exactly what it does without having to dig through chains of abstractions.
The implication is that locality results in more LOC, but a more tractable codebase, especially as it gets larger and more complex and more difficult for engineers to hold in their head.
In functional languages, where every statement is a function, this is often easier.
By the way the copy-pasta code is very resilient: a bug introduced in one place cannot spread, because the other code is duplicated and old.
Instead if you have too much condensed code, you end up with complex method which are difficult to maintain, because you have a huge "coverage land of code", and you get scared when you need to change it.
Code blocks that look to be syntactically the same are the lowest expression of "this might be the same piece of knowledge" insofar as they express knowledge about "how to do X", but the key is identifying the knowledge that is duplicated and working from there. Sometimes it comes out that the "duplication" is something like "this is a for loop iterating over the elements of this list in this field in this object" and that is the kind of code block that contains very little knowledge in terms of our system. But supposing that that list had a special structure (ie, maybe we've parsed text into tokens and have information about whitespace, punctuation, etc in that list) and we start to notice we're repeating code to iterate over elements of the list and ignore the whitespace, punctuation elements in it, then we've got a piece of knowledge worth DRYing out given that all the clients now need to know what whitespace & punctuation look like even when they'd like to filter them out.
It's worth pointing out that DRYing out something isn't necessarily "abstracting", it is more like consolidating knowledge into one place.
The most fun bug I've encountered as a web developer is of this category. Two pages, both check for a logged-in user and redirects to the other if found or not found, respectively. The bug was a subtle difference in how these were calculated, the details of which are unfortunately lost to the sands of time. The end result was that if you sat on one of the pages and waited for your user session to time out, you'd get stuck in a redirect loop between the "logged in" and "please log in" versions of the page.
Anyhow, the point of this is that when you calculate the same fact two different ways, you will occasionally build something that makes an unwarranted assumption that because it's the "same fact" you wind up with the same answer. This is an entire category of easily missed and often subtle bugs.
Especially if you "overly reduce" your knowledge. If your common recipe is "do A, B, C, D, E" and you reduce that to just "do X," for instance.
I've seen this often turn into "now, instead of the knowledge being repeated in several places, it's hidden in one place and only one person knows it." Everybody else just relies on the library doing its magic, and when someone needs to do something differently, they have this huge mountain to climb to figure out how to modify the code to also do "J" for certain cases without breaking everyone else.
Size matters, and depending of the system size we’re dealing with it will have a significant impact on what approach we take. Or how we handle documentation for instance.
When we think about the knowledge of "how to do something" that's where things can get confusing. 9/10 times I'd say that right move is to look for common assumptions or facts. IE it isn't just "doing something" that is important, but the assumptions made in the process of doing it:
As an example, consider finding the average word length in some piece of text. We might start writing that feature like:
def count_words(text: str) -> int:
return len(text.split(' '))
def average_word_length(text: str) -> int:
num_words = count_words(text)
word_lengths = []
for word in text.split(' '):
word_lengths.append(len(word))
return sum(word_lengths) / num_words
then the piece of knowledge they share is "what a word is" and the DRY refactoring would pull out that piece of knowledge into its own function def words(text: str) -> List[str]:
return text.split(' ')
that might be code you write when starting to write a feature and that's the kind of "ding ding ding there's common knowledge here" that should guide refactoring. The system has a concept of a "word" that we've introduced and its important that knowledge about "what a word is" in one place. For DRY things it frequently doesn't make any sense for there to be multiple statements of "what a word is" where the system wants to use the same concept.Kind of orthogonal to this is abstraction where the focus is on "usefulness" and that is where 100% you can abstract incorrectly, prematurely, get screwed over by requirement changes, write a library that hides everything and makes people angry. The example you provide seems more like an error in abstraction where things that should be close together are too far apart in the system (ie, some "fact" is hidden away and another part of the system wants to know it), but the consolidation and DRYing of those facts, I'd argue, is a lot easier once we've figured out how to identify them
In my example, it's less a "core piece of knowledge" that people are trying to DRY, and more just a "common sequence." Someone sees a bunch of different places where we have a sequence of calls like A, B, C, D.. and says "oh this is a shared method I can extract" even if there's plenty of ways that in the future you might want to do A, B, C, E without D. And so then you pass in a bool, than another one, and you have a centralized mess...
There's a standard library to connect to databases. There's a huge hierarchy setup just to start an app running.
All of these super dry infrastructure changes have, unfortunately, come with a huge cost. We are still stuck on ubuntu 14.04 because our super dry puppet framework we invented can't be ported to puppet 6.
We are stuck talking to MS-SQL, because our super dry database connection management library can't handle establishing other database interactions.
We are still stuck on Tomcat 7 because our super dry Jersey libraries don't work with newer versions of Jersey (which has locked us into older versions of tomcat!).
Consolidation is a decent goal, but it really needs to be measured. For me, it is FAR more important to consolidate on the how to do things and not the what does things. In otherwords, rather than making an "elasticsearch connection library" specify "This environment variable is the elasticsearch host/credentials" and let the apps move from there.
That's because, when it comes right down to it, configuration code is super easy to write and it really doesn't matter if it's duplicated. You want your libraries consolidating knowledge to be for things that are easy to get wrong (such as checking who is currently logged in or how to authenticate).
I think we're in agreement here. Config is the most basic kind of knowledge because when something wants to know about the elastic credentials,it almost never makes sense to have it in two places if those two places are supposed to be the same thing.
How to actually connect to elastic -- that's the part that is more iffy. If there is some knowledge we've added there, then it makes sense to DRY it up, but the knowledge of "this is how you pass credentials to this elastic search client" isn't the kind of system knowledge we care about. If, for example, there were some kind of parameters that we had to set on each connection and we claimed it as a piece of knowledge that all of our connections to this service are of this specific TYPE and have these specific parameters, then we've started to add some additional systemic knowledge that might need to get consolidated.If someone were to start working on a piece of code and I feel the need to tell them "Don't forget about X" then that is the kind of situation where DRY comes into play. If it's just a vanilla connection to a database and we don't care about the connections made, then I do given't think we have a violation of DRY given that there isn't an important piece of knowledge that's repeated.
At some point, especially when we pay too much attention to copy-pasted code, we end up abstracting. Abstracting is hard, more general, very difficult to do right, almost always done to early. DRYing out knowledge is easier and almost always improves things.
> The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"
(from wikipedia)
It feels like the name really took over the intention and it became about code repetition instead of knowledge repetition.
I find the vocabulary of DDD to have more explanatory power. Especially with people who don’t grok the difference between removing repetition and consolidating models.
I think repetition is a symptom that a code base may be afflicted with interwoven domains, but the existence of repetition is not sufficient for the diagnosis, IMO.
Yes, I've dealt with systems that had bad abstractions. And I've also dealt with systems where knowledge of highly nameable things - like how to authenticate a user, or how to connect to a database, how to obtain a token to the same API server - wasn't centralized.
Systems of the first kind are certainly bad. It takes a lot of time to understand before you can get ahead and start refactoring. If your organization had low code review discipline at any point, abstractions often become hard to refactor with time, since some developers don't understand the abstractions, and instead of fixing them, just work around them with thread locals or lots of branches.
But systems of the second kind are much worse. Here what happens is that duplicated knowledge invariably diverges with time. It can be developers fix a bug in one place and forget the other, or adding a certain feature in one place and another one the other place. Over time, each implementation of the knowledge has it own unique behavior and bugs, and some parts of the sprawling code base grow to depend on a certain behavior. Or perhaps your code doesn't, but you have other services in other part of the company consuming your API that do and you just have no idea if they rely upon the implementation difference or not.
DRY reduces the number of potential lose ends when you update your code.
If it's > 1, you have a moisture problem!
Of course, the answer to that question can change over time, and one has to combine or duplicate accordingly. This also serves to document the intent that “yes, these two occurrences are expected to evolve identically”, or “no, these two occurrences are expected to evolve independently, even though they currently happen to look the same”.
The article is correct though that there is a trade-off in terms of the complexity created by the abstraction, and in how important the “common truth” is. Sometimes a source comment pointing out the dependency is better than introducing a nontrivial abstraction.
The book “A Philosophy of Software Design” argues that there are two sources of complexity in software: dependencies and obscurity. Combining two similar pieces of logic into one can reduce dependencies (of one having to be changed when the other is changed), but can increase obscurity due to the added abstraction. If the combining was done for the wrong reasons (the two occurrences actually need to evolve independently), then the dependencies are increased instead of reduced.
I have found that starting with duplication is by far the easiest and most flexible way to work through problem domains that are complex. Once you have a really good grasp of the modeling, then you can iterate and decide on normalization where appropriate.
Thinking about this from an analytical perspective - If you build your application with duplication by default (i.e. define a domain model for each logical use case/scenario), then you will have an excellent analysis already in front of you regarding which business types should be normalized and which ones might be a little bit trickier to make common. Many times it is impossible to fully explore a problem domain until you have already written software against its entire extent.
On the other hand, if you realise your abstraction was bad, duplicating a function is always trivial.
I've seen code copy-pasted and slightly modified over a dozen times, sometimes without even eliminating dead code! Copying a function or even a whole file is fine if you actually take a moment to consider whether it needs refactoring or not, but more often than not people will just copy and bash at the code until things work without actually making a conscious choice to duplicate code over refactoring.
I believe DRY was coined in Programming Pearls, and probably none of the examples in the article are instances of DRY.
DRY is about knowledge/requirements, not similar code. It is about ensuring that a given requirement is not duplicated in multiple places in the code. It is not about similar looking code, which often involves differing requirements but just happen to be coded similarly. The latter leads to coupling if you unify it into one piece of code.
My favourite block of "DRY" code was a method that had a triple nested loop (for all object A, for all objects A.B, for all objects B.C) with a bunch of flags (like 15 different bools, ints, dates and arrays) that changed the ORM filters for A, for A->B, for B->C, and then changed what operations were done on A, B, C. Basically, at the end, the only similarity was the foreach part. The comment on the block of code had "Keep this loop together for DRY", as if they knew this was going wrong but not sure why. It ended up being 3 or 4 much simpler methods, based as you say, on requirements NOT code "shape".
The problem is that when people believe this is DRY, they then tend to oppose the "real" DRY as well.
Likely we'll have to give another name to the "real" DRY principle. In general, I've always felt that catchy names/acronyms are a bad idea for anything (e.g. free software, open source, pro-life/choice, etc). Almost all of them end up being used in ways that were differ from the original intent.
The example I always come back to is auth. If you're doing the same thing like "parse a cookie header, get the session, make a DB connection, look up the session info, etc. etc.", consider how you could architect the layers of your application using a mental model that people would find easy to reason about. That might be some OO, middleware, or even a macro, but the point is that it's thought about, designed, engineered, and documented.
The reason helpers are more prevalent than thoughtful architecture is that humans are a lot better at prioritizing the short term "I improved it" fix from factoring into helpers over doing the long term work of architecture. If you want to change this, it starts with cultural values that prioritize long term sustainability.
I really like to see DRY code, but if you have to make a helper function that takes a bunch of parameters with a bunch of conditionals to something slightly different, you might be better off just sticking the specific logic you need in each place.
The worst case of copy-pasta I saw in a codebase I came into was a function that was 1000 lines long, duplicated 3 times with < 10 lines of it different for each copy. That's a classic case for DRY to be applied.
> Dependencies (coupling) is an important concern to address, but it's only 1 of 4 criteria that I consider and it's not the most important one. I try to optimize my code around reducing state, coupling, complexity and code, in that order. I'm willing to add increased coupling if it makes my code more stateless. I'm willing to make it more complex if it reduces coupling. And I'm willing to duplicate code if it makes the code less complex. Only if it doesn't increase state, coupling or complexity do I dedup code.
> The reason I put stateless code as the highest priority is it's the easiest to reason about. Stateless logic functions the same whether run normally, in parallel or distributed. It's the easiest to test, since it requires very little setup code. And it's the easiest to scale up, since you just run another copy of it. Once you introduce state, your life gets significantly harder.
> I think the reason that novice programmers optimize around code reduction is that it's the easiest of the 4 to spot. The other 3 are much more subtle and subjective and so will require greater experience to spot. But learning those priorities, in that order, has made me a significantly better developer.
Dan Abramov also has a good talk about this [2].
I discovered that immutability in functional programming made it far easier to reason about state - something goes in, and you know exactly what comes out. No verbose checking logic, no bugs because something wasn’t set that should have been.
I’d personally switch coupling and complexity (though it really depends on your definition of the latter). Coupling is usually much less of a problem than you expect it to be, and is easier to identify/rectify in retrospect.
At least, I've yet to see one which isn't.
For instance, structured programming (building code out of blocks with structured control flow rather than a pile of gotos) was victorious in the 1970s. Nowadays nobody considers the tradeoffs of using if-then-else versus gotos; structured code is the automatic choice.
Self-modifying code was very popular in the 1950s (since it was the only way to get many things done), but essentially nobody uses it now.
Modularity is another victorious principle of software development, winning out over big blobs of code with global variables.
Using a stack for subroutine calls used to have tradeoffs, but now nobody would consider an alternative.
Looking at the long perspective, there is real progress in software development (although slower than I'd hope).
...which proves that it is a tradeoff. Just one where the local minimum currently is at one end of the domain due to context (e.g. ROM size limitations) having evolved.
Still, there's a certain sense of aesthetic beauty that I just can't derive from Go, and why I kind of hate working in it. There's lots of things about Java and OO that I don't love, but reading a perfectly factored Java code base can be just beautiful. Mostly due to good choice of interfaces.
Now, those code bases might be rare and not worth the lift of a million bad abstractions. I'd probably agree at this point, but still, I find it odd that most Go code bases just feel dirty and thrown together to me. Hacking stuff together in a mostly procedural language with good deployment story is probably the right way to write for-profit code, but I'm not sure I love it.
Dan Abramov also wrote on this fairly recently: https://overreacted.io/the-wet-codebase/
Even when you know what you're doing. there's good refactoring[1] and bad refactoring[2].
[1] https://osdn.net/projects/joypy/scm/git/Thun/commits/aa43eb6... This is a good clean bit of refactoring: it makes the branch symmetrical and lets you move code to a common post-branch step.
[2] https://github.com/calroc/HulloWurld/blob/master/Hullo.html#... This is a terrible function that, while it abstracts the core of the two following functions well, makes the system harder to understand. In other words, the three factored functions are less desirable than the original pair of functions despite their redundancy, because the original functions were easy to understand and the new factored helper funtion is inscrutable. Context counts.
(emphasis mine)
I think this is the crucial part. DRY works fine and in fact arises naturally if the code is well factored to isolate areas of commonality - as the author points out though, this is very difficult to do and I think that's the core problem.
Another anecdote on DRY: I'm currently refactoring two interrelated systems that share a single function, and very horrible bad things happen if the systems disagree on the return value of that function. However sharing the same code is more complex than duplicating it and this has a nontrivial impact on how the systems are distributed. So today I'm undoing the original work I did to make it DRY - turns out that sometimes, you need to copy/paste.
I wonder how much of DRY's popularity is due to the catchy name. One can say "this needs to be DRYed up" (verb), or "this code is really DRY" (adjective), or "I appreciate the DRYness of this code" (noun). The opposite of DRY: "wet", of course. Being a homophone of an existing word that is both a noun and adjective, and that has an obvious antonym really lends itself to usage.
can refer to the distance a car has traveled over time at a fixed speed with a starting point as well as the cost of ordering a certain quantity of an item with a fixed shipping cost
that's my best attempt at an example
DRY is literally impossible. If something has to be performed or evaluated two or more times, and you factor that out under a definition, you still have to invoke the definition multiple times. I.e. you are still repeating yourself, just using an abbreviation.
What you are doing is called "compression". Classic data compression algorithms like LZ77 work by abbreviating.
"LZ77 algorithms achieve compression by replacing repeated occurrences of data with references to a single copy of that data existing earlier in the uncompressed data stream. " - Wikipedia
Outside of alcoholic drinks, that's the ultimate DRY.
Thus, the argument against DRY is obvious: it's a form of compression, and excessive compression destroys readability: or else we would all be able to read source code that has been put through LZ77.
Only mild compression improves readability. Mild compression improves readability largely because it's easier to see that two brief invocations of a definition are exactly the same, than to see that two repetitions of a code block are exactly the same. When we see that two code blocks are exactly the same, we don't have to understand them separately.
Basically, brainless repetition and verbosity hinders readability, as does dense, thorough compression. One extreme might be represented by reams of Java boilerplate; the other by IOCCC entries.
If you have 2-3 problems that kinda look similar, you could wrap them up in a function, with some arguments for variation, and pat yourself on the back for DRYing it up. But after some time you get a 4th or a 5th occurrence of the same problem, all slightly different.
Obviously you could create a mess of things by abstracting away what are different problems, but I don’t think “just don’t do abstractions until its really obvious” is a solution, to me it sounds more like giving up. And worse you can end up with piles of code that look kinda similar but with small differences here and there, really hard for new comers to parse and reason about.
What I think is a better approach is to try to come up with abstraction “layers” - smaller pieces of blocks that would make the same problem trivial to solve.
You got your 2-3 pieces of code that look kinda similar. OK do they have smaller parts that its dead obvious that are similar? Abstract away those, now you are left with parts you might be happy to leave as is, don’t need one big function for all of it.
And sure this has pitfalls too, but a good way to test any abstraction is to see how leaky it is. Can I successfully understand and reason about whats going on by just reading the function names / descriptions / types? Does it compose? Yes? Awesome now you have a layer you can build your business logic on. No? Well either change it or get rid of the abstraction until you can come up with a better one.
> The main problem with repeating a code chunk is that if a bug is found, there is more than one place where it needs to be fixed.
No, the main problem is that reading repeated code adds cognitive load for reader. Also, when you copy-paste the code you should copy-paste its tests too, and that leads to CI/CD resource wasting.
> The alternative to copy-pasting the code is usually to put it in a function (or procedure, or a subroutine, depending on the language), and call it. This means that when reading through the original caller, it is less clear what the code does.
If the function and local variables all has clear naming and function does not mutate passed variables (which otherwise should be clearly implied by it's name) - you never need to step into it while debugging and just save a bit of time while reading the code.
So, the takeaway here is: the code is written for humans, not computers. The idea of clean code is ease of reading and understanding. That's what DRY is for.
Interesting to see all the comments here that make it seem obvious that "fanatic DRY" is bad. Historically, there was a wave of OO love where a lot of people went crazy with wrapping every program element in deep layered class hierarchies. DRY (and OAOO, YAGNI etc) was maybe a backlash to that, and some go too far with it. Now we all seem in love with "leave the redundancy in the code", which is another backlash. What's the next backlash? Maybe we'll finally focus on how to balance these factors rather than seeing some extreme as the silver bullet?
> when reading through the original caller, it is less clear what the code does
In my experience it is usually clearer, if the function has an even remotely appropriate name. And unless you are coding with notepad.exe, toggling between caller and callee is pretty trivial.
> When you move this code to a function as a part of a straightforward DRY refactoring, this means that now a function is mutating its parameters.
Whether that matters depends a lot on the language.
And anyway it seems like the main problem in code like that is that the function is inappropriately mutating state outside of itself in a surprising way, which might be a problem separate from dryness.
"Loss of Locality" does strike me as reasonable argument against code that is too dehydrated though. Maybe somebody else can make some better supporting claims for it?
Also, some of the negatives of not-repeating-yourself are not general:
* Often your repetitions themselves are localized.
* Sometimes, you can generalize your code even _more_, to factor out the non-general parts, so that you end up with a generalization of the scheme/mechanism, applied with specific details.
* You can limit your DRY to within your scope of ownership, i.e. have module-local / unit-local utility constructs. Then, only if you agree with others on the generalization, do yu surrender ownership.
etc.
Yes. I am trying to popularize the term Locality of Behavior (LoB) to capture this software concept:
https://htmx.org/essays/locality-of-behaviour/
There are always trade-offs in development, and the older you get the more you value clarity of code over other potential concers, and locality of behaviour is a big part of that.
I can't find the original source (it was somewhere on medium) but this graph struck me:
"This means that when reading through the original caller, it is less clear what the code does."
This is false - if you have a clear service and method name, with clear, properly-typed params, it SAVES time, because unless it's broken, it's a SHORT invocation that abstracts the details.
"the function might have some surprising semantics. For example, mutating contents of local variables is sensible in code."
Pure functions are the only "apply everywhere" part of the functional programming paradigm. Side effects are just as painful in .NET and Java as they are elsewhere.
"Overgeneralized code"
SRP let's you identify this fairly easily. As an example, I just tried to abstract away "Edit" and "SuggestEdits" in the same controller to stay DRY, but then realized it violates SRP.
"Each modification of the "common" function now requires testing all of its callers. In some situations, this can be subtly non-trivial."
Much less painful then knowing you have to change it in multiple places AND THEN checking the code. Just doesn't apply.
"When each of those code segments were repeated, ownership and responsibility were trivial. Whoever owned the surrounding code also owned the repeated segment."
The team owns the code. At worst, the lead owns the code. Bad excuse.
Feels like a dramatic contrarian piece to me. As mentioned, SRP and DRY are the only two things that allow our team to keep churning without significant tech debt. That, and avoidance of magic strings.
These 3 things are probably 80% of clean code.
Edit: Oh, and keeping methods to 5 lines or less, except in genuinely extreme, rare cases. Of course that's theoretically under "SRP and abstraction", but you know..
Edit 2: The single source of truth comment is on point as well. There was a rule when Python was designed "There should be ONE, and ideally ONLY one way of doing things." This is extremely important to writing good code and on-boarding people onto your project.
This confuses me. Extreme, rare cases? Don't get me wrong, I code Lisp as much as anyone and love keeping my functions short and simple, but not going above 5 lines (esp. in Java or .NET) is masochistic.
By that metric, an if in Java takes up 60% of a function's real-estate, a local variable 20%, and a try-catch is your maximum complexity.
try
{
_legacyCandidateRepo.SaveWithIncrementalBackoff(candidate);
}
catch (Exception exc)
{
HandleException(exc);
}This way, the code is extremely readable, especially if you can easily "Go to definition" in a service, and the file this try-catch isn't 200 lines long.
Also, try-catch is generally an anti-pattern. It should only occur when you genuinely have no way whatsoever to prevent the exception, as such, it will be pretty rare.
Again, it does happen, for example we have an unstable legacy db we hit that we don't have access to, but it should be fixed asap.
Tbh, this is a constant argument between our juniors and I. They want to write 15 line methods, but I have found that they don't want to debug it.
It's constantly them building quickly on top of my code and then me having to fix theirs because they get frustrated debugging their own code.
> try-catch is generally an anti-pattern.
Exceptions are a very useful part of the language if you use them right (to divert code flow in predictable ways in unpredictable scenarios), although I agree it can be easy to go wrong.
Regarding your juniors, that seems more of a problem of skill or determination than anything. Debugging in Java is relaxing, it has stack traces, a debugger, a nice IDE, no segfaults.. a 15 line function should not be an obstacle. I would even prefer to have more of the code on the screen sometimes so I can get the implementation details in my head .
DRY is yet another tool. Skilled hands will be able to judge when to use it and when to keep a little duplication to preserve simplicity and legibility.
I see frequently developers going to great lengths to avoid duplication of couple of lines of code. In the process, they create much more new code, use half a dozen patterns and make the code more difficult to understand. That's not the ultimate goal.
The ultimate goal is always to keep the code produce more value and this usually is best served by simpler and more maintainable code.
The latter tends to happen for business logic: suddenly requirements change and your beautiful "abstraction" falls like a castle of cards.
In it she also offers some great advice on what to do if you find yourself stuck with a bad abstraction.
("Avoid Hasty Abstractions")