Why not comment on the code?

Asked

Viewed 694 times

21

After reading a bit of Robert C. Martin’s Clean Code, he says that it is no use to "make up" a bad code with comments, in other words, try to explain a gambit made there.

It is also quoted about explain what you want to do in your code with your code and don’t use comments for it.; followed by the example that this:

if (employee.isEligibleForFullBenefits())

is better than this:

// Verifica se o empregado é elegível aos benefícios
if ((employee.flags & HOURLY_FLAG)
     && (employee.age > 65)) 

In addition to this answer, where it is written as write code clean and easy to maintain, the code below:

public bool ValidacaoCPF(int[] cpf)
{
    int DV1 = 0, DV2 = 0, aux = 10;

    if (!cpf.All(x => x == cpf.First())) //Verifica se todos os números são iguais
        if (cpf[9] == ((DV1 = (cpf.Take(9).Sum(x => (x * aux--)) % 11)) < 2 ? 0 : 11 - DV1)) //Cálculo do primeiro digito verificador
            return cpf[10] == (((aux = 11) * 0) + (DV2 = (cpf.Take(10).Sum(x => (x * aux--)) % 11)) < 2 ? 0 : 11 - DV2); //Cálculo do segundo digito verificador

    return false;
}

Became that:

if (!cpf.All(x => x == cpf.First())) //Verifica se todos os números são iguais

    //Cálculo do primeiro digito verificador
    if (cpf[9] == (
        (DV1 = (
            cpf.Take(9).Sum(x => (x * aux--)) % 11
        )) < 2 ? 0 : 11 - DV1
    )) 
    {
        //Cálculo do segundo digito verificador
        aux = 11;
        return cpf[10] == (
          (DV2 = (  cpf.Take(10).Sum(x => (x * aux--)) % 11  )) < 2 ? 
          0 : 
          11 - DV2);
    }

As far as I’m concerned, you’ve had almost no significant change, you’re just trying to explain something you wouldn’t understand if you didn’t have those comments there. Right then, it fits into a dirty code for me.

In other words, comments were used to explain something that we would understand now only by the existence of them there.

In short, do comments really dirty the code instead of cleaning it? Where should we use them and when should we avoid them?

Information taken from page 86 and 87 of the aforementioned book.

  • 1

    Comments are very useful for documentation, especially in weakly typed languages, for example, you can better explain what such a method is for and what it needs

  • 2

    One of the points he makes about the comments is that they tend not to be updated with the code changes, which makes them liars and mislead the reader. This would be one more factor to make only the really necessary comments and not go out commenting all that is line.

4 answers

22


Uncle Bob has a way of doing it and it may not be the right one for everyone, he has his context, you have yours and I have mine. You should find what’s best for you and your team. His books and a lot of people’s books are good to make you think, not to give cake recipes on how you code or develop software. His book is full of not very clear statements (this is more or less normal in everything you read) and it is up to you to interpret what is written or even to question whether it is really 100% valid, it is usually not as much as it is written, even if it is not a mistake.

This particular item is good advice, but it cannot be taken to the extreme, has case that you complicate the code too much to avoid comment.

If you follow another point of it which is to have small methods (he misses when he speaks in number of lines, he is naive) the code will be readable on other merits, will need few comments and will not need to be so descriptive (I’m not saying it doesn’t need to be descriptive). I’ll even show you in response to the question linked that often we do not stop to think that it has things very readable and little descriptive because we are very accustomed, the spirit of the thing is there. I also thought that the mgibsonbr code added very little, if it was to improve would have to make more abstractions and not more comments or break line. It may have gotten better, but not much.

There are cases where doing an abstraction (your first example) is better than writing the code that does what you want (your second example), but don’t take it for granted every time.

Have a question about How to know the right measure of comments?. I talk about anti-Pattern when it starts with too much information in the code. Everything has a reason, it’s not a silly invented rule.

I talk about the comment violating the DRY. Just be careful not to think that’s a rule.

Nomenclature can help make the code more described.

Techniques of scaffolding can help (abstraction without processing cost).

Choose the encoding style can help to have more correct and declarative codes.

But beware, too much abstraction, besides potentially slowing down the code, can hide important things. And it’s very easy to make the wrong level. You can’t even leak abstraction, nor exaggerate.

The basic rule is to comment on the why of things, which cannot be expressed in code, but not to exaggerate it. Just qualitative experience (no use making wrong for 20 years that this is not experience) makes you hit the point, not trying magic rule. That’s why it’s good to always have good mentors (it’s not coaching :D) but go guiding whether it is right or not in the specific case. The internet helps in this, but you have to be careful and create your own mindset little by little.

