DEV Community

Clean Code Studio
Clean Code Studio

Posted on • Edited on

1

Python Single Responsibility Design Pattern (Code Example)

Python Single Responsibility Design Pattern

_"Every module, class, or function should have only one reason to change."_

Example of the Single Responsibility Principle design pattern implemented in Python code:

class Journal:
def __init__(self):
self.entries = []
self.count = 0
def add_entry(self, text):
self.entries.append(f"{self.count}: {text}")
self.count += 1
def remove_entry(self, pos):
del self.entries[pos]
def __str__(self):
return "\n".join(self.entries)
class PersistenceManager:
@staticmethod
def save_to_file(journal, filename):
file = open(filename, "w")
file.write(str(journal))
file.close()
@staticmethod
def load_from_file(filename):
file = open(filename, "r")
print(f"Loading journal from {filename}")
data = file.read()
print(data)
file.close()
j = Journal()
j.add_entry("I cried today.")
j.add_entry("I ate a bug.")
print(f"Journal entries:\n{j}")
file = r"C:\temp\journal.txt"
PersistenceManager.save_to_file(j, file)
# Verify that the journal was saved
j2 = Journal()
PersistenceManager.load_from_file(file)

In this example, the Journal class has a single responsibility, which is to store and manage journal entries.

The PersistenceManager class, on the other hand, has a single responsibility, which is to persist the Journal to different storage mediums (file, web, etc.).

This separation of responsibilities makes the code more maintainable and easier to understand, as changes to one class won't affect the other.

Python
Design Patterns
Clean Code Studio
Python Design Patterns
Single Responsibility Principle (SRP)

Top comments (0)