r/programming • • 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

162 comments sorted by

282

u/flerchin Mar 09 '23

Go Ahead Repeat Yourself. GARY

38

u/ScaredOfMyRawr Mar 09 '23

I actually Googled this to see if it was a thing 😅

73

u/SwiftOneSpeaks Mar 09 '23

I've seen actual discussions of "AHA", (Avoid Hasty Abstractions) as the selective rejection of DRY

70

u/UristMcMagma Mar 09 '23

Write Everything Twice

4

u/poopadydoopady Mar 09 '23

Happily Include More Since Everyone Likes Functions.

1

u/DoctorSalt Mar 09 '23

My motto when I'm writing header files

1

u/[deleted] Mar 10 '23 edited Mar 10 '23

This, unironically.

When you've written it more times than twice, it will be super clear to you that it's a pattern that comes up often in your domain so you'd actually re-use the code if you refactor it. It's the right time to create a framework. (That's what DRY refactors are - creating a framework.)

And, because you've got it written a few times, it'll be super clear how to do the refactor when you do it. You'll see the lines of code you should factor out into a helper function, etc, right in front of you. You'll end up with a better API between the two layers in your code base compared to if you tried to figure it out ahead of time.

WET, then DRY. Just pretend you're swimming. Get wet, then get dry.

Also, two isn't a hard rule for the number of times you should aim to repeat yourself. I've also had success using three or four.

0

u/[deleted] Mar 09 '23

[deleted] — view deleted comment

17

u/[deleted] Mar 09 '23

WET (for those that missed it, the opposite of DRY - nice) LOL

4

u/falsedog11 Mar 09 '23

I adhere to the WET principle - write everything twice.

1

u/netherwan Mar 11 '23

Again, I said my name is Jerry. JERRY.

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.

  1. When 2 things whose underlying point - the spec, the reason they exist, are completely unrelated, but nevertheless their code looks very similar. Do not try to fix the DRY problem here. This will lead to a method that grows booleans and other 'modal-choosing' parameters in the future; imagine the roads the 2 separate concepts will walk as entirely separate, it's just that the 2 roads, starting from a different place and ending in a different place too, so happened to overlap for a short while somewhere in the middle, and right at that point, someone waltzed in and decided to take their DRY-violation-linting-tool report a little too seriously. And now 5 years later you have 2 unrelated tasks stuck in one method, with 1 or even multiple modal-choosing parameters dictating how it goes, which, I would hope, is obvious to almost any programmer as a highly suboptimal solution. However, if this happens it may easily be possible that there is some abstraction you could write that both impls can use that would simplify both of them without involving weird modal-choosing parameters. (i.e. there's a common subtask, and that can and should be isolated solving some of the duplication).
  2. It convolutes flow. It's simply easier to read through a series of local (or private or _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.

337

u/GeneReddit123 Mar 09 '23

Can be illustrated with this silly analogy:


"What is the temperature outside?"

"44."

"How old are you?"

"44."

"Gotcha, writing the code now."

The code:

def outside_temperature
  user_age() //extracted common logic
end

tl;dr: DRY things which are logically related, not those which happen to be similar at this point in time, but are not related and not guaranteed to remain similar in the future.

141

u/BigYoSpeck Mar 09 '23

Just to be a little pedantic at what is otherwise a decent analogy for the dangers of DRY, something coincidentally giving the same result wouldn't make it a candidate

A better example is not using the same temperature measuring device to check oral and anal temperature

39

u/Lobreeze Mar 09 '23

Hopefully you check in that order when using same device.

15

u/Thirdbeat Mar 09 '23

Not if the list sorts alphabetically

16

u/BigYoSpeck Mar 09 '23

Thankfully they're a simple directed graph and thus swallowing the thermometer is an optimal solution

2

u/alluran Mar 10 '23

I would hope you're using a FIFO queue, not a list for this.

14

u/zephyrtr Mar 09 '23

But did you wash between sessions?

17

u/iamapizza Mar 09 '23

Sometimes I do and sometimes I don't. It's a session variable.

5

u/[deleted] Mar 09 '23

You're going to have to submit a jira ticket so we can prioritize that work

2

u/[deleted] Mar 10 '23

