I know we all reuse code and some types of reuse are better than the others (I'm looking at you COPY AND PASTE / man in the mirror), but copy-paste is only a symptom of a larger issue, that WET code is not as easy to maintain as DRY code.
Don't Repeat Yourself (DRY) code aims to reduce code repetition. We do not want to reinvent the wheel, but worse is having bad versions of the wheel scattered everywhere. The goal of DRY code is to refactor so that you only have one reusable instance of that code, and if you need to change it, you can do so in one place. It is easier to maintain and update. DRY code also reduces the chance of error since you are only updating one place instead of several. We have all used DRY code when we have used loops, functions, or includes.
Write Everything Twice (WET) code is the opposite of DRY code. It is where you have duplicate code copy/pasted, or rewritten several times in multiple places. Sometimes WET code is DRY code that needs minor changes, but you make a copy of it. If it is a simple change, it might be ok to add it to your DRY code, but sometimes it's better not to over-engineer things. DRY code is the goal in most cases, and the benefits will outweigh the costs.
The biggest benefit of using DRY code is maintainability. Fixing bugs in one location is easier than remembering and finding all the occurrences of that logic. Likewise, updating the business logic or adding functionality is easier when the code is shared.
An Acronym used with DRY code is FIRST, which stands for Focused, Independent, Reusable, Small, and Testable (https://addyosmani.com/first/)
Programs must be written for people to read, and only incidentally for machines to execute - Harold Abelson
If a developer understands the principles of DRY code, they are more likely to understand clean code principles, leading to more readable code. Code reuse usually encourages smaller, more manageable functions, promoting lower cognitive load and making the code more readable.
DRY code is broken down into smaller pieces and is usually easier to test. The more code you have and the more paths and functions to cover, the harder it will be to test. Using DRY Code from libraries and frameworks means more eyes on it, and sometimes those libraries and frameworks have tests for their code already.
- More code takes more time and money
- Reinventing the wheel takes more time and money
- Maintaining more takes costs more time and money
- Testing more code takes more time and money
- Fixing more bugs takes more time and money
We need fast and simple ways to share code in a project and between projects. We are lucky in ColdFusion in that we have lots of techniques and tools to help us write DRYer code. Check back for our next blog entry, where we go into more detail.