This is the 30th Step towards gaining the Programming Enlightenment series. If you didn’t learn the 29th Step, read it.
What is Don’t Repeat Yourself (D.R.Y)?
The DRY principle is stated as “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system” as stated in The Pragmatic Programmer.
DRY principle is aimed at reducing repetition of software patterns, replacing them with abstractions; and several copies of the same data, using data normalization to avoid redundancy.
Why don’t duplicate?
Every duplicate line into application needs to be maintained. If a potential source of bugs appear, it would have to be fixed in all of those duplicates.
It bloats the codebase making it much more difficult for developers to fully understand the entire system.
SOLID principle relies on DRY principle.
How to remove duplication?
- Copy-and-paste coding usually litters the repetition, we can use different design pattern to avoid duplication like Factory Pattern, Strategy Pattern etc.
- IDE are powerful to detect duplicate codes and one can extract them to a common method.
- Use static analysis tools like PMD to detect duplicate lines.
TL;DR Follow DRY principle don’t WET code.
Go to 29th Step
Go to the 31st Step.
References:
- 97 things Every Programmer Should Know ~ Git Book
- 97 Things Every Programmer Should Know ~ Paperback
- DRY~ Wiki