Menu
Coddy logo textTech

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 icon

Challenge

Medium

You 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:

  1. Create and manage person object
  2. Save the person to database

Your task is to make sure Person has only one responsibility.

  • Create class Database with the save method.
  • Create connection between Person and Database

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)

All lessons in Clean Code - Write better code using Python