SOLID - Single Responsibility Principle (SRP)
SOLID - Single Responsibility Principle (SRP)
The Single Responsibility Principle states that a class should have only one reason to change. In other words, a class should have a single responsibility or purpose. Here's an example:
class FileManager:
def read_file(self, file_path):
# Code to read the file
def write_file(self, file_path, content):
# Code to write content to the file
def compress_file(self, file_path):
# Code to compress the file
def decompress_file(self, file_path):
# Code to decompress the file
In the above example, the FileManager class violates the SRP because it has multiple responsibilities. It handles file reading, writing, compression, and decompression. A better approach would be to separate these responsibilities into distinct classes, each with a single responsibility. For example:
class FileReader:
def read_file(self, file_path):
# Code to read the file
class FileWriter:
def write_file(self, file_path, content):
# Code to write content to the file
class FileCompressor:
def compress_file(self, file_path):
# Code to compress the file
class FileDecompressor:
def decompress_file(self, file_path):
# Code to decompress the file
By adhering to the SRP, each class now has a single responsibility and can be independently modified without affecting the others. This promotes better maintainability and modularity in the codebase.