The DRY (Don't Repeat Yourself) Principle states:
If you sincerely apply these two principles you will be forced to learn, discover or invent many common design patterns such as inheritance, template method, visitor, decorator, etc. You may need to use code generation or declarative programming, and you will get lots of practice refactoring.
If you repeatedly repeat yourself you will eventually be confronted with a thicket if impenetrable code. There is little more frustrating that poring over two nearly identical subroutines and wondering if the differences are necessary and intentional or historical accident. Or perhaps one has a bug and the other has been fixed.
Once and Only Once is much easier to apply as you write code than after the fact. It is very difficult to tease together two similar functions.
So when you consider copying a bit of code, think about how you could avoid the copy. Maybe you could extract a method with the duplicated code, perhaps with an extra parameter to distinguish two cases. Maybe you should make a template method and subclass to account for the differences. Sometimes a collection of methods need to be shared with some local state. In this case you can extract a method object to compute the overall result.
If you keep this principle in mind as you code it will help you keep your code supple and useful so it may live long and prosper.
last change 2004-04-24 17:30:40
Don't Repeat Yourself is the cornerstone of good development.
© 2004, Kent Johnson