Getty Images/iStockphoto

Tip

Code comment best practices every developer should know

Source code can benefit from well-written code comments. If teams implement proper writing strategies, code comments can be a great tool to explain code intent.

Code comments are a commonly misunderstood feature of programming languages. Getting them right can be the difference between enhancing source code and adding confusion.

Source code is read and executed by a computer. Code comments, on the other hand, are best reserved for explaining the code's intent rather than what it does. The code should be written to a standard where someone can read the lines directly and understand what will happen in execution. There are some exceptions to this, but generally, code does what it's written for and leaves intent unexplained.

Code comments are a way for developers to add text to source code that is ignored by the compiler or interpreter. Developers can use code comments to explain high-level code intent, provide documentation or describe a bug fix.

Let's look at the purpose of code comments, discuss best practices and highlight a few examples of what useful comments might look like.

Avoid common code comment mistakes

To highlight how code comments should describe high-level intent instead of what the code does, let's look at this login function in Python:

@app.route('/login', methods=['POST'])
def login():
  info = json.loads(request.data)
  username = info.get('username')
  password = info.get('password')
  user = User.objects(name=username, password=password).first()
 
   if user:
      login_user(user)
      return jsonify(user.to_json())
  else:
      return jsonify({"status": 401,
                      "reason": "Username or Password Error"})

On the first line of the function, the data included with the request is parsed into a JSON object and set to the variable info. On the next two lines, the username and password are read from the info JSON object. Then, a variable user is set to the result of checking the user model for entries with that username and password. Next, the code goes through an if statement that checks the user variable. If the user variable is not null, the login_user function is called, and the user info is returned as a JSON object. However, else -- when the user variable is empty or null -- results in a 401 error to indicate that the user does not exist with that username and password.

In this scenario, developers should avoid adding code comments that duplicate the lines of code themselves. Once you know that the json.loads function takes a string and returns a JSON object, you won't benefit from a comment that relays the same information. If you forget what the function does, it's best to look up the documentation for the function.

If there was a comment explaining the code at this level, it could be incorrect or outdated based on differences between you and the original developer. Duplicative code comments clutter the code and make it harder to read, which introduces confusion and possible discrepancies.

Useful comments should add value to and improve the code by clarifying the code's intent by providing a brief, high-level summary. For example, you can add the following comments to this piece of code:

# Log in existing users or return 401
@app.route('/login', methods=['POST'])
def login():
  info = json.loads(request.data)
  username = info.get('username')
  password = info.get('password')
# get a matching user from the database
  user = User.objects(name=username, password=password).first()
 
   if user:
      login_user(user)
      return jsonify(user.to_json())
  else:
      return jsonify({"status": 401,
                      "reason": "Username or Password Error"})

These comments provide a high-level understanding and overall flow of the function. Any other developers working on this code should easily understand the comments and code because of their familiarity with the codebase and frameworks in use.

If developers struggle to write a concise comment, it might indicate a problem with the code in general.

Another code comment best practice that this example highlights is to keep comments brief. If developers struggle to write a concise comment, it might indicate a problem with the code in general. You may want to rethink the way the code is structured.

Overly complicated code is difficult to read, and this, in turn, makes commenting a challenge. Refactoring to where the code is easily explainable saves time for others in understanding the code, as well as any future code maintenance.

What does a well-written code comment look like?

Let's look at an example of well-commented code, where we can see some of the guiding principles in action:

# get local date - does not account for time zone
# note: date was imported at top of script
def stringdate():
  today = date.today()
  date_list = str(today).split('-')
  # build string in format 01-01-2000
  date_string = date_list[1] + "-" + date_list[2] + "-" + date_list[0]
  return date_string

This example comes from source code written for a course on Python. The first comment describes the function at a high level and shares a condition that is important for any developer using the function to know. The second comment focuses on how the date is imported at the top of the script. This comment helps developers learning the process to better understand the function.

Lastly, the comment inside the function helps readers quickly understand what the line does to set the date_string variable. Comments that summarize complex, idiosyncratic code help save time in code review and future maintenance.

Code comments best practices

Overall, there are five guiding principles for cleaner code comments:

  1. Comments should explain why code is written the way it is, rather than explaining what the code does.
  2. Comments should be nonduplicative of code.
  3. Comments should clarify, not confuse.
  4. Comments should be brief; if your comments are extensive, you likely have problematic code.
  5. Comments should provide explanations for nonobvious code.

Using these tips to write code comments creates more readable and maintainable code. Helpful comments in your code enable other developers to more quickly understand the design of your codebase. When that happens, they can contribute code that reinforces the same ideas and design.

Dig Deeper on Software design and development

Cloud Computing
App Architecture
ITOperations
TheServerSide.com
SearchAWS
Close