You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
10 Hrs
55 Min
32 Seg

Uso de comentarios

13/14
Resources

How to use code comments correctly?

Comments in the code are essential elements that, when used properly, facilitate the understanding and maintenance of the software. However, they can become a hindrance if they are abused or used redundantly. Throughout this guide, we will explore best practices for the use of comments in order to write clean and efficient code.

What kind of comments should be avoided?

Excessive commenting is one of the most common problems. Comments that simply repeat what is already stated in the code are redundant and increase visual complexity without adding real value. Here are some practices to avoid:

  • Obvious comments: don't comment what is already obvious from the name of the class, method or variable. For example, if you have a method called calculateAverage, it is not necessary to add a comment that says "calculates the average".
  • Comments without purpose: Don't add comments for temporary things, such as leaving commented code with the intention of using it later. That tends to become permanent by carelessness.
  • Comments on changes: Version control systems like Git keep track of changes. It is not necessary to document every change in the code with comments.

When are comments useful?

Although it is ideal to have self-explanatory code, in specific situations comments can add valuable context.

  • Complex code: In cases where the code is unavoidably convoluted, such as the use of complex regular expressions, comments can help clarify what is going on.
  • Decision justification: If non-obvious decisions must be made, such as modifying indexes of an array, it is useful to document the why behind that choice.

For example:

// Decrement one position, since the array starts at zeroarrayIndex = userInput - 1;

How effective should comments be?

A good comment should not detract from the clarity of the code, but contribute to its understanding. Some recommendations to achieve this include:

  • Make sure they are brief and clear. Avoid long comments; instead, make them direct and precise.
  • Make use of structured blocks if necessary. For example, when documenting functions, you can use summary annotations if they provide useful information when invoking the method.
  • Review and remove unnecessary comments. When maintaining your code, make sure that comments are still relevant and remove them if they no longer add value.

How to apply these practices in specific code?

In the example project, we looked at different cases of comments and how improvements were implemented.

For example, in a method that returns the option selected by the user, a well-structured comment can be useful if it contains a summary and a list of the available options:

/// <summary>/// Displays the available task options/// </summary>/// <returns>Returnsthe option selected by the user</returns>.

On the other hand, comments like:

// read line

Are not necessary when the operation is clear due to the variable or function name.

In this context, code improvement involves not only adding useful comments but also removing those that do not provide clarity and could hinder the understanding of the code.

Implementing these best practices in your personal projects will not only improve the quality of your code but also facilitate its maintenance and evolution over time. I invite you to reflect on the comments in your current projects and to always opt for clarity and minimalism when documenting your code.

Contributions 6

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

No Comentes mal c贸digo, reescribelo

1 ## Uso de comentarios en C\# **驴Qu茅 son?** Los comentarios son **anotaciones en el c贸digo** que no se ejecutan por el compilador. Se utilizan para: * **Explicar el c贸digo:** Ayudan a comprender el prop贸sito del c贸digo. * **Documentar el c贸digo:** Proporcionan informaci贸n sobre el c贸digo, como su autor, fecha de creaci贸n, modificaciones, etc. * **Mejorar la legibilidad del c贸digo:** Ayudan a estructurar y organizar el c贸digo. **Tipos de comentarios en C#:** * **Comentarios de una sola l铆nea:** Comienzan con dos barras diagonales (`//`) y terminan al final de la l铆nea. * **Comentarios de varias l铆neas:** Comienzan con una barra diagonal y un asterisco (`/*`) y terminan con un asterisco y una barra diagonal (`*/`). **Beneficios de usar comentarios:** * **Mejora la comprensi贸n del c贸digo.** * **Facilita el mantenimiento del c贸digo.** * **Permite la colaboraci贸n entre diferentes desarrolladores.** **Consejos para usar comentarios:** * **Utiliza un lenguaje claro y conciso.** * **Evita los comentarios redundantes.** * **Actualiza los comentarios cuando se modifica el c贸digo.** ```js // Este es un comentario de una sola l铆nea. /* Este es un comentario de varias l铆neas. */ ```
no hay que sobre cargar de comentarios nuestros desarrollos, ya que generan mucha ilegibilidad.
IMPORTANTE En ocasiones solemos imprimir en consola informaci贸n. Esto es importante a la hora de desarrollar; pero es fundamental que a la hora de desplegar nuestro proyecto eliminar los debugs que no sean necesarios, generan problemas de seguridad a la hora de algun ataque. Adem谩s, dejar comentado c贸digo que no vamos a utilizar, puede generar que desde alguna pagina web o aplicaci贸n esto pueda verse y no tener sentido alguno, generando nuevamente problemas de seguridad,

