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 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

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

7. Error Handling and Exceptions

8. Modular Design

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

10. Code Reviews and Pair Programming

11. Refactor Ruthlessly