Opinions on how to deal with duplicate code. - eviltoast

The “don’t repeat yourself” principle is well established, but over-aggressive refactorizarions to extract common code are also widely known for creating hard to maintain code due to the introduction of tight coupling between components that should not be coupled. A passing resemblance between code blocks is reason enough to extract them away, even if that ends up breaking Liskov’s substitution principle.

To mitigate problems caused by DRY fundamentalisms, the “write everything twice” (WET) principle was coined. WET works by postponing aggressive refactorizarions, the kind that introduces complexity and couples unrelated code just because it bears some resemblance, by creating a rule of thumb where similar code blocks showing up twice in the code should not be refactored, and only code that shows up multiple times should be considered for this task. However, this rule ignores context and nuances, and can dissuade developers from cleaning up code.

So, where do you stand on the topic? How do you deal with duplicate code? Do you follow any specific rule of thumb?

  • robinm@programming.dev
    link
    fedilink
    arrow-up
    3
    arrow-down
    1
    ·
    1 year ago

    There are 2 metrics that need to be considered:

    • easy to read
    • easy to modify

    The first point is by far the most important. Usually DRY win because less code means less to read so less to put in your head. But if the abstraction is too complicated (for example because there are two many parameteres) then it’s worth considering drying.

    And don’t forget the second point, but do not overthing and YAGNI. Sometime a simple comment “don’t forget to update method foobar()” is enough. Don’t forget either that you can always rewrite the abstraction when you need to modify something (if the original did not fit your new requirements), but for this to be an easy task, the understanding of the original abstraction must be crystal clear. That’s why the first point is so important.