Code comments when working in a group

Asked

Viewed 1,771 times

11

When working in a group, developing code with other people, using specific tools and everything, what is the best way to comment on the code?

Well, let’s go to the stage.

By owning the project in Subversion, Mercurial, Git, TFS, or other tools, multiple contributors will have access to develop the project. When analyzing the code that someone else developed, we can observe that some are great professionals, with everything standardized. However, there is always POG’s (Gambiarra-oriented programmers) that make the code all disorganized, and hindering the understanding of it. From there comes the doubt: Comment on the code helps, but how to make these code comments?

When working with several programmers, one can observe that each make comments, as "think" is the best way, that when the project does not have a standard.

I will use this code to demonstrate some ways:

#include <iostream>
#include <string>

 using namespace std;

 class Person 
 {
   string name; 
   int height;
 };

 void setValues(Person&);
 void getValues(const Person&);

 int main ()
 {
   Person p1;
   setValues(p1);  
   cout << "Informando dados sobre a pessoa:\n";
   cout << "================================\n";
   getValues(p1);
   return 0;
 }

 void setValues(Person& pers)
 {
   cout << "Informe o nome da pessoa: ";
   getline(cin, pers.name);
   cout << "Informe a altura em milímetros: ";
   cin >> pers.height; 
   cin.ignore();
 }

 void getValues(const Person& pers)
 {
   cout << "Nome da pessoa: " << pers.name << endl; 
   cout << "A altura da pessoa em milímetros é: " << pers.height << endl;
 }

Comment the code at the beginning of the class, where the functionality of a class is placed, and its methods will perform.

#include <iostream>
#include <string>

 //Classe responsável por realizar o get, set de uma pessoa
 using namespace std;

 class Person 
 {
   string name; 
   int height;
 };

 void setValues(Person&);
 void getValues(const Person&);

 int main ()
 {
   Person p1;
   setValues(p1);  
   cout << "Informando dados sobre a pessoa:\n";
   cout << "================================\n";
   getValues(p1);
   return 0;
 }

 void setValues(Person& pers)
 {
   cout << "Informe o nome da pessoa: ";
   getline(cin, pers.name);
   cout << "Informe a altura em milímetros: ";
   cin >> pers.height; 
   cin.ignore();
 }

 void getValues(const Person& pers)
 {
   cout << "Nome da pessoa: " << pers.name << endl; 
   cout << "A altura da pessoa em milímetros é: " << pers.height << endl;
 }

Comment only on the methods, describing the functionality of each, but not delving into each method.

#include <iostream>
#include <string>


 using namespace std;

 class Person 
 {
   //Declara as variáveis
   string name; 
   int height;
 };

 //get set da classe
 void setValues(Person&);
 void getValues(const Person&);

 //método para receber dados da pessoa
 int main ()
 {
   Person p1;
   setValues(p1);  
   cout << "Informando dados sobre a pessoa:\n";
   cout << "================================\n";
   getValues(p1);
   return 0;
 }

 //realiza o set da pessoa
 void setValues(Person& pers)
 {
   cout << "Informe o nome da pessoa: ";
   getline(cin, pers.name);
   cout << "Informe a altura em milímetros: ";
   cin >> pers.height; 
   cin.ignore();
 }

  //realiza o get da pessoa
 void getValues(const Person& pers)
 {
   cout << "Nome da pessoa: " << pers.name << endl; 
   cout << "A altura da pessoa em milímetros é: " << pers.height << endl;
 }

Commenting on all code functions:

#include <iostream>
#include <string>

//Classe responsável para guardar e mostrar nome e altura de uma pessoa
 using namespace std;

 class Person 
 {
   //Declara as variáveis
   string name; 
   int height;
 };

 //get set da classe
 void setValues(Person&);
 void getValues(const Person&);

 //método para receber dados da pessoa
 int main ()
 {
   //instancia a classe
   Person p1;
   setValues(p1);  
   cout << "Informando dados sobre a pessoa:\n";
   cout << "================================\n";
   getValues(p1);
   return 0;
 }

 //realiza o set da pessoa
 void setValues(Person& pers)
 {
   cout << "Informe o nome da pessoa: ";
   //Guarda o nome da pessoa
   getline(cin, pers.name);

   cout << "Informe a altura em milímetros: ";
   //Guarda a altura da pessoa em milímetros
   cin >> pers.height; 
   cin.ignore();
 }

  //realiza o get da pessoa
 void getValues(const Person& pers)
 {
   //retorna o nome da pessoa
   cout << "Nome da pessoa: " << pers.name << endl; 
   //retorna a altura da pessoa em milímetros
   cout << "A altura da pessoa em milímetros é: " << pers.height << endl;
 }

We can see that in the latter it becomes easier to understand, but the code would be more extensive, taking into account classes that contain many methods.

I posted only a few examples, but I’ve noticed cases of line comments, all class properties, same comment in class and interface, among many others.

From this scenario comes my question: Is there a "standard" form of good practice to comment on a code? If not, what is the best way?

