© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
V. SarcarSimple and Efficient Programming with C# https://doi.org/10.1007/978-1-4842-8737-8_3

3. Wise Use of Code Comments

Vaskaran Sarcar1  
(1)
Kolkata, West Bengal, India
 

Comments help you understand other people’s codes. They can describe the logic behind the code. But expert programmers are particular about comments and do not like to see unnecessary comments. This chapter provides case studies to help you decide whether to put a comment in your application.

Recap of Code Comments

It is a standard practice to use comments in your program. The C# compiler ignores the comments, but they can help others to understand your code better. Let us consider a real-life scenario. In a software organization, say a group of people are creating software for its customers. It is possible that after some years, none of these people work at the organization anymore. In such a case, someone needs to maintain the software and continue fixing the bugs for its customers. But it is difficult to understand a complex working mechanism if there is no explanation of the program’s logic. Comments are useful in such scenarios. These help us understand the code better.

In C#, you see the following type of comments:

Type 1: Single-line comments use a double forward slash (//). Here is a code segment that starts with a single-line comment:
// Testing whether 2 is greater than 1
Console.WriteLine(2 > 1);
Type 2: You can use multiline comments to comment on more than one line at a time. You use this to comment out a block of statements. Here is a code segment that starts with multiline comments:
/*
Now I use multi-line comments.
It spans multiple lines.
Here I multiply 2 by 3.
*/
Console.WriteLine(2 * 3);
Type 3: Documentation comments are special comments. You can create documentation for your code using this type of comment that contains XML text. There are two types: either they start with three slashes (///), often called single-line documentation comments, or they are delimited comments that start with a slash and two stars (/**). Here is a code segment that uses single-line documentation comments:
  /// <summary>
  /// <para>This is a custom class.</para>
  /// <br>There is no method inside it.</br>
  /// </summary>
  class Sample
  {
  }
Here is a code segment that uses a different form:
/**
 * <summary>
 * <para>This is another custom class.</para>
 * <br>It is also empty now.</br>
 * </summary>
 */
class AnotherSample
{
}

In the end, the key aim is the same: comments help others to understand why you write a piece of code.

POINTS IN A NUTSHELL
  • Comments are simple notes or some text. You use them for human readers, not for the C# compiler. The C# compiler ignores the text inside a comment block.

  • In the software industry, many technical reviewers review your code. The comments help them understand the program’s logic.

  • Developers can forget how the complex logic works after several months too. These comments can help them remember what the code does.

Initial Program

You know that when the C# compiler sees a comment, it ignores it. In demonstration 1, you can see a complete program with many different comments. Compile and run this program to ensure you see the expected output.

Demonstration 1

In this program, you calculate the area of a rectangle. Here is the complete demonstration:
Console.WriteLine("***Measuring the area of a rectangle.***");
Rectangle r = new (2.5, 10);
double area = r.Area();
Console.WriteLine($"The area of the rectangle is {area} square units.");
/// <summary>
/// This is the Rectangle class
/// </summary>
class Rectangle
{
    readonly double l; // length of the rectangle
    readonly double b; // breadth of the rectangle
    public Rectangle(double le, double br)
    {
        l = le;
        b = br;
    }
    // Measuring the area
    public double Area()
    {
        return l * b;
    }
}

Output

Here is the output:
***Measuring the area of a rectangle.***
The area of the rectangle is 25 square units.

Analysis

This program uses different types of comments to explain the code. These are not doing any harm to the program. Now the question is, are they necessary? You will find many people in the software industry who dislike comments. They believe that people without a programming background do not read your code, which is true. Normally, a programmer or a developer is the only one who reads your code. No one likes to read an unnecessary explanation if the code is easily understandable. Also, older comments can be misleading if you do not maintain them. My belief is that comments are good if they are necessary. I dislike unnecessary comments, and I like to remove them if my code is expressive enough.

Better Program

Can you rewrite the program in demonstration 1 without comments? Yes, you can. You can delete all these comments at any time. Then you compile and run the program to confirm the same output. But the question is: when you do that, will your code be readable? Can a person understand it easily? Let’s take a look at demonstration 2.

Demonstration 2

Here is demonstration 2. It is a modified version of demonstration 1 and produces the same output. What are the changes? Notice that I have renamed the variables and the area method inside the Rectangle class. These new names are expressive enough. Anyone who reads this code should have a better idea about what I’m trying to do.
Console.WriteLine("***Measuring the area of a rectangle.***");
Rectangle rectangleObject = new(2.5, 10);
double area = rectangleObject.RectangleArea();
Console.WriteLine($"The area of the rectangle is {area} square units.");
class Rectangle
{
    readonly double length;
    readonly double breadth;
    public Rectangle(double length, double breadth)
    {
        this.length = length;
        this.breadth = breadth;
    }
    public double RectangleArea()
    {
        return length * breadth;
    }
}

Analysis

This demonstration is easy to understand. Did you notice that this time I chose variable names such as length and breadth? But in demonstration 1, I used an l (a lowercase L, not 1) and b, respectively. To let others understand this code, I needed to write the inline comments such as // length of the rectangle or // breadth of the rectangle. In this context, though it is easy to read, this type of comment can create confusion if you read this code on a device that has a smaller display. Microsoft (see https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions) also recommends not putting a comment at the end of a line. It suggests putting a comment always on a separate line.

But, when you choose a method name such as RectangleArea(),one can presume what this method is about to do, and as a result, you do not need to write additional comments for it. A similar type of method name is useful if you work on areas of different shapes such as circles, squares, or triangles.

POINTS TO REMEMBER
Here are Microsoft’s guidelines for the proper use of comments. In practice, we often violate this in a demo application, but these suggestions are helpful when you write enterprise code:
  • Begin comments with an uppercase letter and end with a period.

  • Place comments on a separate line, instead of putting them at the end of lines of code.

  • There should be a space between the comment delimiter (//) and the comment text. Here is a sample:

// This is a sample comment.
  • Avoid creating formatted blocks of asterisks around comments.

  • You need to assure that the public members have the necessary XML comments to describe their behavior. (I admit that I am often lazy about this, particularly when the behaviors of a type are simple and easy to understand.)

Use the Power of C#

Sometimes you see some comments that appear very helpful at the beginning. The following code shows a TODO comment saying that you do not intend to use the SayHello() method in the future. It suggests using the SayHi method starting with the next release.
class Sample
{
    readonly string name = "Reader";
    // TODO-We'll replace this method shortly.
    // Use SayHi() from the next release(Version-2.0).
    public void SayHello()
    {
        Console.WriteLine($"Hello, {name}!");
    }
    public void SayHi()
    {
        Console.WriteLine($" Hi, {name}!");
        Console.WriteLine("This is the latest method.");
    }
}
This TODO comment seems to be easy to understand and useful. Now see some sample client code that uses these methods:
Console.WriteLine("Dealing with TODO comments.");
Sample sample = new ();
sample.SayHello();
sample.SayHi();

This client code is also simple. There is nothing special in this code. Think about it from a company perspective now. A company does not share the actual code with its clients. Instead, the company tells the client how to use the functionalities of the application. But how will the client know that he needs to use SayHi() starting with version 2.0? One way is to include this information in the user manual. But there is an alternative approach too. You can use the power of attributes. This is better in the sense that human behavior often resists the changes. If they can do the work using an old method, it is very much likely that they are too lazy to test the new method. So, I’ll show you a better alternative now. Notice the Sample class that uses an attribute, called Obsolete, to indicate that SayHello() should not be used in the upcoming development work.

Demonstration 3

Here is the complete program:
Console.WriteLine("Dealing with TODO comments.");
Sample sample = new ();
sample.SayHello();
sample.SayHi();
class Sample
{
    readonly string name = "Reader";
    [Obsolete("This method is obsolete. Use SayHi() instead.")]
    public void SayHello()
    {
        Console.WriteLine($"Hello, {name}!");
    }
    public void SayHi()
    {
        Console.WriteLine($"Hi, {name}!");
        Console.WriteLine("This is the latest method.");
    }
}

Analysis

Now the same client code will notice that the SayHello() method is obsolete. The clients also get the information that they should use SayHi() instead of this old method. Figure 3-1 shows a snapshot of the Visual Studio IDE, which gives you the idea.
Figure 3-1

The SayHello() method is obsolete

Summary

The book Clean Code (Pearson) by Robert C. Martin tells us the following: “Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration.” This book continues, “Every time you express yourself in code, you should pat yourself on the back. Every time you write a comment, you should grimace and feel the failure of your ability of expression.” Another great book is The Pragmatic Programmer by Andrew Hunt and David Thomas that tells us: “Programmers are taught to comment their code: good code has lots of comments. Unfortunately, they are never taught why code needs comments: bad code requires lots of comments.”

You may not always agree with these thoughts, but you will find people who can point to pros and cons on both sides of the issue. Even these books show some examples of both good and bad comments.

There are plenty of examples where the actual code is tricky or difficult to understand. Some good, well-maintained comments can help a first-time reader/developer. For me, when I hover my mouse over a built-in function, a comment helps me to understand the method better. In this book, I have generated some random numbers in many examples. There are overloaded methods to do this activity. For example, I often use the following form:
// The previous code is skipped
Random r = new();
r.Next(12);
The associated comments are straightforward for me to understand how this method works. The following built-in comments are associated with this particular version of the Next method:
//
// Summary:
//     Returns a non-negative random integer that is
//     less than the specified maximum.
//
// Parameters:
//   maxValue:
//     The exclusive upper bound of the random number
//     to be generated. maxValue must
//     be greater than or equal to 0.
//
// Returns:
//     A 32-bit signed integer that is greater than or
//     equal to 0, and less than maxValue;
//     that is, the range of return values ordinarily
//     includes 0 but not maxValue. However,
//     if maxValue equals 0, maxValue is returned.
//
// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     maxValue is less than 0.
public virtual int Next(int maxValue);

This is the reason I suggest you stop and think before you place a comment in your code. Use them when they are truly beneficial. You can get a better idea of this when your code goes through peer reviews.

Note

This is nothing worse than a line of commented code that references a method or variables that are no longer in use. It can also cause trouble when you use a comment that does not stay close to the actual code. You may even see comments that give you incorrect information. At any cost, you should not allow bad or unnecessary comments to remain in your application.

Finally, comments are not always used to describe the code. You may see commented-out code in an application too. Keeping commented-out code is not a recommended practice; however, I use some commented-out code in my books for further demonstration purposes. For example, I may point out an alternative way of calling a method. Sometimes I keep the commented-out code with potential output to show you correct or incorrect behavior. But following the experts’ suggestion, I do not like to see unnecessary commented code in an enterprise application. This is because, if needed, you can always track down the old code from a source code version management tool such as Git or SVN.

In short, this chapter discussed the following questions:
  • What are code comments?

  • What are the different types of comments?

  • Why are good comments beneficial?

  • Why are unnecessary comments bad, and how can you avoid them?

  • How can you avoid specific plain comments using C# language features?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.124.177