How duplication insidiously invade our code

Duplication is probably the #1 enemy of clean code. Its presence make the code harder to maintain, harder to evolve, more bug prone, harder to test and probably eat babies every morning. If almost any developer will agree on that fact, me can also notice that almost every codebase is crippled with repetitions in the code. How could we explain that ?

How do duplication appears

I’ll put aside on this post the fact that many developer have no clue how to do their work, and don’t really care about duplication. They usually are not aware of the fact that they are preparing hell for themselves, and they will succeed faster than they may think.

No, I want to talk here about serious programmers. Because they tend to have repetition in their code too. Doing some code review, things become pretty straightforward. Hell hide itself in details.

Consider the small sample code below :

1
string output = online?lang("online"):lang("offline");

Notice something ? yes we do have repetition here. We absolutely don’t need the call to lang to be repeated. Here are some correct forms for such a code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string output = lang(online?"online":"offline");

// Or

string label = online?"online":"offline";
string output = lang(label);

// Or

string label;
if(online) {
    label = "online";
} else {
    label = "offline";
}

string output = lang(label);

As you see solutions are variable and depend on your style. Why is it such a big deal ? Simply because code tend to start small and then get bigger and bigger. In our case, the operation that we want to do depending if we are online or offline may not be just seting a string. And so the duplication tend to become more and more important overtime, by small details like this, and can ends up really killing the cleanness of the source code.

Beware of duplication, they are hiding in details and ends up being pretty significant at the end.

Leave a Reply

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