Don't Repeat Yourself

Don't Repeat Yourself and its special case Once and Only Once are two of the most important principles of good development.

The DRY (Don't Repeat Yourself) Principle states:

''Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.''

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

April 2004
    1 2 3 4
5 6 7 8 91011

Don't Repeat Yourself is the cornerstone of good development.

XML-Image Letterimage


© 2004, Kent Johnson