Code Principles

DRY Principle

Do you tend to repeat code over and over again? There are several important reasons besides DRY (Don’t Repeat Yourself) not to do so.

The DRY Acronym#

DRY stands for “don’t repeat yourself”. The DRY principle is one of the most important principles in software development, if not even the most important. Whenever you write or read code and find repetition in it, chances are high you or whoever planned it, didn't plan well enough.

What's the problem about code repetition?#

Code isn't static. When you write code twice you have to test it twice and if you have to change it afterwards you also have to change it twice, in fact we already got the four-fold effort to invest. There is also a large chance, you miss the second occurrence. Seriously, nobody can remind himself to every line or routine of code he wrote in a project, at least if it isn't an insanely small one.

There is a word for software that isn't changed: Hardware

Unknown author

In fact, redundant code is not only one of the most common causes for bugs, it's also the cause for unnecessary complex or at least long code. The DRY principle helps you to avoid these problems.

Example of duplicated code#

first_player_points = [2, 3, 0, 5]
second_player_points = [4, 1, 1, 2]
def get_score_for_first_player():
return sum(first_player_points)
def get_score_for_second_player():
return sum(second_player_points)

Whats wrong by changing this to:

player_points = {
1: [2, 3, 0, 5],
2: [4, 1, 1, 2]
def get_score_for_player(player_number: int):
points = player_points[player_number]
return sum(points)

I am aware that this is a rather simplified example and that the solution doesn't apply to every problem, but that's not the point. Fact is, by generalizing concepts and for example moving redundant code to functions you save time and spare potential bugs. If applied correctly it may also increase the readability of your code.

How to apply the DRY principle?#

There is no general concept that allows you to always spare repetition, but there are steps that may help you to minimize it.

Plan thoroughly #

By planing your program or software carefully you may identify patterns and generalized concepts in an early stage.

Review frequently #

Review your code frequently, or even better let someone else review your code (That will also ensure your code doesn't exceed a certain level of illegibility).

Use tools that support you #

Depending on how large your project is, it's nearly impossible to find repetition manually. But there are tools that allow you to find repeated code anyway. For instance PyCharm¹ offers a duplicates tool window that allows you to identify code repetition.