Clean code is code that is easy to understand and easy to change. Here are the principles I follow.
Naming
Names should reveal intent:
# Bad
d = 86400
# Good
SECONDS_PER_DAY = 86400
Functions
Functions should do one thing and do it well:
# Bad: Does too many things
def process_user(user):
validate(user)
save_to_db(user)
send_email(user)
log_activity(user)
# Good: Single responsibility
def create_user(user_data):
user = validate_user_data(user_data)
return save_user(user)
Comments
Code should be self-documenting. Comments explain why, not what:
# Bad: Explains what (obvious from code)
# Increment counter by 1
counter += 1
# Good: Explains why
# Compensate for zero-indexing in legacy API
counter += 1
Error Handling
Don't ignore errors:
# Bad
try:
do_something()
except:
pass
# Good
try:
do_something()
except SpecificError as e:
logger.error(f"Failed to do something: {e}")
raise
The Boy Scout Rule
Leave the code cleaner than you found it. Every commit should improve the codebase slightly.