Don’t repeat yourself principle

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Continuing on our articles about object oriented design principles, we will look into don’t repeat yourself principle.


Don’t Repeat Yourself

Don’t repeat yourself design principle is about abstracting out common code and putting it in a single location. It discourages repetitive code. It is about putting one requirement at one piece only. It helps us avoid maintenance jargon. Let us see Don’t repeat yourself principle in an example.

Consider a Mechanic class which services cars and bikes.

Notice that there are two methods serviceCar() and serviceBike(). The mechanic services bikes according to their own method. Nothing strange about it.

Now consider the workshop is offering you other services, the mechanic will wash your bike and then service, he is also offering to polish vehicles in the service itself.

Now we have to update the code for serviceCar() and serviceBike() also

Now what is the problem here? Whenever some procedure changes, methods serviceCar and serviceBike also change. There is code duplication, one piece of code is repeating for same purpose. Here comes the application of don’t repeat yourself principle. It states to abstract out the code that is being duplicated. So we can write a separate method that performs the tasks which mechanic offers other than servicing.

Now you have created a method performOtherTasks() by applying don’t repeat yourself principle.   serviceCar() and serviceBike() simply call it. Now whatever changes the workshop offers in service package, they can be included in the same method. That code need not replicate in serviceCar() and serviceBike(). Thus it makes code more cohesive and maintainable.

I hope this brief example helped understand the don’t repeat yourself principle


Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *