/* Comments */


Link to this posting

Postby Ursego » 21 Feb 2013, 15:31

Clarify your code with comments if it is not absolutely straightforward.

Sprinkle your code with relevant comments explaining what the code is supposed to accomplish. Comments should help the reader over the difficult spots. Thy will not only help other developers to understand your code, but will also be very useful for yourself: investigating a production issue after many years, will you remember what your tricky code does?

Comments as a red flag

When a comment becomes too involved, ask yourself whether the code itself is at fault. Even if bad code is explained, it remains bad. I remember a couple of cases when I wrote a whole story as a comment, and that forced me to look critically on my code and to re-organize some methods, making the module simpler. The lesson I learned: too many comments can signal, that I do things in a more complicated way, than possible.

Use comments as headers of different code fragments to visually divide them.

While your inline comments should assist the next developer in fixing or extending your code, your header comments should give any programmer enough information to use the code fragment without having to read it.

Comments as a skeleton :o

Comments can help you not only understand existing methods, but also write new ones: just after creation of a new function, write a comment before each future code fragment which will perform a different logical task (as if you would comment an existing code), and AFTER THAT begin to write executed code. Below is an example of an initial skeleton (built of comments!) for a function which calculates a new balance for a customer (also pay attention that we can avoid the articles "the" and "a" in the comments - that shortens them):

Code: Select all
private float calcNewBalance (int customerID, float amountToAdd)
   {
   // Validate parameters:
   
   // Retrieve existing balance of customer:
         
   // Retrieve their allowed overdraft:
         
   // Calculate new balance:
         
   // If it exceeds allowed overdraft then return original balance:
         
   // If this code reached then new amount is ok - return it:

   }

An that moment it's easier to concentrate on the "upper-level logic" - you simply describe what the function is doing using the regular human language. After the "comments skeleton" has been created, start writing executed code (each fragment just after its corresponding comment).This method decreases chances of having to re-write code.

Don't leave comments if they are not absolutely necessary.

Write as little comments as possible. As the first sentence of this topic says, Clarify your code with comments if it is not absolutely straightforward - not always you have time. :lol: Too many comments are so noisy that we learn to ignore them. As we read through code, our eyes simply skip over them. Comments even can begin to lie if the code around them changes.

Don't use comments as a substitution for well-named variables and methods, and for correct methods organization.

Name a variable daysAferLastPurchase (rather than days); call a method getFilterBySelectedRowInSummaryScreen() (rather than getMainFilter()). So, when you use them, you don't need to explain what the fragment does (see Give exact names which clearly reveal intent).

Put results of a complicated expression in a well-named Boolean variable rather than explain in a comment what that expression calculates (see Short conditions in IFs).

Before writing a header comment to visually mark a code fragment, consider refactoring that fragment into a new well-named method (see Keep functions simple).

The best comment is the comment you found a way not to write!

Don't just echo the code with comments.

Make every comment count. I saw comments like 'Declare variables:' just before a variables declaration section and 'Call function XXX:' just before calling function XXX ! :x These comments are nothing but noise. They restate the obvious and provide no new information.

Image.
User avatar
Ursego
Site Admin
 
Posts: 128
Joined: 19 Feb 2013, 20:33

Link to this posting

Postby Ursego » 03 Jul 2019, 12:20

From the book "Clean Code":

Explain Yourself in Code

There are certainly times when code makes a poor vehicle for explanation. Unfortunately, many programmers have taken this to mean that code is seldom, if ever, a good means for explanation. This is patently false. Which would you rather see? This:

Code: Select all
// Check to see if the employee is eligible for full benefits
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))

Or this?

Code: Select all
if (employee.isEligibleForFullBenefits())

It takes only a few seconds of thought to explain most of your intent in code. In many cases it's simply a matter of creating a function that says the same thing as the comment you want to write.

From the book "97 Things Every Programmer Should Know":

Comment Only What the Code Cannot Say

The difference between theory and practice is greater in practice than it is in theory - an observation that certainly applies to comments. In theory, the general idea of commenting code sounds like a worthy one: offer the reader detail, an explanation of what's going on. What could be more helpful than being helpful? In practice, however, comments often become a blight. As with any other form of writing, there is a skill to writing good comments. Much of the skill is in knowing when not to write them.

When code is ill-formed, compilers, interpreters, and other tools will be sure to object. If the code is in some way functionally incorrect, reviews, static analysis, tests, and day-to-day use in a production environment will flush most bugs out. But what about comments? In The Elements of Programming Style (Computing McGraw-Hill, PDF), Kernighan and Plauger note that "a comment is of zero (or negative) value if it is wrong". And yet such comments often litter and survive in a codebase in a way that coding errors never could. They provide a constant source of distraction and misinformation, a subtle but constant drag on a programmer’s thinking.

What of comments that are not technically wrong, but add no value to the code? Such comments are noise. Comments that parrot the code offer nothing extra to the reader - stating something once in code and again in natural language does not make it any truer or more real. Commented-out code is not executable code, so it has no useful effect for either reader or runtime. It also becomes stale very quickly. Version-related comments and commented-out code try to address questions of versioning and history. These questions have already been answered (far more effectively) by version control tools.

A prevalence of noisy comments and incorrect comments in a codebase encourages programmers to ignore all comments, either by skipping past them or by taking active measures to hide them. Programmers are resourceful and will route around anything perceived to be damage: folding comments up; switching coloring scheme so that comments and the background are the same color; scripting to filter out comments. To save a codebase from such misapplications of programmer ingenuity, and to reduce the risk of overlooking any comments of genuine value, comments should be treated as though they were code. Each comment should add some value for the reader, otherwise it is waste that should be removed or rewritten.

What then qualifies as value? Comments should say something code does not and cannot say. A comment explaining what a piece of code should already say is an invitation to change code structure or coding conventions so the code speaks for itself. Instead of compensating for poor method or class names, rename them. Instead of commenting sections in long functions, extract smaller functions whose names capture the former sections’ intent. Try to express as much as possible through code. Any shortfall between what you can express in code and what you would like to express in total becomes a plausible candidate for a useful comment. Comment what the code cannot say, not simply what it does not say.
User avatar
Ursego
Site Admin
 
Posts: 128
Joined: 19 Feb 2013, 20:33




IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
free counters

eXTReMe Tracker