Developer 101 - Mastering Comments and Documentation

Learn how to write meaningful comments and documentation in your code. Explore best practices, real-world scenarios, and examples from Python and C# to improve your code clarity and maintainability.

Writing good code is only part of the job. Making it understandable for your teammates — and for your future self — is equally important. Comments and documentation play a vital role in making your codebase maintainable, readable, and collaborative.

Types of Comments

  • Inline Comments: Placed on the same line as code, they explain a specific logic.
  • Block Comments: Span multiple lines, used to explain complex logic or sections.
  • TODO/FIXME Notes: Indicate pending work or known issues.

Best Practices

  • Don’t state the obvious — write comments that add value.
  • Keep comments short, but informative.
  • Update comments when the code changes.
  • Use a consistent style and tone.

Commenting Examples

C#

// Bad: Too obvious
int total = 0; // Set total to 0

// Good: Adds context
int total = 0; // Initialize total to accumulate cart item prices

// TODO: Handle discounts in future

Python

# Bad: Redundant
count = 0  # Count is zero

# Good: Clarifies purpose
count = 0  # Number of users currently online

# FIXME: This needs optimization for large datasets

Docstrings and Documentation

Docstrings are embedded documentation for functions, classes, and modules. Use them to describe purpose, parameters, and return values.

Python Docstring

def add(a, b):
    """Add two numbers and return the result.

    Args:
        a (int): First number.
        b (int): Second number.

    Returns:
        int: Sum of a and b.
    """
    return a + b

C# XML Documentation

/// 
/// Adds two integers and returns the result.
/// 
/// First integer
/// Second integer
/// Sum of a and b
public int Add(int a, int b)
{
    return a + b;
}

External Documentation

  • README: Explain project structure, dependencies, and usage.
  • Wiki or Notion: Maintain detailed project architecture, workflows, and design decisions.
  • API Docs: Auto-generated using tools like Swagger, JSDoc, or Sphinx.

Bad Code Readability – Real-World Problems

Unreadable code leads to confusion, delays, and bugs — especially for support teams maintaining the code under pressure. Without clear comments or structure, even a simple issue can take hours to debug.

❌ Poorly Commented Code (C#)

public void C(int x) {
    if (x == 1) { P(); } else { Q(); }
}
  • Method and variable names are meaningless.
  • No indication of what P() or Q() do.
  • Support team has no clue what behavior to expect.

✅ Refactored and Documented Version (C#)

/// 
/// Processes user request based on priority flag.
/// 
/// 1 = high priority
public void ProcessRequest(int priorityFlag) {
    if (priorityFlag == 1) {
        HandleUrgentRequest();
    } else {
        HandleStandardRequest();
    }
}

❌ Poorly Written Code (Python)

def c(x):
    if x == 0:
        t()
    else:
        y()
  • Function and method names are cryptic.
  • No comments or docstrings to explain the logic.
  • Debugging becomes trial-and-error.

✅ Improved Version (Python)

def process_login(user_status):
    """Processes login based on user status.

    Args:
        user_status (int): 0 for guest, 1 for registered user.
    """
    if user_status == 0:
        handle_guest_login()
    else:
        handle_registered_user()

Support Team Impact

  • Delayed Fixes: Time is wasted understanding what the code is supposed to do.
  • Incorrect Fixes: Misinterpretation of logic can lead to introducing new bugs.
  • Lower Morale: Developers dread working on unclear legacy code.
  • Poor Handover: Code transitions become chaotic when developers leave.

Real-World Bugs Caused by Poor Documentation

🧨 Scenario 1: Misunderstood Business Logic (C#)

// Original developer assumed business hours end at 6 PM.
if (DateTime.Now.Hour < 18)
    SendNotification();

Notifications were sent after hours. Policy had changed but comments didn't reflect that.

Fix:

// Business hours updated as of Jan 2025 policy
if (DateTime.Now.Hour < 17)
    SendNotification();

🧨 Scenario 2: Silent Failures Due to Assumptions (Python)

def calculate_discount(user_type):
    if user_type == 'premium':
        return 0.20
    return None

Fix:

def calculate_discount(user_type):
    """Returns discount rate for known user types."""
    if user_type == 'premium':
        return 0.20
    elif user_type == 'standard':
        return 0.10
    raise ValueError("Unknown user type")

🧨 Scenario 3: Unclear API Response Mapping (C#)

// Mistook business code for HTTP code
if (response.status_code == 200)
    ApproveRequest();

Fix:

// 100 = success; 200 = validation error, etc.
if (response.status_code == 100)
    ApproveRequest();

🧨 Scenario 4: Hidden Calculation Logic (Python)

# Monthly interest
interest = principal * 0.015

Hardcoded value caused miscalculations after interest rate changes.

Fix:

monthly_interest_rate = get_config("interest_rate")
interest = principal * monthly_interest_rate

Conclusion

Don’t leave your future self (or your teammates) in the dark. Clean, meaningful comments and documentation are a hallmark of professional development. When done right, they reduce bugs, speed up onboarding, and make everyone’s life easier.