Note: I analyzed this question Here at the Sopt, but it is focused on the C# language and the comment tags used by Microsoft. My question is about the various languages, including the simple HTML itself.

  • 4

    I think patterns in code comments serve to document and not necessarily to work in a group

3 answers

14


Golden Rule

Comments should be avoided whenever possible.

How not to need to comment

One of the ways is to adopt standards or conventions that facilitate the reading of the code.

For example, the first thing I would do in your example code is to put the class Person in a source file person.cpp containing only the class. a directory entities, model, domain or equivalent containing only domain classes is self-explanatory. Organize your classes, functions and other code elements into a self-explanatory directory structure.

The same goes for class nomenclature. For example, adding suffixes or prefixes according to known patterns: Dao, Repository, Helper, View, Controller, Business, Service, etc..

In the methods, use descriptive names. Access methods (getters and setters) do not need comments. Try to write most of your main code in classes, as this facilitates organization and understanding. For example, calling a method carregar_dados(file) is not so clear, but Person.carregar_dados(file) is intuitive to load the person’s data from a file.

Do not use counterintuitive comments

Do not rely on comments to clarify a counterintuitive code. If a class, a method, a function or a variable is under a bad name or a chunk of code is poorly implemented, refactor to make it clearer.

Comments like the below even explain what the code does:

//método para receber dados da pessoa
int main ()

But main to receive data from the person? Incidentally, this comment is misleading (as most comments try to "explain" methods. The main "receives "data, prints a header and two prints user data.

It would not be much more intuitive and organized something like below?

int main() 
{
    Pessoa p;
    receberDadosPessoa(p);
    imprimirCabecalho();
    imprimirDadosPessoa(p);
}

You need to explain what the above code does?

Don’t teach programming with comments

If younger programmers don’t know how to do things in language, do a brief training, peer program, etc. The worst place to teach someone to code is through comments on the code.

Note the example below:

//Declara as variáveis
string name; 
int height;

Or else:

//instancia a classe
Person p1;

Something interesting about this type of comment is that the novice programmer, who has a certain fear of what he is doing, puts him in two or three parts, but soon he thinks it is no longer necessary and forgets. So the code ends up with some random comments that are more related to the programmer’s learning and insecurity than to some real utility.

When to use comments

Use comments mainly in these situations:

Explain business rules that are not obvious

Programmers don’t live by bits alone. Some things completely escape our everyday lives and these implementations need to be documented in detail to prevent a rushed programmer from trying to "fix" something that is correct.

Example:

/*
 * Implementação segundo a fórmula do banco central disponível em [link]
 */
float converter_taxa_cdi_mensal_para_anual(...) 
{
    //padrão DU/252 representa o número de dias úteis
    //considerando-se um ano padrão de 252 dias úteis
    int diasUteisAno = 252;
    ... 
}

It is tempting for any good programmer to find that number 252 fixed is someone’s gambiarra and that the code should actually calculate the amount of working days of the current year.

Generic code that also does not have its obvious function

Generic code that implements functionality to be reused in certain use cases needs to be documented in some way so that developers know when to apply it without needing to understand its full functioning.

Example:

/*
 * Implementa rotinas gerais usadas nas grids das telas que usam a biblioteca XPTO.
 * Facilita a ordenação automática.
 */
template<typename T> 
class ListaGenericaGrid
{ 
   ...
};

Excerpt of complex code, but which has a reason to be

Sometimes a chunk of code is hard to read, but whoever implemented it had a reason.

See a simple example:

//x * 64, otimizado para o compilador XPTO
int x = y << 6;

The advantage of this comment is that if the "XPTO compiler" is no longer used in the future, any programmer can refactor the code without fear.

Reference to external documentation

Sometimes it is necessary to do something "foreign" to code organization due to something external to your program.

For example, sometimes you use a library and need to add a certain functionality. Then you extend a class and override a specific method that is not obvious. In this case, it is worth putting a comment to the documentation, tutorial or bug tracker where this idea came from.

Considerations

The idea is basically to document with comments only what is relevant and not explicit or to some extent implicit in the code itself.

Above all, don’t comment on the obvious. It’s a waste of time for those who write and for those who read. It is visual dirt and all this will generate, directly or indirectly, a higher cost for the project, whether in terms of money, time, complexity, maintenance difficulty, etc.

  • 1

    What do you think about Javadoc?

  • @Most of what the tools generate I just erase. However, the story changes completely if the idea is to publish an API to third parties. When I publish a library, for example, I usually keep a documentation in the public classes and methods explaining how to use and giving examples.

4

Most of what I could say has already been said in the answers here and in my answer in that question. Also read the other answers there, in a general way I agree with them. I do not think that what was stated in the question cited serves only for C#, some points yes, but almost all are universal.

To consolidate and show why it preaches the use of comments I will post something additional.

Comments are not good because they hurt the DRY. They are hard to keep synchronized. Comments should tell why something was done and never what was done there.

Documentation

Don’t confuse comments with documentation. Documenting classes and methods even using the comment mechanism should not be interpreted as comments. This documentation is easier to keep synchronized with the code because it only documents the contract, and contracts should not be changed. But if the contract is changed anyway, there will certainly be many tests and will need to be communicated to all users. Certainly the change in the documentation will not be forgotten. And if it is, your team is all chipped even, delivery to God :)

