Sobes.tech
Junior — Middle

Can you give an example of when applying the Single Responsibility Principle (SRP) helps improve code quality?

sobes.tech AI

Answer from AI

The Single Responsibility Principle (SRP) helps improve code quality by separating different responsibilities into separate classes or functions. This makes maintenance, testing, and extension easier.

For example, if you have a class that both reads data from a file and processes it, it's better to separate these tasks:

class FileReader:
    def read(self, filepath):
        with open(filepath, 'r') as file:
            return file.read()

class DataProcessor:
    def process(self, data):
        # data processing
        return data.upper()

# Usage
reader = FileReader()
data = reader.read('data.txt')
processor = DataProcessor()
result = processor.process(data)

This approach simplifies changing the reading or processing logic without risking to break other parts of the code.