Balancing DRY and readability

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.