What are the best practices for clean coding?
Arpit Nuwal

 

1. Use Meaningful & Descriptive Names πŸ“›

βœ… Variables & Functions Should Be Self-Explanatory
❌ x = 10
βœ… maxRetryAttempts = 10

βœ… Use Verb-Noun Format for Functions
❌ data()
βœ… fetchUserData()

πŸ’‘ Why? Improves readability and eliminates the need for excessive comments.


2. Keep Functions Small & Focused πŸ”

βœ… Follow the Single Responsibility Principle (SRP)
βœ… One function = One task

❌ Bad Example (Too Many Responsibilities)

python
def processOrder(order): validateOrder(order) applyDiscount(order) updateInventory(order) sendConfirmationEmail(order)

βœ… Good Example (Each Function Does One Thing)

python
def validateOrder(order): # Validation logic def applyDiscount(order): # Discount logic def updateInventory(order): # Update stock def sendConfirmationEmail(order): # Send email

πŸ’‘ Why? Easier debugging, testing, and reuse.


3. Write DRY (Don’t Repeat Yourself) Code πŸ—οΈ

βœ… Avoid Duplicate Code, Use Reusable Functions

❌ Bad Example (Repetitive Code)

python
total = price * quantity tax = price * 0.15 discount = price * 0.1

βœ… Good Example (Refactored with Functions)

python
def calculatePercentage(value, percentage): return value * (percentage / 100) total = price * quantity tax = calculatePercentage(price, 15) discount = calculatePercentage(price, 10)

πŸ’‘ Why? Prevents inconsistencies and makes code easier to update.


4. Follow Consistent Formatting & Indentation πŸ“

βœ… Stick to a consistent style (PEP 8 for Python, Airbnb for JS, etc.)
βœ… Use proper spacing & line breaks for clarity
βœ… Use a linter (ESLint, Prettier, Black) to enforce style

πŸ’‘ Why? Consistent formatting makes it easier for others to read and collaborate.


5. Avoid Magic Numbers & Hardcoded Values πŸ”’

βœ… Use Constants Instead

❌ Bad Example (Magic Numbers)

python
if user_age > 18: print("Access granted")

βœ… Good Example (Use Named Constants)

python
LEGAL_AGE_LIMIT = 18 if user_age > LEGAL_AGE_LIMIT: print("Access granted")

πŸ’‘ Why? Increases clarity and simplifies future changes.


6. Handle Errors & Exceptions Gracefully 🚨

βœ… Use try-except blocks (Python) or try-catch (JS, Java, etc.)
βœ… Log errors properly instead of hiding them
βœ… Provide meaningful error messages

❌ Bad Example (No Exception Handling)

python
result = 10 / user_input # Crashes if user_input is 0

βœ… Good Example (Handles Errors Gracefully)

python
try: result = 10 / user_input except ZeroDivisionError: print("Error: Division by zero is not allowed")

πŸ’‘ Why? Prevents crashes and improves user experience.


7. Write Clear & Minimal Comments πŸ“

βœ… **Comment WHY, not WHAT
βœ… Use docstrings for functions

❌ Bad Example (Obvious Comments)

python
x = x + 1 # Increment x by 1

βœ… Good Example (Explain Purpose, Not Code)

python
# Increase user score when they complete a task user_score += 10

πŸ’‘ Why? Too many unnecessary comments clutter the code.


8. Use Version Control & Meaningful Commit Messages πŸ—‚οΈ

βœ… Write concise, informative commit messages

❌ Bad Commit Message:

 
Fix stuff

βœ… Good Commit Message:

rust
Refactored user authentication logic for better readability & performance

πŸ’‘ Why? Helps track changes and understand past modifications.


9. Optimize Code for Performance ⚑

βœ… Use efficient data structures & algorithms
βœ… Minimize unnecessary loops & computations

❌ Bad Example (Unoptimized Loop)

python
for i in range(len(users)): if users[i] == "John": print("User found")

βœ… Good Example (More Efficient)

python
if "John" in users: print("User found")

πŸ’‘ Why? Reduces execution time and memory usage.


10. Write Unit Tests βœ…

βœ… Test edge cases & unexpected inputs
βœ… Use frameworks like PyTest (Python), Jest (JS), JUnit (Java)

πŸ’‘ Why? Prevents future bugs and ensures code reliability.