Clean Code Principles
Clean code is readable, maintainable, and well-organized. Follow naming conventions, keep functions small, use meaningful names, and write self-documenting code.
15 min•By Priygop Team•Updated 2026
Clean Code
Clean Code
# ❌ BAD: Hard to read
def p(d,t):
r=d/t
return r
# ✅ GOOD: Self-documenting
def calculate_speed(distance_km: float, time_hours: float) -> float:
"""Calculate speed in km/h."""
if time_hours <= 0:
raise ValueError("Time must be positive")
return distance_km / time_hours
# ❌ BAD: Magic numbers
def calc(amount):
return amount * 0.18
# ✅ GOOD: Named constants
TAX_RATE = 0.18
def calculate_tax(amount: float) -> float:
"""Calculate tax based on the standard rate."""
return amount * TAX_RATE
# ❌ BAD: Long function doing many things
# ✅ GOOD: Small, focused functions
def validate_email(email):
return "@" in email and "." in email
def format_user(name, email):
return {"name": name.title(), "email": email.lower()}
def process_registration(name, email):
if not validate_email(email):
return {"error": "Invalid email"}
user = format_user(name, email)
return {"success": True, "user": user}
# Demo
result = process_registration("alice smith", "Alice@Email.COM")
print(f"Result: {result}")
# Clean code principles:
print("\n=== Clean Code Principles ===")
principles = [
"Use descriptive names (user_age, not x)",
"Keep functions short (one responsibility)",
"Avoid magic numbers (use constants)",
"Write docstrings for public functions",
"DRY — Don't Repeat Yourself",
"KISS — Keep It Simple, Stupid",
"Handle errors explicitly",
"Use type hints for clarity",
]
for p in principles:
print(f" • {p}")Tip
Tip
Follow PEP 8 for style, PEP 257 for docstrings. Use Black for formatting, isort for imports, flake8/ruff for linting.
Diagram
Loading diagram…
BEM keeps CSS flat, readable, and avoids specificity wars
Common Mistake
Warning
Inconsistent coding style across a project. Use automated formatters (Black) to enforce consistency without manual effort.
Quick Quiz
Practice Task
Note
(1) Run ruff or flake8 on your code. (2) Fix all warnings. (3) Add a pre-commit hook for auto-formatting.