Documentation shall provide relevant information. Read the documentation of well-known Apis that are reputed to be well documented to see what is relevant. Stating the obvious doesn’t help anything. A silly comment just to say that it has documented does not serve much. There must be an explanation of the implications of using that class or method. What can go wrong, when to use and not to use. Because it exists, especially if it seems that it should not exist. Documenting means informing all aspects of it, all the important data for the contract, such as parameters, return, possible exceptions.

To learn it’s just not worth looking at the PHP documentation that’s too bad :) Lie, it’s better than most of the documentation people do. It’s just not as good as some very good ones, which are examples of well-done documentation. Although none are grade 10 either, documenting well is difficult.

But you also have to see the cost of documenting this, it’s not always worth the effort. Will it be too big? Is it too complicated to track without documentation? Can’t we simplify the architecture to avoid having to document so much? Often it doesn’t need everything that has been done. Can you make some parts private and take them out of the API? Will it be used by a lot of people? For a long time?

If extremely popular programming languages don’t make grade 10 documentations in their Apis, why should you do this with their system that will be used by a few programmers? Think about it. And if it’s not to document reasonably well, it’s better not to document.

Expressive codes

Real comments are only needed when the code is misspelled.

Commentary was encouraged in the 1950s and 1960s when languages were limited. It was common for variables to have only two characters, functions, or to have no expressive names. Memory was so scarce that any economy counted. The same goes for processing cycles. The important thing was to produce efficient code, because compilers were very bad at optimizing. Legibility was secondary, making the commentary essential. In fact where most used comment was in Assembly - very used at the time - which has almost zero expressiveness.

This was taught to newcomers in the profession. And they became teachers. All wrote books. And the knowledge was passed down to generations. But the technology has changed, the languages, the more modern compilers and the more loose resources have allowed to prefer readable codes and dispense almost completely the use of comments. But a lot of people didn’t understand this. And they keep repeating the mantra.

Do you realize that people have trouble commenting? It seems like a burden to do this. And it’s something much easier and less laborious than coding. Maybe I don’t have any studies on the subject, it’s because subconsciously people know it’s useless. Then they stop doing it when the comment is really necessary. The brain is very confusing. That is why advertisements use this failure to associate products with good feelings. That is why gamification works. You have to train your brain to accept the importance of the necessary comments and not let it get confused with the wise part of it that says comment should be avoided.

In some reply or comment I have criticized the use of redundant comments, as used in your example. I already quit because I was forced to do this:

//Este método inicializa os componentes
InicalizaComponentes();

Note that it is a call, which is even worse to document the use. If it was in the definition of the method and explained why it is necessary, how it acts in the system, then fine. But not only was this not necessary, it was not done by anyone.

HTML and CSS

Even though HTML is not very expressive, but on the other hand also does not generate so much confusion, it is not very necessary. HTML is not a programming language.

If you organize (with vertical and horizontal spacing) the code so as to facilitate the reading fluency and put expressive names in id, class, name and other attributes, eventually even putting where they are not needed at that time, also need no comment.

I see more reason to comment CSS code. Ali is full of tricks to work in all browsers. You have to explain why you’re using that. There’s no way to make code expressive enough to indicate why that crazy thing is there. And you don’t even have to be crazy to need comment.

Almost no one comments on CSS and when they comment, in general it is not well done.

Completion

One thing I’ve learned is that the person who can’t program right won’t be able to comment properly. So many comments not only speak the obvious but do the opposite, say things that do not match the reality. She often doesn’t understand what she’s doing. She even knows that the result is being produced but she doesn’t understand the semantics of it. And commentary, even those that we are saying are not good, serve to give more semantics to what is being done. If the programmer does not know how to define clearly what happens in fact there, the comment will go wrong. I myself after more than 35 years of experience have a hard time fully understanding the problem I’m dealing with when it’s a new problem for me. An example of how easy it is to misunderstand one thing can be seen in one more excellent response from Eric Lippert.

I don’t know how to solve this except train hard and maybe seek specific professional help to help with cognitive ability.

2

Well, I am totally against comments in codes, but as you yourself reported has always moved the gambiarra and consequently to gambiarra there is no convention.

Comments too much as in the last option are very complicated, because every time you change something in the code will have to remember to check if the comment should be updated too.

The best option would be to: Comment only on the methods, describing the functionality of each, but not delving into each method.

Preferably using the form of multi-line commentary:

/*
 * Método para receber dados da pessoa
 * Comentários assim permitem que os orientados 
 * a gambiarra tenham mais liberdade para quebrar linhas
 * e não extrapolar no comprimento, fazendo utilizar a 
 * barra de rolagem para que você possa ler
 */
int main ()
{
   //instancia a classe
   Person p1;
   setValues(p1);  
   cout << "Informando dados sobre a pessoa:\n";
   cout << "================================\n";
   getValues(p1);
   return 0;
}

Browser other questions tagged

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