What the principles are for
Principles are not laws but rules grown from experience: they make code cheaper to change. They can pull against each other, so you need to know each one and keep a balance. Related: anti-patterns, SRP.
DRY: Don't Repeat Yourself
Every piece of knowledge should live in one place in the system. If the same check is repeated in two functions, it is easy to forget one when the rule changes.
def create_user(name, email):
if not name.strip():
raise ValueError("name is empty")
if "@" not in email:
raise ValueError("bad email")
return {"name": name, "email": email}
def update_user(user, name, email):
if not name.strip():
raise ValueError("name is empty")
if "@" not in email:
raise ValueError("bad email")
user.update(name=name, email=email)
return user
u = create_user("Ann", "ann@mail.io")
print(update_user(u, "Anna", "anna@mail.io")){'name': 'Anna', 'email': 'anna@mail.io'}Now the rule lives in one place:
def validate(name, email):
if not name.strip():
raise ValueError("name is empty")
if "@" not in email:
raise ValueError("bad email")