Functions – The DRY Principle

A very important lesson that every programmer has to learn at some point, is that duplication is bad. This is what the DRY Principle addresses.

What is duplication?

Simply put, duplication is having lines of code in your application, that are repeated in multiple places. Whenever you copy and paste a snippet of code, you are very likely guilty of duplication.

Why duplication is bad

One of the problems that comes from having duplication in your code is that it gets bloated. Copying and pasting code can get out of hand very quickly.

The main reason that duplication is something you want to avoid, is that it makes maintaining your code very difficult. Whenever you need to modify your code, you have to track down all the places where that code has been duplicated and make the changes for all the duplications. This is very time consuming and requires you to have a deep knowledge of the entire system. If you have a lot of duplication, it is probable that you will miss one or more of them. This will cause bugs  in your code that are very hard to track down.

The DRY Principle

DRY stands for “Dont Repeat Yourserlf”

The formal definition for the DRY principle is:

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

Another way of explaining is to say that your program shouldn’t have two or more blocks of code that all do the same thing.

Functions help us keep our code DRY

Functions allow us to keep our code DRY, because we encapsulate the logic inside the function. This way when we need our code to do something more than once, instead of copying the code, we call the function instead. This helps prevent code bloat.

DRY Code is easier to modify

Modifying the code also becomes a lot easier. If we want to change the behavior of a certain functionality in our program, we just need to modify the function that implements it. All the places in our program that call the function will automatically have been “updated”. There is no need to search all our code base to modify anything else.

 

Leave a Reply