Introduction
When building an API, it's essential to include comments that provide context and explanations for the development decisions made by your team. These comments are not about explaining what the code does (that's handled by the variable names), but rather why certain design choices were made.
The Problem with "What" Comments
# This is a comment explaining what the code does
def get_user_data(user_id):
# Get user data from database
user_data = db.get_user_data(user_id)
return user_data
While this comment provides some context, it's not particularly useful for future developers trying to understand why this specific implementation was chosen. It only explains what the code does.
The Power of "Why" Comments
# This is a comment explaining why the decision was made
def get_user_data(user_id):
# We're using a database query instead of caching because we expect high traffic and frequent user updates
user_data = db.get_user_data(user_id)
return user_data
By including "why" comments, you provide context for future developers to understand the reasoning behind your design decisions. This makes it easier for them to maintain and extend the codebase.
Examples of Why-Not Comments
Here are a few more examples of why-not comments in action:
# We're using a 2-factor authentication system instead of just passwords because we want to provide an extra layer of security for our users
def authenticate_user(username, password):
# Authenticate user with 2-factor code
return auth.authenticate_user(username, password)
# We're caching frequently accessed data in Redis instead of the database because it's faster and more efficient
def get_cached_data(key):
# Get cached data from Redis
return cache.get(key)
Best Practices for Writing Why-Not Comments
Here are some best practices to keep in mind when writing why-not comments:
- Be specific: Avoid vague comments like "We're using this because it's faster." Instead, provide concrete details about the trade-offs you made.
- Use a consistent tone: Try to maintain a neutral or slightly informal tone. This will make your comments more approachable and easier to read.
- Keep them concise: Aim for 1-2 sentences per comment. Any longer than that can be overwhelming.
Conclusion
Why-not comments are an essential part of writing maintainable, readable code in an Apiary platform. By including context about the reasoning behind design decisions, you make it easier for future developers to understand and extend your codebase. Remember to keep your comments concise, specific, and neutral, and always prioritize explaining why over what.