r/programming • u/ScaredOfMyRawr • Mar 09 '23
A case for selectively applying DRY, sometimes it's good to repeat yourself
https://medium.com/better-programming/a-case-against-relying-solely-on-dry-16dd712e422b
894
Upvotes
282
u/flerchin Mar 09 '23
Go Ahead Repeat Yourself. GARY
321
u/rzwitserloot Mar 09 '23
There are 2 problems with DRY. These are usually of a lesser magnitude than the problems that repeating yourself causes, so please don't construe this as 'this moron is advocating for copy/pasting your code all over the place'. This post seems to drive at one of them but I'm not sure they're saying it clearly.
privateor_x, - whatever your language calls 'you may assume this code is only used by very few, even 1, caller') calls, especially when the aim is to fully grok all of the code involved in a process. If the code instead flows through paths that are also busied by many other things, then there's an entwining of those things with the process you want to understand.In some ways #2 boils down to #1 - if truly the jobs really are entwined then trying to grok all code underlying a process has to involve understanding the related parts too, even if (especially if) you are not immediately aware they even are related. But, if truly those things aren't related, your attempt to fix DRY just complicated things, and is possibly (probably) failing at making your code simpler to understand and maintain (which, surely, is the point, no?)
Determining whether it's a good idea to abstract away some task to avoid code duplication requires domain knowledge and quite a bit of coding experience, therefore, a tool that tries to find violations can, at best, recommend that you should perhaps consider a thing, and if there is no way to tell such a tool that you have considered it, and 'remove DRY violation does not apply' cannot be configured in a way that survives source control, it's a shit tool that should not be used. Unfortunately, quite a few DRY violation scanners (and some code reviewers, who do an apt impression of a DRY violation scanner in meat popsicle form) simply do not acknowledge that, from time to time, a seeming DRY violation is best left untouched. That's unfortunate; if not for that oversight I might have wanted to use them.
61
u/ryanhollister Mar 09 '23
People talk about pre-mature optimization, I am a firm believer that pre-mature abstraction is even worse. You build an abstraction before you really know its consumers, then that leads to very leaky abstractions because the consumers actually end up needing different things.
28
u/Nephelophyte Mar 09 '23
I see a lot of acronyms but I think this saying really sums it up for me:
"The only thing worse than duplication is the wrong abstraction"
102
u/EvenInfluence9 Mar 09 '23
WET. Write everything twice
40
u/CodyEngel Mar 09 '23
You should repeat yourself. Avoid Hasty Abstractions and build those abstractions once it’s clear what those abstractions should be. Copy paste is far less destructive than 100 uses of a poorly defined abstraction.
8
u/Amuro_Ray Mar 09 '23
Only time I've really been annoyed by DRY was when someone brings up in a code review the code is used in a unrelated place and asks for the section to be moved to a miscellaneous module full of independent functions to avoid repetition.
8
u/abeuscher Mar 09 '23
Some tool my brother was friends with got out of a 3 month bootcamp a few years ago and immediately thought he was like an elite programmer. It was super cringey. His resume had this sentence at the top:
I write DRY code. I repeat, I write DRY code.
7
u/krucabomba Mar 09 '23
I was actually surprised someone did homework and read Andrew Hunt's approach.
GJ.
12
u/IAmTheKingOfSpain Mar 09 '23
Having to update all the callsites to make the typechecker happy (because you added an extra parameter to the method) actually seems like a feature to me. Otherwise, you're just relying on searching and memory to update all the publishers to have the extra context. If you're defining context that all events should have, then I think it's pretty clear that you DO want a helper function that's used in all the publishers.
For example, if the version numbers in this example are supposed to be bumped at the same time (unclear from the example), then not having this in a helper method looks like a disaster to me.
All of this doesn't mean all the context has to be supplied in helper methods, though!
11
u/ProgramTheWorld Mar 09 '23
In the article’s example that won’t be the case. All dependents of the common helper class aren’t coupled together as they do not interact with each other.
When you’re making a common helper class, you are declaring that they are the same business logic, now and in the future. If they aren’t the same logic because their implementations might diverge in the future, then there’s no duplication going on because they are in fact not the same, even though the implementation might look the same at this moment.
4
u/somebodddy Mar 09 '23
I'm a firm believer that the DRY principle is made completely redundant by the SSoT principle. Any violation of DRY that really is a bad duplication also violates SSoT, while violations of DRY that are not actually bad code and that should remain "duplicated" do not violate SSoT. SSoT is a strictly superior principle.
4
u/am0x Mar 09 '23
The problem with all this stuff is that some people think a particular way to do something in programming is the only way. But different systems, different languages, different frameworks, different paradigms, different scopes, etc. all require a specific best choice. It won’t always be the same.
Shitty or inexperienced devs don’t think this way.
Yea, I’ve suggested a Wordpress site or 2 to clients. It made them happy and we made money.
4
u/Zeno343 Mar 10 '23 edited Mar 10 '23
I've found a pretty practical approach for my personal projects that involves two alternating phases:
The first phase is to write your new feature at the level of the executable. You are ONLY allowed to touch the file that your main() function lives in, using the tools from your library. You aren't allowed to make changes to the library at all, you must implement this new feature as helper functions to your main(), and you aren't allowed to think about abstracting anything from those functions at all. Just sprint to a working implementation of the new feature and allow yourself to do it in the naive, "hacky" way. Repeat yourself all over the place, who cares, just get it done. Give yourself permission to let go of large-scale concerns entirely and write garbage code to that end.
Second phase, you read over that new code in the context of your existing design and refactor your library and executable to bring that new feature's functionality into the library in a sensible, better way. Don't aim for perfection at this stage either. It doesn't have to be perfect at that point, and you are allowed to choose abstractions only on the basis of the next feature you have planned, no further than that.
It can feel a little short-sighted and "gardeny", especially if you are an "architecture" heavy sort of engineer, but I've found it to be a simple and very effective method for my own work. It solves the issue that a lot of organizations have with de-prioritizing tech debt, since the second phase is basically just a "fix the tech debt" phase.
Final edit to fix some typos and add: Once I stumbled onto this idea from other sources and gave it a formal process, it felt a little odd as I was used to dealing with the end product and the library in tandem, and I had concerns that I would hamper long-term planning at the expense of feature velocity, but I've found that concern to not be borne out in the results at all. Sometimes my refactor phase is larger and affects more of the library code than other refactors, and sometimes bending the existing code into a new feature without touching the library can be tricky, but I find that the long term considerations sort of work themselves out gradually as each phase drives discovery of problems faster than alternative approaches, and the library gradually approaches a cohesive, well considered design by itself as the sediment of each new feature settles into bedrock with each pass.
15
u/okawei Mar 09 '23
WET is better, "write everything twice", if you write something twice and you need it a third time then you should consider abstraction
13
u/ctheune Mar 09 '23
An important part for me is doing bottom-up (or evolving) design. In that case I try to avoid any deduplication of (code) patterns unless I have at least 4 or 5 incarnations. Otherwise you end up extrapolating for future use cases from too few data points and doing multiple rounds of refactorings typically makes it harder to see the patterns clearly if they have already been muddled by DRY.
I typically catch young developers trying to apply DRY on the second instance of something and have to make them breath real slow and endure actually repeating themselves for 3-4 times to end up with a better picture.
3
u/nebbly Mar 09 '23
rule of three
3
u/loopzle Mar 09 '23
DRY is useful but the phrase isn't specific enough. I like to say "don't repeat your business logic" so... DRYBL?
I've seen bad code in the name of DRY with developers scared to repeat properties in separate classes. Surely a concept should only have one representation otherwise it's repeated! Then there's a bunch of null properties flying around and the repetition of logic is then just seen as unavoidable because of the code style.
The real aim is to avoid repeating business logic because that's where mistakes happen. For example:
Make as many representations of data as you like. Some without certain fields, some with extra fields, some just for serialisation, any use-case you like. Just try to minimize the repetition of logic.
Also, remember, it's a guideline. If it really is better for you to repeat some logic somewhere to get it working, do it and add a helpful comment... maybe a nice reference code in both locations so everyone can search it.
3
u/jbrains Mar 09 '23
The point of DRY is to build sensitivity to the risks of duplication, which seems not to happen spontaneously for most programmers.
Don't turn mind off. Always design mindfully, which also means selectively.
Even so, when in doubt and you see three copies of something, try removing duplication. You'll probably learn something helpful. That's DRY.
3
u/Neophyte- Mar 09 '23
i think this is especially so for microservices, the setup for xyz tooling may not be identical per service
5
u/mindbleach Mar 09 '23
'Rule-of-thumb mantra isn't universal standard for Good Code,' says Medium article written by Lt Col Obvious.
Congrats on that promotion.
4
u/3MU6quo0pC7du5YPBGBI Mar 09 '23 edited Mar 09 '23
There's never a time you shouldn't use DRY.
Just, sometimes, it means Do Repeat Yourself.
2
u/Inside_Dimension5308 Mar 09 '23
Actually we don't need to be strict if we are trying to create modules which can diverge in terms of logic at some point of time. So, right now they may look duplicate but what about the future.
6
u/m15otw Mar 09 '23
Good naming also helps. If your function just filters items out of a collection, call it
filter(), notexcludeNonButterflies(), because one can clearly be reused where the other can't (clearly), and absolutely shouldn't be without renaming.Admittedly, in the context of Python and duck typing, I write generically useful functions more often than normal, by accident, so maybe this rule doesn't work as well in statically typed languages with onerous generics boilerplate.
3
u/poloppoyop Mar 09 '23
Simple heuristic:
First time you have to code something, write it.
Second time, copy and paste.
Third time is when you can think about refactoring.
1
u/Ykieks Mar 09 '23
I prefer as a rule the following phrase: repeat, not copy-paste
1
u/ILikeChangingMyMind Mar 09 '23
I still think DRY is a good principle in normal code, but for test code I've always preferred DAMP not DRY.
1
u/clichekiller Mar 09 '23
I generally subscribe to the belief that all principles should be selectively applied after judicious thought. Following any paradigm blindly leads to cargo culting. It’s important to always engage your critical thinking. About the only principles I always adhere to is avoid premature optimization, and YAGNI. Oh, and always offer up a choice line of code to the patron saint of yak shaving.
1
u/dariusj18 Mar 09 '23
I can't stay dry because it takes me too long to think of a name for the abstraction.
1
u/kking254 Mar 09 '23
Repeat yourself when the repetition carries information.
1
u/spacezombiejesus Mar 10 '23
Blanket statements and generalisations are all bad. Some are better than others.
1
u/neumaticc Mar 10 '23
is the picture of candles
who died???/s
1
u/SayMyVagina Mar 10 '23
Especially when you can manipulate a data in one or ow lines with functional calls. I've banged my head against a wall with how young devs structure their functions. Make a whole function for a bunch of lines and only call it once arbitrarily breaking up their program flow. Wild.
1
u/squirtle_grool Mar 10 '23
Making a "Helper" is dumb, as the name Helper adds zero context. DRY, and add a CommonContexts scope including a DefaultContext which is this one.
I don't believe in blindly applying DRY but this is just a bad example.
1
u/sabrinajestar Mar 10 '23
It kind of balances against KISS. If you have to make it really convoluted to avoid repeating yourself, or refactor bunches of code, etc., it's probably not really worth the effort.
1
u/R34ct0rX99 Mar 10 '23
Sometimes it’s ok. If forcing dry causes a wrong abstraction, that is worse than repeating yourself
1
u/sarhoshamiral Mar 10 '23
I get their point but the example is really a bad one because there could actually be great value in having a helper method if location context is handled centrally as well.
It all depends on context ultimately and finding the right approach for the current project.
1
u/cwalk Mar 10 '23
"Everything should be made as simple as possible, but no simpler". Keep DRY within reason.
1
u/embair Mar 10 '23
I always ask myself this: Does the code in both places have the same reasons to change in the future?
1
u/NotMyRealNameObv Mar 10 '23
I keep seeing people extracting common code in test cases at work:
For some reason, when I extraction and abstract common code, I am told that I need to write tests for it. But I never hear anyone suggesting that tests should be written for
doTestabove...1
u/david-song Mar 10 '23
If you need to construct a location context so your order placed event publisher and your item viewed event publisher can publish order placed and item viewed events, then moving the location context creation logic to a shared location context helper is more of the wrong kind of Kafka. KISS, and the DRY will sort itself out.
1
u/angch Mar 10 '23
A little copying is better than a little dependency.
https://go-proverbs.github.io/
1
u/SquishTheProgrammer Mar 10 '23
I think it’s ok to repeat simple methods in order to prevent having to add another project and create a new dependency. Also, all these comments has me thinking no one on here writes tests. If you have tests that cover your code when you make a change and a test fails you know what to fix (this assumes you’re writing good tests and actually checking the output). I hate writing tests but they’ve saved me enough times that I know it’s worth it.
TLDR: Not saying you shouldn’t use DRY as much as possible but it’s ok in some cases and if it’s covered by tests you’ll probably be fine.
1
u/Tarl2323 Mar 10 '23
The time to apply DRY is when it makes code difficult to read and reduces errors.
I work in games and I can't tell you the amount of times I've had pages and pages of copy-pasta code for stuff like configurations.
Then we need to change one thing...like a color of a button, and then it takes ages and requires tons of testing since you gotta change that color in 400 different lines.
At that point yeah, you delete the 40 blocks of repetitive code and write a fucking abstraction lol.
1
u/Other_Goat_9381 Mar 10 '23
I'm not entirely convinced that there's an issue here. Assuming that you genuinely want both functions to always do the same thing, it would be extremely simple to just wrap your methods in a functor that adds this logic to your methods. To me that makes the code easier to read because I don't have to parse 2 functions anymore.
Maybe doing this is inconvenient in Ruby, but its certainly not inconvenient in some other languages.
There's always the case that they're identical by coincidence and that they need not be identitical in the future. In that case, yes, of course don't prematurely abstract the code away. But that wasn't mentioned in the article.
1
u/Respaced Mar 10 '23
Sometimes a tiny bug is found and fixed in a function, that is shared across many places. The problem is now that other places might depend on that bug still being there. In ways that are not immediately obvious.
1
u/[deleted] Mar 10 '23
As a general rule, apply general rules in general.
0
u/[deleted] Mar 09 '23
[deleted] — view deleted comment
0
u/[deleted] Mar 09 '23
[deleted] — view deleted comment
0
u/[deleted] Mar 10 '23
[removed] — view removed comment