02 December 2012

DRY (Do not repeat yourself) design principle

As a software developer when we are working on a project, the natural tendency is to Create logic whenever and wherever we want. i.e. we duplicate the same code all across the project.

The disadvantage of repeating the same code is maintenance overhead in terms unit testing the code, defects fixing, etc. and also not but not least, the size of the code base grows bigger!!!, which we don’t want.

So, don't repeat the same code. That is what DRY principle says.

DRY principle article with an example:


Problem statement:

In one of the windows application project we had a requirement to put the cursor to the next/previous control On the form with the Down arrow/up arrow keys. This was got assigned to a naive developer. This windows application project was being developed on .NET 3.5; to achieve this behavior we had to write code for this.

The naive developer started coding. He got the required functionality of changing the control focus with the Down/up arrow keys but only for the single form. He had spent a day of effort for the same. The windows form application had over 30 forms. So he might need another 30 days to achieve the functionality across All the forms in the windows application.

Definitely that is not acceptable.

Solution by using the DRY principle:

Here the behavior expected is the same for all the 30 forms in the windows application project. Can we not move create a code which a single place and which will be applicable in all the places?

Yes. Definitely we can do that. Let's see how DRY principle helps:

  1. By making use of the inheritance we can achieve this. Create a class which derives from the System.Windows.Forms.Form Class
  2. Move all the code for achieving the desired functionality into it. And derive all the 30 forms in the app from the base class.

Here by following DRY principle helps to reduce the time required to get the functionality and future changes will be applicable to all the forms by making changes in just one place. So don't duplicate the code in your project. Always try to write a code in reusable manner, so that it can be applied in different places.

If you are adding new code, check you are not violating DRY principle:

  • The new code is not already exist anywhere in the project. If exists, reuse it.
  • If the new code is not already exist, make sure you write it in a reusable manner.
  • No comments:

    Post a Comment