Hacker News new | ask | show | jobs
by jehlakj 1914 days ago
DRY seems to be one of those principles too many people take literally. Especially among junior devs from my observation (and experience).

Just because there is a block of code that’s being used in two different places doesn’t mean it should always be abstracted out. There’s a subtle yet mindful consideration whether these two consumers are under the same domain. Or if it should exist as a utility function across all domains. And if that’s the case, changing the code to make it generic, simple and without side effects is ideal.

I’ve seen too many of these mindless DRY patterns over time, and they eventually end up with Boolean flags to check which domain it’s being used in as the codebase becomes larger.

4 comments

DRY should really be DRYUTETNRYDTP - dont repeat yourself unless the effort to not repeat yourself defeats the purpose

I also propose LAWYD - look at what you've done, a mandatory moment of honest reflection after drying out some code where you compare it to the original and decide if you've really improved the situation

I honestly thought that was one of the principles of DRY. Maybe I've been wrong this whole time. Will it be faster, safer, more maintainable if I just leave this code in here twice? At what point does that equation change?
My approximate guideline is "is this copy and that copy of the code the same because they HAVE to be, or are they accidentally the same?"

If they absolutely have to be the same, wrap'em in a function. If they just happen to be the same, leave them as separate copies. If I don't know, make an educated guess.

Sure it is. However, teachers/mentors may be just a tad to dogmatic and pupils/juniors may just be a tad to inexperienced to properly grok when to do what.

And it sure is easier to just not argue about it and abstract everything. The real pain only comes later, after all.

Just this week I came across a set of 20+ controls in a form. Every control downloaded some version of a file from "report". Not once was there any shared code behind any of these controls. Because different people over time touched this code, not all of the functions were in the same place. And those that were each had slightly different nuances.

Without DRY, this would be a perfectly acceptable practice. DRY gives me something I have in my head when I see this and refactor into something that is manageable. DRY gives me something I can point to and say "please for the love of god don't perpetuate this folly".

I think a good rule of thumb is to never prematurely apply DRY in source code BUT always try to aim for it when it comes to data and configuration unless there's a special need.
pylint irritates me a bit for this. I already created an abstraction, and I'm using the abstraction in a few places, but pylint doesn't like that and says it's duplicate code.