No Comentes mal c贸digo, reescribelo
Introducci贸n
Presentaci贸n
Prerrequisitos
Terminolog铆a: Buenas pr谩cticas, refactoring, c贸digo limpio, deuda t茅cnica
Descarga y an谩lisis del proyecto a trabajar
Principios del c贸digo limpio
Nombramiento
Code Smells
Principio DRY
Principio KISS
Usando try catch
Mejoras en C# y comentarios
Evoluci贸n de C#
Interpolaci贸n de cadenas, inicializador de propiedades y operador condicional null
Implementando minimalismo
Uso de comentarios
Cierre
Resumen y cierre del curso
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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:
calculateAverage
, it is not necessary to add a comment that says "calculates the average".Although it is ideal to have self-explanatory code, in specific situations comments can add valuable context.
For example:
// Decrement one position, since the array starts at zeroarrayIndex = userInput - 1;
A good comment should not detract from the clarity of the code, but contribute to its understanding. Some recommendations to achieve this include:
summary
annotations if they provide useful information when invoking the method.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
No Comentes mal c贸digo, reescribelo
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
}
Want to see more contributions, questions and answers from the community?