Single responsibility
Lesson 22 of 28 in Coddy's Clean Code - Write better code using Python course.
"There should never be more than one reason for a class to change."
Single responsibility principle (SRP) states that every class and function should have only one job or one reason to change.
Goals -
- Create high cohesive and robust classes and functions.
- Promote class composition
- Avoid code duplication
Challenge
MediumYou are given class Person which have a method save to save the person to the database.
In the given code the class have two responsibilities:
- Create and manage person object
- Save the person to database
Your task is to make sure Person has only one responsibility.
- Create class
Databasewith thesavemethod. - Create connection between
PersonandDatabase
There are many options for doing this task we are aiming for one specifing use the hints when needed!
Note that when we create seperate class for Database we can manage all "Database related" stuff in one place!
Try it yourself
class Person:
def __init__(self, name):
self.name = name
def save(self):
print('Saving person with name "%s"' % self.name)