Comments

How often do you use comments in your code?

In the last two posts I talked a bit about what is clean code and how to use variables and write clean functions – lets remember last week’s example (from Clean methods):

bool isListEmpty(List<string> text)
{
       if (text.Count() == 0)
              return true;

       return false;
}

I, personaly, don’t think that in the above example any comment is needed – and that because the whole function is pretty straightforward. Any comment would’ve been more than needed – and why would we make our life harder by doing so?

When writing code you should not repeat yourself.

This is why a comment like: /* checks if a List is empty */ is not needed above.

  • Question: Do you? Would you add a comment in the above function? Do you think it’s necessary? If so, explain why.

I believe no clean code should need comments.

There are obviously some exceptions that we will discuss later on.

Lets consider the following example:

// MUSIC or Instance
class Program
{
       public static const int y = 10;
       private bool physF;
       private string age;
       public int aYears;

       // is under + yearsInterval time?
       public static bool still(int age)
       {
              var year = DateTime.Now.Year;
              if (age + y <= year)
                     return true;

       // is not
       return false;
       }

       . . .
}

First of all – do you understand anything? I suppose not – that code is awful. But lets clean it up a bit:

class MusicEra
{
       public static const int yearsInterval = 10;
       private bool physicalFormat;
       private string age;
       public int activeYears;

       public static bool stillInThisAge(int year)
       {
              var currentYear = DateTime.Now.Year;
              if (year + yearsInterval <= currentYear)
                     return true;

              return false;

       }

       . . .
}

It can be seen that no comments are needed here anymore. [I won’t explain why or how I did cleaned the above code – if you missed my first posts you can find them here which continues with a link at the bottom of the page]

But still, what’s the difference between these two examples? (The one from the beggining and the above one) That is that the last comments were terrible – misleading, wrong and again misleading.

That is because they didn’t have any meaning – the only thing they do is get missinterpreted by the reader, making the understanding of the code a lot harder. Also, they are innacurate and have absolutely no relevance.

Again, do we have to use comments?


 

Programmers are generally smart people – they know how to think a problem through, they know (at least) a programming language to solve it in and also can come to such a level where their code won’t need comments to be understood.

Instead of doing your best to write explicit and sugestive comments, devote into making your code clear, easy to understand, explicit and suggestive.

Only code can (and should) tell you what it does.

 

Also, why waste important lines with comments? Write functions instead!

When you want to describe what a function’s steps does better break those steps in other functions more suggestive.

Use constants. Use define statements.

Ok, obviously you can’t write a function for everything. (I mean, you can, but.. it’s not so stylish)

Lets have another example:

 

protected void getInformations()
{
       string inputMusicYear;
       int musicYear;

       bool isEightes = false, isNinetes = false, isTwenties = false;
       List<string> givenEraMusic = new List<string>();

       // prints message
       Console.Write("Type a year: ");

       // gets input
       inputMusicYear = Console.ReadLine();
       musicYear = Int32.Parse(inputMusicYear);

       // prints new line
       Console.WriteLine();

       // if the year is in the 80s list
       if (musicYear < 1990 && musicYear >= 1980)
              isEightes = true;

       // if the year is in the 90s list
       if (musicYear < 2000 && musicYear >= 1990)
              isNinetes = true;

       // if the year is in the 00s list
       if (musicYear >= 2000)
              isTwenties = true;

       string message = "";
       // is the inputed year is in the 80s
       if (isEightes)
              givenEraMusic = eightesMusic;
       message += "in the 80s!";

       // is the inputed year is in the 90s
       if (isNinetes)
       {
              givenEraMusic = ninetesMusic;
              message += "in the 90s!";
       }

       // is the inputed year is in the 00s
       if (isTwenties)
       {
              givenEraMusic = twentiesMusic;
              message += "in the 00s!";
       }

       // print message to output
       Console.Write("Your year finds itself in the " + message+ " and the bands and songs from that era are: ");
       for (int i = 0; i < givenEraMusic.Count; i++)
              Console.WriteLine(givenEraMusic.ElementAt(i).ToString());
       Console.WriteLine();
}

 

Now that’s some function! Yet still the comments do seem pretty suitable, don’t they? The problem is I wouldn’t write a function like that. Why? Because 1. it is too long (52 lines) and 2. come on, why would I try to write about clean code principles if I wouldn’t apply them.

Notice that the comments only occupy 12 lines. This is how I would write this code:

protected string GetInput()
{
       Console.Write("Type a year: ");

       return Console.ReadLine();
}

protected int GetMusicYear(string input)
{
       return Int32.Parse(input);
}

protected string GetMusicalEra(int musicYear)
{
       if (musicYear < 1990 && musicYear >= 1980)
              return "80s";

       if (musicYear < 2000 && musicYear >= 1990)
              return "90s";

       if (musicYear >= 2000)
              return "00s";

       return "notFound";
}

protected string CreateMessage(int musicYear, string musicEra)
{
       string message = "Your inputed: " + musicYear.ToString();
       message += " year's music is found in the " + musicEra;

       return message;
}

protected void PrintMessage(string message)
{
       Console.WriteLine(message);
}

protected List<string> PrintAndReturnEraData(string musicalEra)
{
       List<string> givenEraMusic = new List<string>();

       if (musicalEra.Contains("80"))
              givenEraMusic = eightesMusic;
       if (musicalEra.Contains("90"))
              givenEraMusic = ninetesMusic;
       if (musicalEra.Contains("00"))
              givenEraMusic = twentiesMusic;

       for (int i = 0; i < givenEraMusic.Count; i++)
              PrintMessage(givenEraMusic.ElementAt(i).ToString());

       return givenEraMusic;
}

protected void getInformations()
{
       int musicYear;
       string message = "";
       List<string> givenMusicalEraData = new List<string>();

       string musicYearFromInput = GetInput();

       musicYear = GetMusicYear(musicYearFromInput);

       string musicalEra = GetMusicalEra(musicYear);

       message = CreateMessage(musicYear, musicalEra);
       PrintMessage(message);

       givenMusicalEraData = PrintAndReturnEraData(musicalEra);
}

That would be a total of 70 lines (counting brackets and new lines) – but notice the flow of the code: you can tell what it does only by looking at the functions’ headers. Beautiful.

You might think now: “ok, what about Copyright and name headers? Am I suppose to name my function after me?”

Of course not – there are permitted comments – you are often asked to customize your code or you have to give copyright (C) rights. These are good comments.

Other examples of good comments are the ones that summarize mathematical formulas or give meaning to printing or various types.

Others… mostly are bad comments – so do try to avoid them as much as you can. You will see how your code writing techniques as you will write it cleaner and clearer so that no comments are needed.

 

For closing, I will add some comment patterns I like to use for files’ headers:

/**
* Function's use
* [other valid information]
* @parameters 
* @return
*/

/* • parameters:
- parameter1 - using hints;
- parameter2 - using hints;
- ...
• function's use hints
*/

//-------------------------------------------------------------------------------------------------
// Description
//
// Author: <first name> <second name>
// Date: mm-dd-yyyy
//-------------------------------------------------------------------------------------------------


 

 

Leave a Reply

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