C贸digo actualizado:

List<string> TaskList = new List<string>();

int menuOption = 0;

do
{
    menuOption = ShowMainMenu();
    if ((Menu)menuOption == Menu.Add)
    {
        AddTask();
    }
    else if ((Menu)menuOption == Menu.Remove)
    {
        RemoveTask();
    }
    else if ((Menu)menuOption == Menu.List)
    {
        ShowTaskList();
    }
} while ((Menu)menuOption != Menu.Exit);

/// <summary>
/// Show the options for Task:
/// 1. Nueva tarea
/// 2. Remover tarea
/// 3. Tareas pendientes
/// 4. Salir
/// </summary>
/// <returns>Returns menuOption indicated by user</returns>
int ShowMainMenu()
{
    Console.WriteLine("----------------------------------------");
    Console.WriteLine("Ingrese la opci贸n a realizar: ");
    Console.WriteLine("1. Nueva tarea");
    Console.WriteLine("2. Remover tarea");
    Console.WriteLine("3. Tareas pendientes");
    Console.WriteLine("4. Salir");

    string taskIndex = Console.ReadLine();
    return Convert.ToInt32(taskIndex);
}

void RemoveTask()
{
    try
    {
        Console.WriteLine("Ingrese el n煤mero de la tarea a remover: ");
        ListTasks();

        string taskIndex = Console.ReadLine();

        // Remove one position because the array starts with 0
        int indexToRemove = Convert.ToInt32(taskIndex) - 1;

        if (indexToRemove <= TaskList.Count - 1 && indexToRemove >= 0)
        {
            if ((indexToRemove > -1) || (TaskList.Count > 0))
            {
                string taskToRemove = TaskList[indexToRemove];
                TaskList.RemoveAt(indexToRemove);
                Console.WriteLine($"Tarea {taskToRemove} eliminada");
            }
        }
        else
        {
            Console.WriteLine("El n煤mero de tarea seleccionado no es v谩lido.");
        }
    }
    catch (Exception)
    {
        Console.WriteLine("Ha ocurrido un error al eliminar la tarea.");
    }
}

void AddTask()
{
    try
    {
        Console.WriteLine("Ingrese el nombre de la tarea: ");
        string taskToAdd = Console.ReadLine();

        if (!string.IsNullOrEmpty(taskToAdd))
        {
            TaskList.Add(taskToAdd);
            Console.WriteLine("Tarea registrada");
        }
        else
        {
            Console.WriteLine("La tarea no puede estar vac铆a.");
        }

    }
    catch (Exception)
    {
        Console.WriteLine("Ha ocurrido un error al intentar ingresar la tarea.");
    }
}

void ShowTaskList()
{
    if (TaskList?.Count > 0)
    {
        ListTasks();
    }
    else
    {
        Console.WriteLine("No hay tareas por realizar");
    }
}

void ListTasks()
{
    Console.WriteLine("----------------------------------------");

    var indexTask = 1;
    TaskList.ForEach(task => Console.WriteLine($"{indexTask++}. {task}"));

    Console.WriteLine("----------------------------------------");
}


public enum Menu
{
    Add = 1,
    Remove = 2,
    List = 3,
    Exit = 4
}

Recomendaciones para comentar: * No abuses de los comentarios. * Si los comentarios son obvios, no los pongas. * Escribe c贸digo f谩cil de entender como filosof铆a. * No comentes la trazabilidad de cambios (eso lo deber铆a hacer el controlador de versiones que estemos utilizando, por ejemplo git, github etc...). * Mant茅n los comentarios cortos y claros. * No dejes c贸digo comentado.