Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
roth_stephan_clean_c20_sustainable_software_development_patt-1.pdf
Скачиваний:
25
Добавлен:
27.03.2023
Размер:
7.26 Mб
Скачать

Chapter 4 Basics of Clean C++

I think it is pretty obvious that using the same name for different purposes can be puzzling and can mislead readers. Don’t do that. That’s all I have to say about that topic.

Comments

“If the code and the comments disagree, then both are probably wrong.”

—Norm Schryer, Computer Scientist and Division

Manager at AT&T Labs Research

Do you remember your beginnings as a professional software developer? Do you still remember the coding standards of your company during those days? Maybe you’re still young and not long in business, but the older ones will confirm that most of those standards contained a rule that professional code must always be properly commented. The absolutely comprehensible reasoning for this rule was so that any other developer, or a new team member, could easily understand the intent of the code.

On first sight, this rule seems like a good idea. In many companies, the code was therefore commented extensively. In some projects, the ratio between productive lines of code and comments was almost 50:50.

Unfortunately, it was not a good idea. On the contrary: This rule was an absolutely bad idea!

It is completely wrong in several respects, because comments are a code smell in most cases. Comments are necessary when there is need for explanation and

clarification. And that often means that the developer was not able to write simple and self-explanatory code.

Do not misunderstand: there are some reasonable use cases for comments. In some situations, a comment might actually be helpful. I present a few of these rather rare cases at the end of this section. But for any other case, this rule should apply, and that’s also the heading of the next section: “Let the Code Tell the Story”.

Let the Code Tell the Story

Just imagine watching a movie that’s only understandable when individual scenes are explained using a textual description below the picture. This film would certainly not be a success. On the contrary, the critics would pick it to pieces. No one would watch such a bad movie. Good films are therefore successful because they tell a gripping story only through the pictures and the dialogues of the actors.

77

Chapter 4 Basics of Clean C++

Storytelling is basically a successful concept in many domains, not only in film production. When you think about building a great software product, you should think about it as telling the world a great and enthralling story. It’s not surprising that Agile project management frameworks like Scrum use phrases called “user stories” as a way to capture requirements from the perspective of the user. And as I’ve explained in a section about preferring domain-specific names, you should talk to stakeholders in their own language.

Note  Code should tell a story and be self-explanatory. Comments must be avoided whenever possible.

Comments are not subtitles. Whenever you feel the desire to write a comment in your code because you want to explain something, you should think about how you can write the code better so that it is self-explanatory and the comment is therefore superfluous. Modern programming languages like C++ have everything that’s necessary to write clear and expressive code. Good programmers take advantage of that expressiveness to tell stories.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

—Martin Fowler, 1999

Do Not Comment Obvious Things

Once again, we take a look at a small and typical piece of source code that was commented extensively. See Listing 4-12.

Listing 4-12.  Are These Comments Useful?

customerIndex++; // Increment index

Customer* customer = getCustomerByIndex(customerIndex); // Retrieve the

customer

 

at the given index

CustomerAccount* account = customer->getAccount();

// Retrieve the

 

 

customer's account

account->setLoyaltyDiscountInPercent(discount);

// Grant a 10% discount

78

Chapter 4 Basics of Clean C++

Please don’t insult the reader’s intelligence! It is obvious that these comments are totally useless. The code itself is largely self-explanatory. They don’t add new or relevant information. Much worse is that these useless comments are a kind of duplication of the code. They violate the DRY principle discussed in Chapter 3.

Maybe you’ve noticed another detail. Take a look at the last line. The comment speaks literally of a 10% discount, but in the code there is a variable or constant named discount that is passed into the function or method setLoyaltyDiscountInPercent(). What has happened here? Remember the quote by Norm Schryer from the beginning of this section? A reasonable suspicion is that this comment has turned into a lie because the code was changed, but the comment was not adapted. That’s really bad and misleading.

Comments defy any quality assurance measure. You cannot write a unit test for a comment. Thus, they can become misleading and outright wrong very quickly without anyone noticing.

Don’t Disable Code with Comments

Sometimes comments are used to disable a bunch of code that should not be translated by the compiler. A reason often mentioned by developers for this practice is that one could possibly use this piece of code again later. They think, Maybe one day ... we’ll need it again.” What could happen then is that from time to time you’ll find a stone-old piece of code from ancient times, commented out and forgotten for years, as shown in Listing 4-13.

Listing 4-13.  An Example of Commented-Out Code

// This function is no longer used (John

Doe, 2013-10-25):

/*

 

 

double calcDisplacement(double t) {

 

 

const double goe = 9.81;

//

gravity of earth

double d = 0.5 * goe * pow(t, 2);

//

calculation of distance

return d;

 

 

}

 

 

*/

 

 

A major problem with commented-out code is that it adds confusion with no real benefit. Just imagine that the disabled function in the example in Listing 4-13 is not the

79