An Obsession With Being DRY?

In the programming world, there is a principle referred to as ‘DRY’, which stands for “Don’t Repeat Yourself”. In a nutshell, it states that if you find yourself writing identical code in two or more different areas of a system, then you should rationalise this into a single module that is utilised within these areas.

DRY is part of a broader principle of Code Reuse – a fundamental tenet of software engineering. The reuse of code carries with it the advantage of a smaller code base and reduced maintenance costs.

As the spotlight falls ever more frequently on the world of Object Oriented Programming (OOP), it’s worth highlighting some of the key challenges that this discipline attempts to address. Code reuse is certainly one of them, but others such as segregation of functional responsibility, and ‘coupling’ are also relevant.

‘Coupling’ is a term that describes interdependence of a system. Systems are said to be highly coupled when each module depends on many other modules in a system. We can visualise the modules as a series of balls each connected by a string to other balls (modules) on which it depends. This analogy is quite good, as we can see that a system that is highly-coupled (lots of string) has a tendency to become a tangled mess. And, if we want to replace a ball, or change the nature of it in some way (size, colour, for example), then this may have a knock-on effect on all the balls (modules), so we have to examine (test) these to ensure they are still ok. In short, a highly-coupled system is BAD!

As it turns out, DRY, and the principle of reuse can actually lead to more tightly coupled systems. Consider and contrast two distinct are areas of a financial system. One is concerned with keying new client informations and the other with the provision of management information. These are two areas that are largely unrelated. If we consolidate all their common functionality, then we tie them closely together. If we then modify this common functionality in future, then we have to test two different areas.

So, like almost any other principle in programming, it turns out that DRY is a trade-off and a compromise. They key is context. Sometimes duplication is a mere coincidence, and by retaining it we allow independent areas of the system to mature and evolve independently while limited the bonds that couple it. Sometimes, WET (Write-Every-Time) really is better than DRY!

Leave a Reply