Sobes.tech
Junior — Middle

Should comments be added to code and when is it justified?

sobes.tech AI

Answer from AI

Comments in code should be added when they genuinely help understand the logic or the author's intentions, especially if the code is complex or non-standard.

It is justified to add comments:

  • To explain complex algorithms or business logic.
  • When using non-standard solutions or workarounds.
  • To describe the reasons for choosing a particular approach.
  • To document public APIs, methods, and classes (for example, using Javadoc).

Avoid commenting on obvious code to prevent noise and make reading easier.

Example of a comment in Java:

/**
 * Calculates the factorial of a number n recursively.
 * @param n the number for which the factorial is calculated
 * @return the factorial of number n
 */
public int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
Should comments be added to code and when is it… - sobes.tech