We all love the DRY principle (Don’t Repeat Yourself). It really is a good idea, we don’t want to have two places in the code that do the same thing, and we want good object-oriented design. But even DRY can go too far.
Recently I’ve run into some cases where DRY decreases the readability of the code. I had some simple classes to write that do some relatively simple calculations, and the business rules are fairly similar to some other classes that exist, but with a few differences. I started down the path of making one class that can handle all situations, with hooks for modifying the behavior of the class (either virtual methods or configuration settings somewhere else).
This is all well and good until you realize that now you’ve taken something simple and turned it into something really complicated that even you have a hard time understanding anymore.
DRY is great, but I lost sight of why DRY is good. DRY is good because it makes code more maintainable, more consistent, and easier to understand and add new functionality. But as soon as DRY stops providing those benefits, maybe it’s time to keep things simple and just write readable code that makes sense, even if it means you have a little bit of duplication.
Avdi Grimm did two RubyTapas episodes on the concept of Coincidental Duplication. (episodes #89 and #92)
In those episodes, he points out that the core of DRY is about eliminating the duplication of knowledge in a system (specifically, domain knowledge). If there are two distinct pieces of knowledge that are *coincidentally* implemented in a similar fashion, that doesn’t mean they should be combined. The similarity in structure does not imply a shared domain concept or shared piece of knowledge.
I like this idea because it clearly explains cases in my own experience where a DRY-focused refactor made the code worse. In those instances, it was clearly a coincidental structural similarity in the code. In fact, one easy way to spot the difference is to think about how two similar chunks of code would change. If it would ever make sense that one would change without the other, then it’s very possible that the similarity is structural, coincidental (and perhaps even temporary). If, on the other hand, two similar chunks of code will likely change in concert, then that’s an indication that they share a domain concept. As such, the duplication should be removed.
In short, finding the nuance in what is DRY vs what is coincidental duplication usually makes clear what would be a good refactoring and what wouldn’t.