The Secret to Writing Code That Humans Can Understand


 

The Secret to Writing Code That Humans Can Understand

Why your future self (and your team) will thank you





You've just finished a brilliant piece of Python code. It works perfectly, a testament to your skill. You close your laptop, proud of your work, and move on to the next task.

Fast forward three months. You reopen the file to add a new feature, and suddenly, a wave of confusion washes over you. "What on earth was I doing here? Why did I write it this way?"

This is a familiar feeling for every developer. It's the moment you realize that code isn't just for computers — it's for people. This is where the simple act of commenting comes to the rescue. Think of comments as sticky notes for your code, little messages for your future self and other developers to explain not just what your code does, but why you wrote it that way.

In this article, we'll move beyond the basics and dive into the art of writing comments that are genuinely useful, turning your code from a puzzle into a clear, readable story.

The Three Types of Python Comments

Python offers three primary ways to add notes to your code, each with a different purpose.

1. Inline Comments

These are short notes that live on the same line as your code, after a # symbol. They are best used for quick, one-line explanations of a specific action.

# Good inline comments:
radius = 5  # Radius in centimeters
area = 3.14 * radius**2  # Calculate area using πr²

PEP 8, Python's official style guide, has a specific rule for these: always separate the comment from the statement by at least two spaces, and the # should be followed by a single space.

2. Block Comments

These are longer notes that span multiple lines. Each line must start with a # followed by a single space. Block comments are used to explain a whole section of code that follows.

# This function validates the user input against a list of
# approved names and handles case-insensitive matching. It is
# designed to prevent injection attacks and to be robust against
# common typos.
def validate_user_name(name):
    # ... code goes here

3. Docstrings

These are the "super-powered" comments, enclosed in triple quotes ("""). They are used to document modules, classes, and functions, explaining their purpose, arguments, and return values. Docstrings are crucial for creating high-quality, self-documenting code. Tools like Sphinx can even use them to automatically generate documentation for your project.

def calculate_discount(price, discount_percent):
    """
    Applies a discount to a price and returns the new amount.

    Args:
        price (float): The original price of the item.
        discount_percent (float): The discount to apply (e.g., 20.0 for 20%).

    Returns:
        float: The discounted price.
    """
    return price * (1 - discount_percent / 100)

The Golden Rule: Write Why, Not What

The most important lesson in commenting is a simple mantra:

"Write why, not what."

The code itself shows what is happening. Your comments should explain the reasoning behind it. This is the difference between a useless comment and a valuable one.

❌ Don't write: x = x + 1 # Add 1 to x (This is obvious and redundant.)

✅ Do write: index = index + 1 # Skip the first header row in the data file (This provides crucial context that isn't visible in the code.)

The Hall of Fame: Examples of Great Comments

Great comments provide insight that the code cannot express on its own. They are the artifacts of your thought process, preserving the context and decisions you made.

✅ Explaining a Workaround

# Using a list comprehension here instead of a generator because
# we need to iterate over the result multiple times to validate it.
data = [process(item) for item in large_dataset]

This comment explains a performance-related decision, which is vital for anyone maintaining the code later.

✅ Warning Future Developers

# WARNING: Do not change this key. It is hardcoded to match the external
# third-party API integration. See ticket DEV-445 for more details.
API_RESPONSE_KEY = "External-ID"

This comment is a lifesaver. It prevents a future developer from breaking a critical system connection.

✅ Clarifying Complex Business Logic

# The discount is capped at 50% for 'SUPER_SALE' events, but
# management has approved a 60% cap for user tier 'PLATINUM'.
# (Email approval from CMO, 2023-10-26)
if user_tier == 'PLATINUM':
    discount = min(discount, 0.6)
else:
    discount = min(discount, 0.5)

This provides business context and a source of truth for a seemingly arbitrary rule.

The Hall of Shame: What to Avoid

Just as important as writing good comments is knowing what not to write. Avoiding these common mistakes will keep your code clean and your comments useful.

❌ Outdated Comments

This is the most dangerous kind of comment. It actively misleads anyone reading the code. If your code changes, your comments must change with it.

# ❌ The Outdated Comment:
# This function returns a list of strings
def get_user_data():
    return {'name': 'Alice', 'id': 12345}

# ✅ The Fix:
# This function returns a dictionary containing a user's name and ID.
def get_user_data():
    return {'name': 'Alice', 'id': 12345}

❌ The Obvious

These comments add nothing but visual noise. They are a sign that the code is not self-explanatory. The best way to fix this is to use clear variable and function names instead of adding a comment.

❌ Commented-Out Code

This is what version control systems like Git are for. Don't leave commented-out code in your file. If you need a historical record, check your commit history.

Comment Maintenance: The Unsung Hero

Writing a comment is just the first step. To ensure they remain valuable, commenting must be a continuous practice.

Review and Refactor: Treat your comments like you treat your code. When you refactor a function or change its behavior, take a moment to update or remove the old comments.

During Code Reviews: A good code review doesn't just check for bugs. It should also ask: "Is this code understandable? Could a comment here prevent future confusion?"

The Takeaway

Great comments are not a chore; they are an investment in the future of your code and your sanity. They are a sign of a thoughtful developer who considers the human element of programming.

Start with your most complex function and ask yourself: "Would a new team member understand why I made these choices?" If the answer is no, it's time to write a great comment. Master this art, and you'll not only write better code but also become the most valued developer on any team.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Comments

Popular posts from this blog

The New ChatGPT Reason Feature: What It Is and Why You Should Use It

Raspberry Pi Connect vs. RealVNC: A Comprehensive Comparison

Insight: The Great Minimal OS Showdown—DietPi vs Raspberry Pi OS Lite