Python Rocks! and other rants
Weblog of Kent S Johnson

2004-04-24 17:30:40

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., 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.

 
© Kent S Johnson Creative Commons License

Comments about life, the universe and Python, from the imagination of Kent S Johnson.

kentsjohnson.com

Weblog home

All By Date

All By Category

Essays

XML-Image

BlogRoll