Please update the status to high priority. This needs to be resolves as soon as possible.

6

u/Arc125 Mar 09 '23

Flashbacks to the Idiocracy hospital scene.

39

u/Conscious-Ball8373 Mar 09 '23

There's another DRY case that I see frequently that causes moderately severe maintainability issues:

TOP_DIR = "/"
USER_DIR = os.path.join(TOP_DIR, "usr")
THIS_MACHINE_DIR = os.path.join(USER_DIR, "local")
LIB_ON_THIS_MACHINE_DIR = os.path.join(THIS_MACHINE_DIR, "lib")
OUR_APP_LIB_DIR = os.path.join(LIB_ON_THIS_MACHINE_DIR, "program_name")
PROCESS_FILE_EXT = ".pid"
PID_FILE_1 = os.path.join(OUR_APP_LIB_DIR, "dhcpcd" + PROCESS_FILE_EXT)
PID_FILE_2 = os.path.join(OUR_APP_LIB_DIR, "nc" + PROCESS_FILE_EXT)

Bonus marks if these definitions are sprinkled across multiple modules.

Some poor engineer finds a file on the system called /usr/local/lib/program_name/dhcpcd.pid. Good bloody luck to him trying to find the code that creates it. Searching for any string in the path other than dhcpcd will not return anything that even remotely hints that it's related to this file. Even if he manages to find that file, it's not obvious that it is the filename he's looking for without checking half a dozen other definitions.

Yet people will always prefer this style to just writing PID_FILE_1 = /usr/local/lib/program_name/dhcpcd.pid because DRY.

18

u/[deleted] Mar 09 '23

God I see this in a particular codebase at work and it drives me insane. There's nothing wrong with simple repetition when the statements are all together like that...

root =         /foo
libs =         /foo/bar
services =     /foo/bar/svc

6

u/papasmurf255 Mar 09 '23

I've seen this with SQL queries too. Find a slow query in the query stats and want to find it in the codebase? Good luck 🥲

6

u/jarfil Mar 10 '23 edited Dec 02 '23

CENSORED

-3

u/Conscious-Ball8373 Mar 10 '23

"Other debugging tools" 😂😂😂 Tell me you don't work on constrained embedded platforms without telling me you don't work on constrained embedded platforms.

Yes, there can be reasons - for instance, the code I was thinking of has a unit test framework and we prefer not to run it as root so being able to move the whole lot somewhere else is useful. But the example is both typical of code I see and massively overdone. Note also that no-one of the symbolic names contain the path element they represent, so even a reasonably clever case-insensitive regex won't find them - also typical of what I see.

2

u/jarfil Mar 10 '23 edited Dec 02 '23

CENSORED

1

u/Conscious-Ball8373 Mar 10 '23

I didn't say "develop on", I said "work on." I use an IDE, thanks.

Your proposed debugging method is unworkable for all sorts of reasons:

  • Realistically, a PID file goes in /run which is a ramfs created from scratch on each boot. Opportunities to make it read-only are relatively difficult to come by, especially since:
  • The file I chose was one created in the course of bringing the network interfaces up on system boot. Quite early in system boot. On a system where almost everything else is a read-only filesystem.

