Best

Code comment best practices every developer should know

Code comments are a commonly misunderstood feature of programming languages. Getting them right can mean the difference between improving source code and creating confusion.

Source code is read and executed by a computer. Code comments, on the other hand, are best reserved for explaining the intent of the code, not what it does. The code should be written to a standard where someone can read the lines directly and understand what will happen when executed. There are some exceptions, but in general, code does what it’s written to do and leaves the 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 the code’s intent at a high level, provide documentation, or describe a bug fix.

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

Avoid common code comment mistakes

To emphasize how code comments should describe the high-level intent rather than 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"})

In the first line of the function, the data contained in the request is parsed into a JSON object and set to the variable the information. In 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 a If Statement that checks the user Variable. If the user variable is not null that login_user function called and returned the user information as a JSON object. However, different — if that user Variable is empty or null – results in a 401 error to indicate that the user with that username and password does not exist.

Read  XT.COM Wins "Best Crypto Platform 2023" Award at Crypto Expo Dubai 2023

In this scenario, developers should avoid adding code comments that duplicate the lines of code themselves. Once you know that json.loads If the function takes a string and returns a JSON object, you don’t benefit from a comment passing the same information. If you’ve forgotten what the function does, it’s best to consult the function’s documentation.

If there was a comment explaining the code at this level, it could be incorrect or out of date due to differences between you and the original developer. Duplicate code comments clutter the code and make it harder to read, leading to confusion and possible discrepancies.

Useful comments should enhance and improve the code by clarifying the intent of the code by providing a brief, high-level summary. For example, you can add the following comments to this section 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 general understanding and flow of the feature. All other developers working on this code should easily understand the comments and the code since they are familiar with the code base and frameworks used.

When developers are having trouble writing a concise comment, it may indicate a general problem with the code.

Another best practice for code comments, highlighted in this example, is to keep comments short. When developers are having trouble writing a concise comment, it may indicate a general problem with the code. You might want to rethink the way the code is structured.

Overly complicated code is difficult to read, which in turn makes commenting a challenge. Refactoring the code to be easily explainable saves others time understanding the code as well as 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 is from source code written for a Python course. The first comment describes the function at a high level and shares a condition that is important to any developer using the function. The second comment focuses on how the date is imported at the top of the script. This comment will help developers learn the process to better understand the function.

Finally, the comment inside the function helps readers quickly understand what the setting line does date_string Variable. Comments summarizing complex, idiosyncratic code help save time on code review and future maintenance.

Best practices for code comments

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 not duplicate code.
  3. Comments should clarify, not confuse.
  4. Comments should be short; If your comments are large, you probably have problematic code.
  5. Comments should provide explanations for non-obvious code.

Using these tips for writing code comments will result in more readable and maintainable code. Helpful comments in your code allow other developers to more quickly understand the design of your code base. In this case, they can contribute code that reinforces the same ideas and design.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button