Write clean code instead of comments

Of course comments help to understand code. They are an essential part of the source code. But comments are an addition only. If you want to create readable and easy to understand source code, you have to focus on the code itself. An obscure implementation cannot be rescued by comments.

But how can we see whether a comment is a helpful addition to the source code or a helpless try to explain bad code. I think there are two main types of comments: the ones explaining “why” something is implemented in this way and the ones explaining “what” is implemented.

A good comment adds additional information to the source code and therefore explains the “why”. Bad comments instead explain “what” is implemented. Without these comments the source code is very hard to understand.

But how can we avoid bad comments and the bad source code they try to explain?

Every time we write a comment we shall ask ourselves: do we explain “what” or “why” we have implemented the code. If the comment explains “what” we have implemented we must try to refactor the source code. In such cases the source code shall be changed to self-explaining code which makes the comment obsolete.

int sellerIdentifier = 15;

//check whether the list of all sales of the seller contains the last sale

The comment within the example explains what the source code shall do. The source code itself is hard to read. Without the comment and even with the comment you have to read it several times to understand its behavior.

If you write such code and add the comment, you have to slow down for a moment and think whether the comment explains what the code does or why it is implemented. In this case the comment explains what the code does. So you should think about a possible refactoring. In this case you can remove the comment by using variables. Following you will see a possible refactoring result.

int sellerIdentifier = 15;

List<int> sales = procuctManager.GetAllSales(sellerIdentifier);
int lastSale = procuctManager.GetLastSale();


As you can see the second version of the source code does not need the comment anymore. Instead you may add a new comment and explain why this function is executed.


Comments are no substitute for bad code. Bad code stays bad code even if you write a detailed comment explaining each detail. It’s better to spend the time in a refactoring of the bad code then writing long comments.

Dieser Beitrag wurde unter .NET, C#, Clean Code veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:


Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )


Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s