If you comment on what is really best expressed in dirty code yes.

7

There is no definite reason not to use comments. There are recommendations. You have to ask yourself if it’s really useful to put them on or if it’s just adding noise to the code that will generate more distraction than guidance.

Comments are available in all languages and are useful yes, but like everything, they should also be used sparingly.

The intention of the author to be contrary to the use of comments aims precisely to cause reflection. Do you really need to add this comment to explain the code? Do you really need to turn a chunk of code into a comment just so the compiler can ignore it without losing the old code history? And so on and so forth.

Most of the time it was better to have used good names, taken into account patterns and good practices, finally, thought a little more in architecture or modeling, than complicate a code and then try to explain through comments.

Examples like this:

// Verifica se o empregado é elegível aos benefícios
if ((employee.flags & HOURLY_FLAG)
     && (employee.age > 65)) 

They’re not bad for using comments, they’re bad for violating standards like DRY or Demeter’s Law. By exposing details of validation rules that are the responsibility of the object employee and that lead to duplication of code, as they would probably repeat themselves in more places where such validation was needed.

The second example given, in my opinion also contains Code Smells and would not need comments, as it is burdened with responsibilities, violating the first SOLID principle.

public bool ValidaCpf(int[] cpf)
{
    int DV1 = 0, DV2 = 0, aux = 10;

    if (!cpf.All(x => x == cpf.First())) //Verifica se todos os números são iguais

        //Cálculo do primeiro digito verificador
        if (cpf[9] == (
            (DV1 = (
                cpf.Take(9).Sum(x => (x * aux--)) % 11
            )) < 2 ? 0 : 11 - DV1
        ))
        {
            //Cálculo do segundo digito verificador
            aux = 11;
            return cpf[10] == (
                (DV2 = (cpf.Take(10).Sum(x => (x * aux--)) % 11)) < 2 ?
                0 :
                11 - DV2);
        }

    return false;
}

Being refactored could look like this:

public bool ValidaCpf(int[] cpf)
{
    return !saoTodosNumerosIguais(cpf) && digitoEhValido(cpf, 10) && digitoEhValido(cpf, 11);
}

private bool saoTodosNumerosIguais(int[] cpf)
{
    return cpf.All(x => x == cpf.First());
}

private bool digitoEhValido(int[] cpf, int posicao)
{
    int dv = 0;
    return cpf[posicao - 1] == ((dv = (cpf.Take(posicao - 1).Sum(x => (x * posicao--)) % 11)) < 2 ? 0 : 11 - dv);
}

The extent to which you want to go is subjective. But the lesson given by the book Clean Code is very good and is worth much for reflection. See, how much we reflect on the first code until we evolve it into "higher quality" models, easier to be tested unitarily while exercising our way of thinking about the generated solution, simply questioning the need to comment on the code!

6

One way I learned where I work is to make the name of the variables clear for what I want to do.

This already avoids many unnecessary comments.

Let me give you an example:

    foreach (var perfilDoUsuario in listaDePerfisDoUsuario)
            {
                if (perfilDoUsuario.Value.ToUpper().Contains((ListaDePerfisDoRelatorio.Gerente).ObterDescricao().ToUpper()))
                {
                    listaDeTiposDePerfis.Remove((int)ListaDePerfisDoRelatorio.Gerente);
                    listaDeTiposDePerfis.Remove((int)ListaDePerfisDoRelatorio.Administrador);
                }
            }

In this section I make it very clear which profiles I want to remove from the list I have.

Of course, it doesn’t really explain why I did it, but it does help a little.

In the old days I used to put the number right on the profile, without identifying it.

It’s just an additional tip.

5

Good names make some comments unnecessary

When the author says not to comment on the code, he refers to prioritizing a readable code that does not need redundant explanations by adding comments. No rule should be followed blindly, because everything depends on a context. Comments have their use, the problem is when they are repetitive or are a crutch to add readability to a code that is confusing and lacks good names. For example, the following code adds a line in a file:

// Função que adiciona uma linha em um arquivo.
function add($name, $string){

    file_put_contents($name, $string, FILE_APPEND);

}

As you can see, the comment makes it clearer what the code is doing. In that case it would not be necessary to comment if the code had a better name, the following is the same function without the need for comments:

function addLineOnFile($filename, $line){

    file_put_contents($filename, $line, FILE_APPEND);

}

When the code has a good name, comments like these are not necessary, however this does not mean that commenting is wrong and that this should be followed in all situations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.