Code-Memo

Writing Clean and Maintainable Code

These brief notes summarize key concepts from Clean Code by Robert C. Martin (also known as “Uncle Bob”), focusing on principles for writing clear, maintainable, and high-quality code.


Throughout my modest few years of experience, I have learned that writing code is not just about meeting deadlines, it’s about writing software that can be developed, be easily understood, and be extended by others (or even by yourself months later). As we advance in our career, mastering the principles of clean code becomes critical for long-term project success and team efficiency.

1. Clarity Over Cleverness

Example:

# Bad
def calct(a, b):
    return a + b

# Good
def calculate_tax(income, tax_rate):
    return income * tax_rate

2. Function Design: Single Responsibility Principle (SRP)

3. Consistent Naming Conventions

Example:

# Bad
def calculate_discount(price):
    return price * 0.1  # What does 0.1 represent?

# Good
DISCOUNT_RATE = 0.1

def calculate_discount(price):
    return price * DISCOUNT_RATE

4. Meaningful Comments

Example:

# Bad
i += 1  # Increment i by 1

# Good
i += 1  # Adjust for 0-based index

5. Avoid Repetition

Example:

# Bad
def create_admin_user():
    user = User()
    user.role = 'admin'
    user.save()

def create_guest_user():
    user = User()
    user.role = 'guest'
    user.save()

# Good
def create_user(role):
    user = User()
    user.role = role
    user.save()

6. Avoid Premature Optimization

Example:

# Bad
# Assuming this loop is slow without measuring:
for i in range(1000000):
    # Some processing

# Good
# Profiled and found the loop isn’t the bottleneck, so no premature changes are made

7. Error Handling and Exceptions

Example:

# Bad
try:
    data = load_data()
    process(data)
except:
    pass  # Silently ignores all exceptions

# Good
try:
    data = load_data()
    process(data)
except FileNotFoundError as e:
    log_error(f"File not found: {e}")
    raise
except DataProcessingError as e:
    log_error(f"Processing error: {e}")
    raise

8. Modular Design

Example:

# Bad
def process_user_data(user_data):
    # Validation
    if not validate(user_data):
        raise ValueError("Invalid data")
    # Database interaction
    db.save(user_data)
    # Notification
    send_email(user_data.email)

# Good
def process_user_data(user_data):
    validate_data(user_data)
    save_to_db(user_data)
    send_notification(user_data)

9. Write Tests and Practice TDD (Test-Driven Development)

Example:

def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

10. Code Reviews and Pair Programming

11. Refactor Ruthlessly

Refactoring Example:

# Before
def process_data(data):
    if not isinstance(data, list):
        return
    result = []
    for item in data:
        if isinstance(item, dict):
            result.append(item.get("value"))

# After
def process_data(data):
    if not isinstance(data, list):
        return
    return [item.get("value") for item in data if isinstance(item, dict)]