So to do what you suggest, I'd have to make a source tree change that creates the file in /run and makes absolutely certain that a process running as root can't overwrite it (realistically it'll probably take me a couple of goes to get this right, but let it pass), build a new firmware image, sideload it and boot it. That takes about two hours. OR if were just a little bit flexible on how we apply DRY, I could have found it using grep in about three seconds.

I'm glad you work on systems that are easy to work on. We don't all.

1

u/jarfil Mar 11 '23 edited Dec 02 '23

CENSORED

-2

u/KevinCarbonara Mar 09 '23

Yet people will always prefer this style to just writing PID_FILE_1 = /usr/local/lib/program_name/dhcpcd.pid because DRY.

You should never write that line, regardless of DRY.

14

u/fresh_account2222 Mar 09 '23

Even more concisely: Imagine one of them changes. Should the other one change too?

4

u/s73v3r Mar 10 '23

Hell, sometimes that two things are not logically related isn't apparent until further down the road, so one should be willing to refactor when that becomes apparent.

2

u/Kwantuum Mar 10 '23

Generally the point when you start to introduce boolean flags to a function is also the right time to ask yourself if this shouldn't just be two functions.

3

u/ricky_clarkson Mar 10 '23

Solved: FORTY_FOUR = 44

This can safely be used for ages and temperatures.

I jest, but I saw ALL = "ALL" just today.

1

u/The_Northern_Light Mar 09 '23

I laughed, but I definitely used to do this.

19

u/unknownmat Mar 09 '23

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.

Very insightful! Good writeup. I've run into this, and can maybe give an example.

After noticing duplication in the way I was throwing and managing exceptions, I - being the diligent young programmer I was at that time - of course consolidated it all into an exception library that perfectly eliminated the duplication and allowed exceptions to be created and thrown with minimal impact at the error-site.

A problem came up, however. Before, the exception mechanism would produce error messages pointing me to the function and line-number of the problem in my code, which was very helpful for figuring out what the system was doing when the error occurred. But after the refactoring, all the messages pointed to the same library routine within my exception library.

I had to learn that not all duplication is necessarily redundant, and that it sometimes serves a useful purpose.

4

u/iloveportalz0r Mar 09 '23

The tool you needed is macros.

3

u/unknownmat Mar 09 '23

Thanks. It was a while ago, but I do believe I wound up using a macro-based solution.

2

u/[deleted] Mar 09 '23 edited Jan 02 '24

lavish cheerful worm mysterious rhythm birds shelter deserve absorbed childlike

This post was mass deleted and anonymized with Redact

9

u/cogman10 Mar 10 '23

These are good points.

One other I'd make is that of the dependency problem (DLL Hell).

What few seem to recognize is that dependencies aren't free "save time magic". That's because code that works today may not work tomorrow when you need to update your dependency to address a CVE. The more complicated the dependency web, the bigger the headache updating can be.

If you need a single function which can be written in 2 minutes, just write the damn function rather than pulling in the dep. Nobody needs the isOdd or isEven dependency.

The worst examples of this that I've seen are when someone pulls in a giant framework for a single simple method tangentially related. "Why yes, I'll pull in JavaFX, because I really like the Pair class it has" (real example). You can imagine my confusion seeing a backend web service/client with a gui framework dependency.

DRY is over-applied because it's easy for someone to parrot without thinking and see without reasoning. "These 2 lines of code are the same?!!?!?!?! VIOLATION, SINNER, TRANSGRESSION!". I'd go so far as to say code without methods and with tons of repetition is often easier to maintain and fix than DRY code I've dealt with.

26

u/noodlez Mar 09 '23

I would suggest a third thing:

When the product is still in flux. Its sort of a corollary to your first point, but often times, two things can start at a place where they have the same underlying point, but because a product/feature/etc is so new, user feedback (or whatever else) might make the "underlying point" diverge due to new information.

It can be a huge waste of time to abstract and then un-abstract something. So, wait to DRY things up until there's a really solid grasp on the use case.

I generally speaking follow the rule of three, but sometimes expand it beyond just three, depending on the situation.

31

u/venustrapsflies Mar 09 '23

I'm not so sure, actually. In fact I was about to say almost the opposite.

When you get to a point that two slightly different ways of using a function should just be separated, it's almost trivial to split the code for that function into two variants and clean up each branch separately.

But going the other way can be an extremely expensive operation, because when two copies are grown independently they accrue non-meaningful differences. It's then up to someone to check every line of both copies and parse out every code difference just to figure out how they can be combined.

Abstractions don't need to be costly, in fact organizing as generally as possible (without adding unneeded complexity) can end up producing code that is easier to extend and maintain in the future, for reasons that aren't even obvious to you when you write it.

This is basically thermodynamics applied to programming. It's a lot easier to increase entropy than to decrease it, so I'd always lean on the side of DRY until there's a solid case to violate it.

4

u/robhanz Mar 09 '23

Arguably, if they’re hard to combine, they’re not the same thing.

13

u/venustrapsflies Mar 09 '23

In practice this is not true. People can and will write code to do something logically equivalent in very different ways. Even ostensibly minor differences in things like variable names, style, formatting are completely trivial from a logical perspective but can require a good bit of parsing to fully understand. Two code blocks can be programmatically distinct, but have equivalent (or approximately so) business logic. When they're actually a bit different, it might mean a bug in one, and it's not free to figure that out. Are A; B; and B; A; equivalent? It depends!

If everyone was a disciplined coder that followed a consistent style and common practices in your org, it might not be that big of a problem. But that's not the reality we live in.

2

u/noodlez Mar 09 '23

Hey, whatever works for you. I know I've lost significant time to prematurely optimizing and DRYing up code.

However, I think your comment focuses heavily on the "its easy to just un-abstract stuff" without really significantly discussing the costs of doing the abstraction in the first place, extending/managing bad abstractions, as well as the costs of needing to support abstraction layers that exist in your codebase for no real reason.

4

u/venustrapsflies Mar 09 '23

I wouldn't dispute the truth of any of the things you've said. I think it's a matter of appropriately weighting these factors given the application and the team writing it.

It is a bit of a noob trap to try to over-abstract things right out of the gate. But with experience you can learn to quickly identify which ones are likely to be fruitful. If it's a lot of work to figure it out, then it's probably not worth it, but sometimes it just takes a little bit of thought.

I've also spent a lot of very frustrating time de-duplicating co-workers copy-pasted code, and the inefficiency of that process irritates me to no end.

7

u/c4boom13 Mar 09 '23

The way I look at it, "premature optimization is the root of all evil" is still undefeated. Things like DRY are still subject to it.

A lot of the skill and experience that makes someone a successful developer is just focused on determining if something is premature or not yet. No one has a crystal ball, so it's always a bit of an art to find the balance.

2

u/rzwitserloot Mar 09 '23

they accrue non-meaningful differences

If the two tasks are unrelated, the differences are rather unlikely to be 'non-meaningful'. If it is likely that any accrued differences are non-meaningful, it wasn't a case of 'these 2 things are unrelated, it's just that their code is rather similar right now'.

1

u/Uristqwerty Mar 10 '23

When you duplicate the function, you need to decide which call sites to change to the new copy. As a compromise, when first combining them you might have them all delegate to a single instance as an implementation detail, while leaving the original semantics clear. Effectively, deduplicate the parts that actually coincide, leaving the differing names and locations in place.

1

u/fragglerock Mar 10 '23

This is when you hope to god your unit tests are testing functionality not implementation and they will protect you through the refactor!

1

u/xeio87 Mar 09 '23

It can be a huge waste of time to abstract and then un-abstract something. So, wait to DRY things up until there's a really solid grasp on the use case.

Couldn't you say similar to not abstracting to begin with? If the functionality isn't shared you probably need twice as many things like tests which doubles your up-front workload that you may not have needed.

A bigger motivation for me, than not having copy-pasted code, is having fewer failure points to need to test since the same code paths all get tested at once.

1

u/noodlez Mar 09 '23

If the functionality isn't shared you probably need twice as many things like tests which doubles your up-front workload that you may not have needed.

In my experience, this isn't as related to abstracting or not abstracting. Its about the complexity and topic of the abstraction.

7

u/Habadasher Mar 09 '23

If things change together, they belong together. Your example is a good illustration of how the opposite is also true, if they don't change together, don't force them together.

7

u/Goodie__ Mar 10 '23

One thing a senior once said to me thats stuck in the yesrs since

"Its important to unserstand somethings look the same, but arent, and some things look different but really arent"

Being able to tell the difference is a constant strugle.

10

u/_Pho_ Mar 09 '23

Also DRY code isn’t a product. Code reuse is good but it ultimately isn’t (or shouldn’t be) a bottom line.

2

u/warlaan Mar 10 '23

DRY isn't as much about code reuse as it is about preventing bugs.

Code duplication is a form of code debt, and as such at times it makes sense to tolerate it. If you know that the point in time where the code debt is going to hurt you is likely to never come (like in a single-run script or days before the deadline of a prototype) then removing code debt may just be a waste of time.

3

u/robhanz Mar 09 '23

There’s a different between things being inherently the same, and then being accidentally/temporarily the same.

Writing one piece of code that does ten mostly-unrelated things makes everything worse.

3

u/Plazmatic Mar 09 '23

and 3. Don't implement DRY just to get around the limitations of your programming language. This comes up a lot in C++, C++ lacks a few critical features the promote a lot of boiler plate, for example static reflection. Magic enum for example, attempts to be a "hack" around the problem of this specifically for enums, and even it has massive problems that are better off served by redudancy/code generation outside the langauge itself. But there are other scenarios where going down the rabbit hole of trying to hack around features to get around the lack of a feature will end up being a more complicated effort than actually just repeating yourself. Even with a constant cost on programming effort, that cost can be extremely high.

Another example with enums and C++. C++ enums are special, in that unlike classes, structs, and unions, enums can't have methods. This... is a big PITA in many projects, especially those that are enum heavy, or rely on bit flag enums. What you might be enticed to do, is take advantage of constexpr classes and static members to emulate enums with member variables, and all the other tricks you can do with regular objects. Going further, you could extend this to somewhat look like match expressions in other languages like python or rust. But doing this would be:

  • Complicated to literally anyone new you hired on
  • Require your own documentation separate from your project
  • Be harder to debug
  • Be harder to write
  • Possibly take longer than the entirety of the project you're already working on.

1

u/[deleted] Mar 09 '23

Thanks for this description. This actually helped me rationalize doing some things in separate programs in LabView when I can see that they are similar, but ultimately they do different things and if I have a problem in one later it could cause problems in the other trying to fix it.

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.

8

u/bheklilr Mar 10 '23

Currently working on rewriting some code at work right now where the original dev did a lot of premature abstraction. There are some shared data types with a lot of fields, and for some of them there are 4 or more different methods that build different parts of an instance, spread across 3 different layers of inheritance. My rewrite is just repeating itself, despite intellij bitching at me about repeated code. However each code block is slightly different, and now these blocks are linear, contained in a single class, and far more readable. In fact, I've been discovering bugs in the original code.

My philosophy is to not make abstractions unless you need to, not just because you want to.

2

u/drakens_jordgubbar Mar 10 '23

spread across 3 different layers of inheritance

Sounds like they did the wrong abstraction. Inheritance is rarely the right answer.

If you need to share code between classes, just use composition. If you need polymorphism, just use interfaces.

My main concern with having many repeating, but slightly different, code blocks is that it’s difficult for the next developer to tell the differences apart. Like, how do you tell if a difference is intentional or not? What happens if the next developer overlooks a difference?

A good abstraction should emphasize what’s different and what’s the same between all code blocks. If it’s unclear, then it’s not a good abstraction.

3

u/bheklilr Mar 10 '23

spread across 3 different layers of inheritance

Sounds like they did the wrong abstraction. Inheritance is rarely the right answer.

The original dev is thankfully no longer on the team, which we're thankful for if you catch my meaning

My main concern with having many repeating, but slightly different, code blocks is that it’s difficult for the next developer to tell the differences apart. Like, how do you tell if a difference is intentional or not? What happens if the next developer overlooks a difference?

There's a risk to that, but in this case it's a reporting app that has fairly well delineated paths it can take. I'd say 2 words uniquely identify the main paths the code can take: customer type and report type. If there's a problem with X report type we know that crosses all customer types and vice versa.

After long talks with my teammates we all came to the conclusion that it's better for our code to be a bit repetitive than have it be overly abstracted. Maybe the pendulum is just swinging too hard in the other direction but that kind of problem rarely crops up due to how we expect issues to arise.

2

u/drakens_jordgubbar Mar 10 '23

Well, it’s impossible for me to make a full verdict without seeing your code. Your work sounds like an improvement at least. What matters is that it’s easier for your team to work with.

4

u/Cart0gan Mar 10 '23

Premature optimization is not as bad as people make it out to be. Having to rewrite large parts of the codebase because they need to be optimized but the whole thing was written with a suboptimal approach from the start, now that sucks.

10

u/[deleted] Mar 09 '23

Sure, but the alternative when you have parallel development going on in a greenfield project is that everyone implements everything differently.

Creating an underlying unifying abstraction after the fact can end up forcing painful refactoring.

My preferred solution is to make lightweight abstractions initially and let the implementors contribute back concepts over time. I see the abstraction as a place where devs working in parallel can create a shared understanding of a fundamental concept.

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"

7

u/sorryforconvenience Mar 09 '23

Ya! That one stuck with me too. Here's the source afaik:

https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction

2

u/smokesick Mar 10 '23

Lovely read. Thanks for sharing!

102

u/EvenInfluence9 Mar 09 '23

WET. Write everything twice

35

u/boy_named_su Mar 09 '23

We Enjoy Typing

21

u/[deleted] Mar 09 '23

Especially for tests. DRY tests are often difficult to change and read.

3

u/Zalack Mar 10 '23

I think it depends. Especially in integration tests you often want to assert a bunch of stuff on a success that mostly stays the same, but need to test a bunch of different inputs. Sometimes you can dry that out by using a pattern like table tests, or fuzzing (although Fuzz tests should generally be their own layer of testing after well defined integration tests). But other times the setup for various tests is too different to allow that.

In that case having a common assert_success helper or something can REALLY help. I hate when I add a field to a Payload then have to update like 50 tests in a file instead of 1 helper and the 3 tests that actually return a non-default value.

1

u/[deleted] Mar 10 '23

Yeah, I've often suggested reusable assertions in PR reviews, but WET during test setup for clarity.

21

u/Irregular_Person Mar 09 '23

MOIST. Maybe Optimize If Shit's Tangled

1

u/DeceitfulDuck Mar 09 '23

This is my new favorite

1

u/teepee33 Mar 10 '23

Start Over And Keep Everything Dry

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.

36

u/dAnjou Mar 09 '23

Or shorter, heard it first from Sandi Metz: a little duplication is cheaper than the wrong abstraction.

6

u/CodyEngel Mar 09 '23

Yep, Sandi Metz also coined AHA 😊

7

u/dAnjou Mar 09 '23

Ah, didn't notice you were quoting a principle.

Had to look it up. Apparently Kent C. Dodds coined it, but influenced by what Sandi said 😅

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

If you needed to add additional data to the context, sure it would be quicker if there was the helper, but there’s no guarantee the data needed is in the parameters currently passed, in which case you have to update all places that the helper is used anyway.

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!

7

u/salbris Mar 09 '23

I agree but not everything is caught by a typechecker. Logical errors can and do happen while refactoring. Reducing the number of dependencies between pieces of code helps make it more resilient to bugs.

3

u/IAmTheKingOfSpain Mar 09 '23

In this case, I have a hard time believing that a type checker won't help you catch missing required parameters, unless you've got some dynamic, untypeable function calls that I would avoid in your codebase.

3

u/salbris Mar 09 '23

Absolutely, that's the beauty of statically typed languages there are a whole host of bugs they catch.

1

u/livrem Mar 09 '23

You can have the correct types, but the wrong values. Kind of easy error to do with code-completion I noticed that you find a function that returns the correct type without realizing it wasn't the thing you actually needed. Everything can not have its own type. You always end up, somewhere, with two different functions that returns the same type, but not always the same value.

1

u/nschubach Mar 09 '23

Honestly, the version number being passed on assumes that the client knows the inner workings of the called method so it "does the thing right" and that's the code smell for me.

If the version is needed to process the data properly, it should be part of the data, not the method passing it along.

11

u/ProgramTheWorld Mar 09 '23

By removing the duplication, we’ve unnecessarily coupled a large number of classes together.

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.

7

u/BestUsernameLeft Mar 09 '23

Coupling is more than just "does this class have a reference to that class". You also have to take into consideration execution flow. If classes Foo and Bar both use class Bazoo, I still consider Foo and Bar to be coupled because of the shared execution flow.

The above, in my experience, is where the dreaded "Oh, just pass a boolean..." problem is sometimes introduced by the well-meaning developer who wants to maintain DRY.

Imagine a new requirement that requires the shared code in Bazoo.frood() to change -- but only when called from Foo. Our well-meaning developer sees that the smallest, easiest change to effect this is to introduce a boolean to Bazoo.frood(); Foo passes 'true' and Bar passes 'false'. And now matters are worse.

7

u/ProgramTheWorld Mar 09 '23

By that definition, all classes in the application would be considered coupled, otherwise that would imply there are unused code.

I think what you mean by “coupled” is that the dependencies are “coupled” in the way that, when a dependency needs to update some logic in the common helper class, that in turns affects all the other consumers.

In your example, I would say that is not a problem in the pattern but a problem in the implementation of the change. A common code smell is using booleans as arguments. You almost never should be using booleans as arguments. Introducing a new method would be a better choice and is backward compatible.

IMO, the point of having a common helper class is to ensure the common business logic is shared across all of its dependencies. If a dependency requires its own special logic, then by definition that’s not common business logic and it shouldn’t be done in the common helper class. With that said, code structuring heavily depends on the context and it’s definitely a tricky matter.

2

u/BestUsernameLeft Mar 09 '23

Yeah agree, my wording could have been better / more precise. Thanks.

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

3

u/[deleted] Mar 09 '23

It is sometimes necessary to write things more than twice, actually. There are parts of my codebase where a piece of code is repeated 20x times, without abstraction.

4

u/siemenology Mar 09 '23

I've found that test code is a place where writing things 20x is fine, and even preferable. If your tests are simple snapshots, then sure using a loop with an array of parameters and expected values is fine. But if your tests are more complicated, and involve setting a few things up, and checking different properties of result objects, etc etc, then it's usually better to repeat all of this code each time.

When you are diagnosing why a test failed, you want to be able to see exactly what the test was doing when it failed -- you don't want to have to read through 5 layers of indirection to figure out what was happening when it broke.

Second, tests usually aren't exactly the same things each time. If you try to create test "helper" functions that can handle every variation you might want to do, you've usually created a nightmare. It's usually much easier to copy and paste a similar test and make tweaks for the case you are testing.

Third, tests are generally static and fairly independent. They represent a set of requirements for your code, so an individual test at the integration level should only change if the requirement it is testing changes as well. They don't benefit from being able to make a fix in one place and have it apply everywhere, the way application code does. In fact, doing that may actually invalidate some of your tests. And bugs in test code are in many ways the most insidious of bugs. Or at least the most annoying.

In conclusion, make your test code really dull. Copy and paste where you need.

3

u/PurpleYoshiEgg Mar 09 '23

100%. I've seen people on team in the past try to reduce the boilerplate of the test code. Then, when the code decides not to work on someone else's machine, you are often struggling to figure out how your layers of test initialization are being set up and failing.

Plus, having redundant test code helps people with examples on how everything is initialized, or different ways things can be initialized. I love opening a complex project and seeing a bunch of small tests that help me understand the entry point into the API the team's devised.

1

u/jaytan Mar 10 '23

You won’t believe the number of for loops we fit in this bad boy!!

1

u/SekYo Mar 09 '23

I kind of use the same rule of thumb to decide when to abstract something, especially if working in a new product constantly changing.

I like this explanation too: there are an infinite number of lines that goes through one point. There is always one line that goes through 2 points (so your second similar case could be a pure coincidence). But if you have a third point still aligned with the two others, chance that you have a real commun concept are a lot higher... And thus this is probably a good time to avoid copy/pasting another time and abstract it.

But again, this is just a rule of thumb and all these recommendations (DRY, YAGNI, KISS, etc..) should not be applied blindly.

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:

  • You write your business logic in four separate locations, now you're 4x more likely to make a mistake.
  • You had your coffee that day and wrote all four correctly, but now there's a spec change a year later. Do you remember all four?
  • You had your coffee and they all match, but all are wrong, see above.

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(), not excludeNonButterflies(), 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.

13

u/BradBeingProSocial Mar 09 '23

It’s sucks though when you try to search a codebase for a common name and get 1000+ results. Another trade off here with reusable name vs searchability

2

u/m15otw Mar 09 '23

IDEs can find usages, not just instances of the string in code, pretty well these days. Project-wide refactor isn't always perfect of course, but I think generic names should be widely used if the generic is the correct name, and that's not a bad thing necessarily.

4

u/troyunrau Mar 09 '23

I'm not sure this is necessarily good advice. A verbose name implies that it was tested to perform a single task. Whereas a generic name implies it should be able to do a bunch of things, but you don't know if it was actually tested for those cases. So you either end up having to make assumptions about the safety of the function, or you end up having to add new tests each time you apply it in a new circumstance.

Futhermore, names like filter are often reserved words - granted some languages have more polluted namespaces than others. More verbose names tend to avoid accidentally redefining something core to a language (which you can do, for example, in python).

3

u/m15otw Mar 09 '23

Well, if filter() is a built-in function, like it is in python, then you don't even need to write a custom function! Boom, less code, still works = improvement.

I am more talking about finding the "correct" name for the function. It might be more general OR more specific than you're naming it at first - my example was extreme. Naming is hard, but if you get the name right, then it gives you a clue about how general or specific the function is when you're reading it somewhere.

4

u/troyunrau Mar 09 '23

There are only two hard things in Computer Science: cache invalidation and naming things.

1

u/m15otw Mar 09 '23

This is indeed what I was referencing in my original post. If you spend time on the problem, you do improve things (unlike with cache invalidation). It is just hard to persuade your manager to devote time to naming things better.

4

u/john16384 Mar 09 '23

Really? filter? Does it filter things out that match an expression, or does it keep the ones matching the expression...

1

u/m15otw Mar 09 '23

Well, this is the signature I'm most familiar with.

https://docs.python.org/3/library/functions.html#filter

Actual answer: one argument is a lambda which maps an element to a boolean - those elements that map to True are included.

6

u/john16384 Mar 09 '23

My point is that you mentioned good naming, but then use filter, which is quite ambiguous, as an example.

2

u/m15otw Mar 09 '23

My example was extreme, sure.

But sometimes a method is just filter (and there was probably a standard library function that could have been used instead.)

Other times its a super specific bit of code, in which case the name should reflect that. The point is that if you spend a little time thinking about the name, you might figure out whether it is reusable elsewhere or not.

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?

  • yes => DRY up to avoid future bugs/inconsistencies
  • not necessarily => leave it the F alone

1

u/NotMyRealNameObv Mar 10 '23

I keep seeing people extracting common code in test cases at work:

void doTest(bool v1, bool v2)
{
    // common code
    
    if (v1)
        // do something
    else
        //do something else
    
    if (v2)
        // do something
    else
        // do something else
    
    //more common code
}

TEST(Test1)
{
    // some set up code
    doTest(true, true);
    // some tar down code
}

TEST(Test2)
{
    // some set up code
    doTest(false, false);
    // some tar down code
}

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

1

u/SquishTheProgrammer Mar 10 '23

If using MSTest why not just use a DataRow attribute instead? xUnit and nunit have similar attributes (Fact and Theory I think?).

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

30

u/salbris Mar 09 '23

Exactly. Problem is this is not easy, it's more like a gut feeling than an objective analysis. For that reason alone is why no advice should be thought of as a silver bullet. Everything has pros and cons.

8

u/Climax708 Mar 09 '23

This.

One way to try to approx this, is to look at who are the stakeholders/users of the use cases. If the stakeholders/users aren't the same, then they'll probably change independently.

5

u/Grouchy_Client1335 Mar 09 '23

This reminds me of something in DNA - some genes can be traced to a gene duplicatation event. Once a gene got duplicated, each copy would be able to undertake separate evolution, with one copy retaining the original function while another copy of the gene is free to evolve in new directions.

The fact that it happens in mother nature's code shows that it's ssometimes a good thing.

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

0

u/[deleted] Mar 09 '23

[deleted] — view deleted comment

7

u/mindbleach Mar 09 '23

Not especially on-topic, but uh, what are your mirrors usually filled with?

3

u/KevinCarbonara Mar 09 '23

The issue of the hollow mirror is that so, so many people understand DRY to be "don't copy and paste code, if you end up writing the same lines of code you should pull them out into a function/class abstraction instead". That is not what DRY says nor has it ever been.

That actually is pretty much verbatim what Robert Martin says

0

u/[deleted] Mar 10 '23

[deleted] — view deleted comment

1

u/KevinCarbonara Mar 10 '23

Robert Martin came up with SOLID, not DRY.

No one said he invented DRY 🙄

For that matter, he didn't invent SOLID either

0

u/[deleted] Mar 10 '23

[removed] — view removed comment

1

u/account312 Mar 11 '23

for example using functional programming merely to avoid writing the i++ in a for loop.

DRY doesn't in any way imply that you shouldn't use for loops.