๐Ÿงผ Clean Code

Code that reads like a story

โ† Back to Architecture

๐Ÿ“– Why clean code?

Code is read far more often than it's written. You โ€” or a teammate โ€” will come back in 6 months and need to understand it. Clean code means writing for humans, not just computers.

Two programs can do the exact same thing, but one is a joy to read and the other is a headache. Let's learn the difference.

๐Ÿท๏ธ Rule 1: Good names

Names should tell you what something is or does. Avoid x, data2, and tmp.

# ๐Ÿ˜ต Mystery code d = 86400 t = s / d # ๐Ÿ˜€ Clear code SECONDS_PER_DAY = 86400 days = total_seconds / SECONDS_PER_DAY

๐Ÿ’ก Naming guide

  • Variables & functions: snake_case
  • Constants: UPPER_CASE
  • Functions are verbs (calculate_total), variables are nouns (total_price).

๐Ÿ”ง Rule 2: Small functions that do one thing

A function should do one job. If you need "and" to describe it, split it up.

def calculate_area(width, height): return width * height def calculate_perimeter(width, height): return 2 * (width + height)

๐Ÿšซ Rule 3: Don't Repeat Yourself (DRY)

If you copy-paste code, turn it into a function instead. One place to fix bugs, one place to improve.

# Instead of repeating the greeting three times... def greet(name): return "Hello, " + name + "!" print(greet("Mia")) print(greet("Leo"))

๐Ÿ’ฌ Rule 4: Comments explain WHY, not WHAT

A comment like # add 1 to x is useless โ€” the code already says that. Good comments explain why something is done, or warn about a tricky case.

# Good: explains the reasoning # Tax is applied only after the discount, per store policy final = (price - discount) * 1.08

โœ… What you learned

  • Write code for humans to read.
  • Use descriptive names; functions are verbs, variables are nouns.
  • Keep functions small โ€” one job each.
  • DRY: don't repeat yourself.
  • Comments explain why, not what.