Skip to content
Mishel's Devnotes.
software development

Single Responsibility Principle (SRP) Explained: SOLID with Examples

In this article, we'll focus on the first principle: Single Responsibility Principle. The Single Responsibility Principle is commonly expressed as: A class should have one, and only one, reason to change.

There's a certain type of class you'll eventually encounter if you work on software projects long enough.

It starts small. Maybe it has three methods and a perfectly reasonable name like InvoiceService.

Then someone adds a new feature. Another developer adds database operations. Someone else adds email notifications. A few bugs get fixed, some logging is introduced, and a year later, the class is 1,500 lines long.

It calculates invoices, talks to the database, sends emails, generates PDF documents, and probably makes coffee when nobody is looking.

Every developer is afraid to touch it, but somehow, every new requirement ends up there.

The funny thing is that nobody necessarily made a terrible decision. The class probably made sense when it was first created.

The problem was that it kept collecting responsibilities.

This is exactly the kind of situation the Single Responsibility Principle (SRP) is meant to prevent.

SRP is the first principle in SOLID. It's also one of the easiest principles to remember and one of the easiest to misunderstand.

Because despite what the name might suggest, the Single Responsibility Principle doesn't mean that a class should do only one thing.

There's a little more to it than that.

What is SOLID?

SOLID is a collection of five software design principles that help developers build applications that are easier to understand, maintain, test, and modify.

The principles are:

LetterPrinciple
SSingle Responsibility Principle
OOpen/Closed Principle
LLiskov Substitution Principle
IInterface Segregation Principle
DDependency Inversion Principle

The principles are closely associated with software engineer Robert C. Martin, commonly known as Uncle Bob. The SOLID acronym was later popularized by Michael Feathers.

SOLID isn't a programming language feature or a framework. You don't need a special library to follow these principles.

They are guidelines that help us make decisions about how code should be organized.

And as with most software design guidelines, applying them everywhere without thinking can make your application worse.

For now, let's focus on the first principle.

What is the Single Responsibility Principle?

The Single Responsibility Principle is commonly defined as:

A class should have one, and only one, reason to change.

Read that sentence carefully.

It doesn't say that a class should contain only one method. It doesn't say that every operation requires a separate class.

It says a class should have one reason to change.

But what does that actually mean?

Let's say you're developing a school management application. You create a class called ReportCardManager.

It calculates a student's average marks, prepares the report card, and saves it to a file.

All these operations are related to report cards, so keeping them together seems reasonable.

But imagine what happens when the school introduces new requirements.

The academic department changes how average marks are calculated.

The administration wants a different report card format.

The development team decides to store report cards in a database instead of text files.

You now have three different reasons to modify ReportCardManager.

These changes have very little to do with one another, yet they're all happening inside the same class.

That's the problem SRP tries to solve.

A useful way to understand the principle is:

Keep code that changes for the same reason together. Separate code that changes for unrelated reasons.

This is more helpful than simply telling developers to write smaller classes.

Robert C. Martin's explanation: What is an actor?

Robert C. Martin provides a more precise interpretation of SRP in his book Clean Architecture: A Craftsman's Guide to Software Structure and Design.

He explains the principle in terms of actors.

Here, an actor isn't an object in your application. It means a person or group of people who are responsible for a particular set of requirements.

Consider an invoicing application.

The finance team determines how taxes, discounts, and invoice totals should be calculated.

The team responsible for data storage might decide how invoices are persisted.

The marketing or customer communications team might change the wording of confirmation emails.

All these teams could request changes to the invoice-processing feature.

But those requests come from different responsibilities.

If one class contains the calculation rules, database operations, and email formatting, it may have to change whenever any of these groups introduces a new requirement.

Martin's actor-based interpretation helps us identify where one responsibility ends and another begins.

A practical question to ask when reviewing a class is:

"Who would ask me to change this code, and why?"

If the answers involve several unrelated groups of requirements, the class might contain too many responsibilities.

This doesn't mean every employee or department needs a separate class. Different people may request changes to the same business responsibility.

The point is to understand which requirements naturally belong together and which can change independently.

A realistic example of an SRP violation

Let's build a simple invoicing application.

When a customer purchases products, the application needs to calculate the invoice total, apply tax, save the invoice, and send a confirmation email.

We'll use pseudocode throughout this article so that the concepts are understandable regardless of whether you work with C#, Java, Python, or another language.

Pseudocode describes programming logic without requiring the exact syntax of a particular programming language. Keywords such as CLASS, FUNCTION, and RETURN should be easy to understand even if you've only recently started learning programming.

Here's one possible implementation.

CLASS InvoiceService

    FUNCTION CreateInvoice(customer, items)

        // Calculate subtotal
        subtotal = 0

        FOR EACH item IN items
            subtotal = subtotal +
                (item.price * item.quantity)
        END FOR

        // Apply 18% tax
        tax = ROUND(subtotal * 0.18, 2)

        total = subtotal + tax

        // Save invoice
        CONNECT TO database

        INSERT INTO invoices:
            customer.id
            subtotal
            tax
            total

        DISCONNECT FROM database

        // Send confirmation
        SEND EMAIL TO customer.email
            SUBJECT: "Your Invoice"
            MESSAGE: "Your total is " + total

        // Record activity
        APPEND "Invoice created" TO "app.log"

        RETURN total

    END FUNCTION

END CLASS

The example uses an illustrative 18% tax rate. The rate isn't intended to represent the tax rules of any particular jurisdiction.

Our InvoiceService calculates the invoice, saves it to the database, sends an email, and writes a log entry.

It might even work perfectly.

So what's wrong with it?

The problem is that the class has several different reasons to change.

Suppose the finance team introduces a new tax rate or discount rule. We need to modify InvoiceService.

Suppose the database structure changes. We modify the same class.

Suppose the confirmation email needs a new template. Again, we modify InvoiceService.

If the operations team wants structured logging instead of writing messages to a text file, guess which class might need another change.

Yes, our old friend InvoiceService.

The class has become responsible for business calculations, persistence, customer communication, and logging implementation.

These concerns are connected through the invoice-processing workflow, but they don't all need to be implemented inside the same class.

Why does this become a problem?

The first issue is testing.

Suppose we want to verify that the tax calculation works correctly.

For an invoice subtotal of ₹200, an 18% tax produces ₹36, giving a total of ₹236.

That's a simple calculation.

But with our current design, testing it through CreateInvoice() may require a database connection, email infrastructure, and access to a log file.

We've made a simple arithmetic test unnecessarily complicated.

The second issue is maintainability.

Imagine two developers working on different tickets. One is updating the tax calculation, while another is changing the email template.

Both need to modify the same class.

That increases the chance of merge conflicts, especially when the responsibilities share code or variables.

Then there's the risk of unexpected bugs.

When code for unrelated concerns is mixed together, a change in one part can accidentally affect another.

For example, changing the format of a total amount for an email might accidentally change the value saved to the database if both operations rely on the same formatted variable.

Finally, the business logic becomes harder to reuse.

What if another feature needs to calculate an invoice estimate without saving anything?

With the current design, calculation is tied to database storage and notifications.

We'd either need to duplicate the calculation or modify the existing class to introduce another mode of operation.

Neither is particularly attractive.

Refactoring the application using SRP

Let's improve the design by separating responsibilities.

We'll give the invoice data its own representation, keep the calculation rules together, and move storage and communication into appropriate components.

We'll also retain one component to coordinate the overall workflow.

The goal isn't to create more classes for the sake of it. It's to give each responsibility a clear home.

Step 1: Represent the invoice data

First, let's define the data required for an invoice.

CLASS InvoiceItem
    description
    quantity
    unitPrice
END CLASS


CLASS Invoice
    customerId
    items
    subtotal
    tax
    total
END CLASS

InvoiceItem represents a product or service included in the invoice.

Invoice contains the customer identifier, purchased items, and calculated amounts.

For this example, we're keeping these classes as simple data models.

That doesn't mean every model must contain only properties. A model can legitimately contain behavior that belongs to its own domain responsibility.

The important point is that an invoice doesn't need to know how to connect to a database or send an email merely because those operations involve invoice data.

Step 2: Separate the calculation rules

Now let's create InvoiceCalculator.

CLASS InvoiceCalculator

    taxRate = 0.18

    FUNCTION Calculate(customerId, items)

        subtotal = 0

        FOR EACH item IN items
            subtotal = subtotal +
                (item.quantity * item.unitPrice)
        END FOR

        tax = ROUND(subtotal * taxRate, 2)

        total = subtotal + tax

        RETURN NEW Invoice(
            customerId,
            items,
            subtotal,
            tax,
            total
        )

    END FUNCTION

END CLASS

This class owns the invoice calculation rules.

It knows how to calculate a subtotal, apply tax, and determine the final amount.

It doesn't connect to the database. It doesn't send notifications. It doesn't write log files.

If the finance team changes the tax calculation, we know where to make the change.

More importantly, the calculation can run without relying on external systems.

This makes it easier to test and reuse.

For example, an order preview could call the calculator to display an estimated total without creating a saved invoice.

That's something our original design made unnecessarily difficult.

Step 3: Separate database operations

Next, let's introduce a repository responsible for storing invoices.

A repository is a component that handles data persistence. It provides a way to save or retrieve data without requiring the rest of the application to understand every database operation.

We'll first define a simple contract.

INTERFACE InvoiceRepository

    FUNCTION Save(invoice)

END INTERFACE

An interface describes an operation that implementations agree to provide.

Now we can create a database implementation.

CLASS SqlInvoiceRepository
    IMPLEMENTS InvoiceRepository

    FUNCTION Save(invoice)

        CONNECT TO database

        INSERT INTO invoices:
            invoice.customerId
            invoice.subtotal
            invoice.tax
            invoice.total

        DISCONNECT FROM database

    END FUNCTION

END CLASS

The repository is responsible for saving invoices.

It doesn't know how tax is calculated or what the confirmation email should say.

If we later move to a different database, the persistence implementation can change without requiring us to rewrite the calculation rules.

Notice that we've introduced an interface here.

An interface isn't mandatory for SRP. We could have used a concrete repository class.

We're using one because it provides a useful boundary: the rest of the application needs something capable of saving invoices, not necessarily one specific database implementation.

This will also help us when we write tests.

Step 4: Separate notifications

Now let's move email notifications into their own component.

INTERFACE InvoiceNotifier

    FUNCTION Send(invoice, customerEmail)

END INTERFACE

And create an email implementation:

CLASS EmailInvoiceNotifier
    IMPLEMENTS InvoiceNotifier

    FUNCTION Send(invoice, customerEmail)

        SEND EMAIL TO customerEmail
            SUBJECT: "Your Invoice"
            MESSAGE:
                "Thank you for your purchase."
                "Total amount: " + invoice.total

    END FUNCTION

END CLASS

This class handles the notification.

If the email template changes, we modify the email notifier.

We don't need to open the invoice calculator or database repository.

If the application later supports another notification channel, such as SMS, we can add an appropriate implementation without mixing it into the calculation logic.

This is also where the Open/Closed Principle, the next principle in SOLID, can become relevant.

Step 5: Coordinate the workflow

We now have separate components for calculation, storage, and notification.

But an invoice still needs to be processed.

Someone has to coordinate the operations and decide their order.

Let's introduce InvoiceWorkflow.

CLASS InvoiceWorkflow

    CONSTRUCTOR(calculator, repository, notifier)

        this.calculator = calculator
        this.repository = repository
        this.notifier = notifier

    END CONSTRUCTOR


    FUNCTION CreateInvoice(customer, items)

        invoice = calculator.Calculate(
            customer.id,
            items
        )

        repository.Save(invoice)

        notifier.Send(
            invoice,
            customer.email
        )

        RETURN invoice

    END FUNCTION

END CLASS

Look at how much simpler the workflow has become.

We calculate the invoice, save it, and notify the customer.

The workflow doesn't need to know the tax formula, the database schema, or the email provider's API.

It only coordinates the operations.

There is one important detail: this workflow assumes that saving the invoice succeeds before the notification is sent. In a production application, we would also need to handle failures, retries, and situations where the database save succeeds but email delivery fails.

Those are legitimate workflow and reliability concerns. Separating responsibilities doesn't make them disappear.

Step 6: Put the components together

Now let's create the required objects and use our application.

calculator = NEW InvoiceCalculator()

repository = NEW SqlInvoiceRepository()

notifier = NEW EmailInvoiceNotifier()

workflow = NEW InvoiceWorkflow(
    calculator,
    repository,
    notifier
)

customer = {
    id: 101,
    email: "customer@example.com"
}

items = [
    {
        description: "Notebook",
        quantity: 2,
        unitPrice: 100
    }
]

invoice = workflow.CreateInvoice(
    customer,
    items
)

PRINT invoice.total

Output:

236

The calculation is:

Subtotal:   2 × 100 = 200
Tax (18%):  200 × 0.18 = 36

Total:      200 + 36 = 236

The invoice is also saved, and the notification component sends a confirmation message.

Functionally, we haven't changed what the application does.

We've changed how its responsibilities are organized.

And that can make a considerable difference when the application grows.

Does InvoiceWorkflow violate SRP?

This is usually where someone raises a hand and asks a very reasonable question.

"Hold on. You told us to separate responsibilities. But now InvoiceWorkflow calls the calculator, repository, and notifier. Isn't it doing three things?"

Not necessarily.

There's a difference between implementing several independent responsibilities and coordinating a workflow that uses those responsibilities.

Think about ordering food in a restaurant.

The waiter takes your order, communicates it to the kitchen, and arranges for the food to reach your table.

That doesn't mean the waiter is responsible for cooking the food, buying ingredients, or maintaining the kitchen equipment.

The waiter coordinates part of the service.

Our InvoiceWorkflow does something similar.

It knows the order in which invoice processing should happen, while the individual components know how to perform their assigned operations.

If the business changes the workflow, such as introducing an approval step before an invoice can be saved, the workflow component may need to change.

That's reasonable because the workflow is its responsibility.

If the tax rate changes, the workflow shouldn't need to change.

That belongs to InvoiceCalculator.

A class can coordinate several operations and still have one coherent responsibility.

This is an important distinction when applying SRP.

The biggest practical advantage: Easier testing

Let's talk about something developers actually care about: tests that don't require half the production environment to be running.

In our original InvoiceService, the calculation lived inside a method that also accessed a database, sent email, and wrote logs.

After refactoring, InvoiceCalculator can be tested independently.

Here's a simple test in pseudocode.

TEST "Invoice calculation applies 18% tax"

    calculator = NEW InvoiceCalculator()

    items = [
        {
            description: "Notebook",
            quantity: 2,
            unitPrice: 100
        }
    ]

    invoice = calculator.Calculate(
        customerId = 101,
        items = items
    )

    ASSERT invoice.subtotal == 200
    ASSERT invoice.tax == 36
    ASSERT invoice.total == 236

END TEST

That's all we need.

No database connection. No email server. No file system setup.

We're testing calculation logic without involving unrelated infrastructure.

Now let's take this a little further.

Testing the complete workflow without a real database

Sometimes we want to test whether the invoice workflow saves an invoice and requests a notification.

But we don't necessarily want to use a real database or send an actual email during every unit test.

We can create test implementations of our interfaces.

For example, an in-memory repository:

CLASS InMemoryInvoiceRepository
    IMPLEMENTS InvoiceRepository

    savedInvoices = EMPTY LIST

    FUNCTION Save(invoice)

        ADD invoice TO savedInvoices

    END FUNCTION

END CLASS

This repository stores invoices in memory instead of using a database.

We can also create a notifier that records notification requests.

CLASS RecordingInvoiceNotifier
    IMPLEMENTS InvoiceNotifier

    notifications = EMPTY LIST

    FUNCTION Send(invoice, customerEmail)

        ADD {
            invoice: invoice,
            email: customerEmail
        } TO notifications

    END FUNCTION

END CLASS

Now we can test the workflow.

TEST "Invoice workflow saves and notifies"

    repository = NEW InMemoryInvoiceRepository()

    notifier = NEW RecordingInvoiceNotifier()

    calculator = NEW InvoiceCalculator()

    workflow = NEW InvoiceWorkflow(
        calculator,
        repository,
        notifier
    )

    customer = {
        id: 101,
        email: "customer@example.com"
    }

    items = [
        {
            description: "Pen",
            quantity: 1,
            unitPrice: 10
        }
    ]

    workflow.CreateInvoice(customer, items)

    ASSERT COUNT(repository.savedInvoices) == 1

    ASSERT COUNT(notifier.notifications) == 1

    ASSERT notifier.notifications[0].email
        == "customer@example.com"

END TEST

This test verifies that the workflow uses the repository and notifier correctly.

We didn't need a live database or email service.

The tests can run quickly and predictably because the external dependencies have been replaced with controlled test implementations.

Of course, we'd still need integration tests to verify that the real SQL repository and email provider work correctly.

But for testing the workflow itself, these stand-ins are often enough.

That's one of the practical advantages of separating responsibilities and introducing useful boundaries.

A smaller example: The User class

SRP violations don't always appear in enormous classes.

Sometimes they're hiding inside a class with just a few methods.

Consider this example:

CLASS User

    id
    email
    passwordHash

    FUNCTION Save()

        CONNECT TO database
        SAVE user details

    END FUNCTION


    FUNCTION SendWelcomeEmail()

        SEND EMAIL TO this.email

    END FUNCTION

END CLASS

It's a small class, and both methods involve the user.

But think about the reasons it might change.

Database requirements could change how the user is saved.

Communication requirements could change the welcome email.

Those are unrelated concerns.

A more focused design might look like this:

CLASS User

    id
    email
    passwordHash

END CLASS


CLASS UserRepository

    FUNCTION Save(user)

        SAVE user TO database

    END FUNCTION

END CLASS


CLASS WelcomeEmailSender

    FUNCTION Send(user)

        SEND welcome email TO user.email

    END FUNCTION

END CLASS

Now persistence and communication have separate homes.

But there's an important point here.

This doesn't mean the User class must contain only data.

Suppose we add a method such as:

FUNCTION ChangeEmail(newEmail)

    VALIDATE newEmail

    this.email = newEmail

END FUNCTION

That behavior may reasonably belong inside User, because changing the user's email address according to the domain rules is part of managing the user's state.

The point isn't to remove every method from our models.

It's to keep behavior with the responsibility that owns it.

Does SRP mean a class should have only one method?

Absolutely not.

Let's look at a bank account.

CLASS BankAccount

    balance = 0

    FUNCTION Deposit(amount)

        IF amount <= 0
            THROW "Invalid deposit"
        END IF

        balance = balance + amount

    END FUNCTION


    FUNCTION Withdraw(amount)

        IF amount <= 0
            THROW "Invalid withdrawal"
        END IF

        IF amount > balance
            THROW "Insufficient balance"
        END IF

        balance = balance - amount

    END FUNCTION


    FUNCTION GetBalance()

        RETURN balance

    END FUNCTION

END CLASS

The class contains three methods.

Does that mean it has three responsibilities?

No.

All these methods belong to the same coherent responsibility: maintaining the balance and basic rules of a bank account.

They work together and operate on the same state.

Now imagine adding a method called SendPromotionalEmail().

That introduces marketing communication into a class responsible for account behavior.

The bank's marketing campaigns can change independently of the rules governing deposits and withdrawals.

That would be a reason to separate the functionality.

The number of methods isn't the deciding factor.

A class can contain twenty methods and have one coherent responsibility.

Another class can contain just two methods and still combine unrelated responsibilities.

SRP is about cohesion and reasons to change, not method count.

SRP also applies beyond classes

Although SRP is usually discussed in object-oriented programming, the underlying idea can be useful at other levels of software design.

For example, consider a function that calculates monthly sales and immediately prints a report.

FUNCTION PrintMonthlySales(orders)

    total = 0

    FOR EACH order IN orders
        total = total + order.amount
    END FOR

    PRINT "Total sales: " + total

END FUNCTION

This is a small function, and for a simple script it might be perfectly reasonable.

But imagine that the calculation becomes more complicated and the same sales total is needed by an API, a dashboard, and a PDF report.

Now the calculation is tied to console output.

We could separate the logic:

FUNCTION CalculateMonthlySales(orders)

    total = 0

    FOR EACH order IN orders
        total = total + order.amount
    END FOR

    RETURN total

END FUNCTION

And let another function handle presentation:

FUNCTION PrintMonthlySales(total)

    PRINT "Total sales: " + total

END FUNCTION

The calculation can now be reused without requiring console output.

The same idea can apply at the module or service level.

For example, a large service that manages payroll, recruitment, attendance, and employee marketing communications may contain several distinct business capabilities.

That doesn't automatically mean every capability should become a separate microservice. Splitting services introduces its own complexity, including network communication, deployment, and data consistency concerns.

The important idea remains the same: understand which responsibilities belong together and which are better kept apart.

How to spot an SRP violation in your own project

The best way to identify possible SRP violations is to look at how code changes over time.

A class might look perfectly reasonable today. Six months later, it may have accumulated several unrelated responsibilities.

Here are a few warning signs worth watching.

The class has become everyone's favorite dumping ground

Names like Manager, Helper, Utility, and Service aren't inherently bad.

But they can become suspicious when nobody can clearly explain what a class is responsible for.

For example, InvoiceCalculator communicates a much clearer purpose than CommonManager.

If a class handles unrelated operations simply because they all involve the same business entity, it's worth examining.

Every feature request touches the same class

Look at your version control history.

If changes to tax calculations, database operations, and email templates repeatedly modify the same class, you may have responsibilities that should be separated.

This is especially noticeable when different developers frequently work on the same file for unrelated tickets.

Simple tests require complicated setup

Suppose you want to test a calculation but need to configure a database, file paths, an email provider, and application settings.

That's a sign that the calculation may be unnecessarily coupled to infrastructure.

Not every dependency is a problem, but unrelated dependencies make tests harder to write and maintain.

You have to understand unrelated code to make a small change

Imagine being assigned a ticket to update the wording of a confirmation email.

If you need to read hundreds of lines of payment, inventory, and database code just to find the relevant message, the class may be handling too many concerns.

The class keeps growing

Line count alone doesn't prove an SRP violation.

A 300-line parser may have one perfectly reasonable responsibility.

A 30-line class could contain several unrelated responsibilities.

But rapid growth is still worth investigating, especially when new features keep being added to the same vague class.

These signs don't automatically mean your code is wrong. They tell you where to look more carefully.

Can we take SRP too far?

Definitely.

This is probably one of the easiest SOLID principles to overapply.

Imagine a developer learns that classes should have a single responsibility and immediately starts creating separate classes for every small method.

A simple invoice calculation now requires:

InvoiceCalculator
InvoiceTaxCalculator
InvoiceTaxRounder
InvoiceSubtotalCalculator
InvoiceDiscountCalculator
InvoiceCalculationCoordinator
InvoiceCalculationCoordinatorFactory

At some point, we need to ask whether the additional separation is actually helping.

Perhaps discounts, tax calculations, and rounding rules all belong to one cohesive pricing responsibility.

If they change together according to finance requirements, keeping them within the same component may be perfectly reasonable.

Splitting them into different classes just to make files smaller doesn't necessarily improve the design.

It may introduce more dependencies and force developers to jump between several files to understand one calculation.

Another mistake is creating interfaces for everything.

Interfaces can be useful when they define real boundaries, support alternative implementations, or make testing easier.

But adding an interface to every small class without a clear need is often unnecessary.

Sometimes a simple concrete class is enough.

There's also the temptation to design for every imaginary future requirement.

Maybe the application will support seventeen database engines, twelve notification services, and three different calculation systems one day.

Or maybe it won't.

Building abstractions for requirements that don't exist can make software more complicated without providing any practical benefit.

A useful guideline is to separate responsibilities when the separation solves a real design problem or protects against a reasonably expected change.

If your application is small and the responsibilities aren't causing any trouble, a simple design may be enough.

You can always refactor later as the requirements become clearer.

A practical checklist before creating or refactoring a class

Before splitting a class, I find these questions more useful than counting methods:

  • Can I clearly explain what this class is responsible for?
  • What kinds of requirements would cause me to change it?
  • Do those requirements come from unrelated business or technical concerns?
  • Can I test its important logic without involving unrelated external systems?
  • Am I separating these responsibilities because they change independently, or simply because the class looks large?
  • Will the new design genuinely make future changes easier?

You don't need a perfect answer to every question.

The idea is to think about responsibilities before introducing more abstractions.

Sometimes the right decision is to split a class. Sometimes it's to keep the existing design.

Both can be reasonable.

SRP vs separation of concerns

You may have heard about another design principle called Separation of Concerns.

The two concepts are related, but they aren't identical.

Separation of Concerns is a broader idea that encourages us to keep different concerns in appropriate parts of a software system.

For example, a web application might separate presentation logic, business rules, and database access.

SRP focuses more specifically on whether a class or module has one coherent responsibility and reason to change.

You can have a neatly organized project with separate folders for controllers, services, repositories, and models and still violate SRP.

For example:

Project
│
├── Controllers
│
├── Services
│   └── EverythingService
│
├── Repositories
│
└── Models

The folder structure looks respectable.

But if EverythingService calculates invoices, manages passwords, processes images, sends emails, and generates reports, the underlying problem hasn't disappeared.

We've simply given it a nice address.

Good software design depends on how responsibilities are organized, not just where the files are placed.

When should you actually apply SRP?

You don't need to begin every project with a complicated architecture.

When requirements are simple and unlikely to change independently, a straightforward implementation may be the best option.

But as the application grows, pay attention to which parts of the code keep changing.

If a class repeatedly changes for unrelated reasons, that may be a good time to refactor.

If tests are difficult because business logic is mixed with database and network operations, consider separating those concerns.

If different developers regularly modify the same class for unrelated requirements, responsibility boundaries may need attention.

The goal isn't to predict every future requirement on day one.

It's to recognize where the current design is making changes more difficult than necessary.

Martin Fowler's Refactoring: Improving the Design of Existing Code is a useful resource for learning how to improve existing code while preserving its behavior.

SRP is one of the principles that can help you decide what kind of refactoring might be worthwhile.

Final thoughts

The Single Responsibility Principle is easy to misunderstand because of its name.

"Single responsibility" sounds like one class, one method, one task.

But that's not the real point.

A class can contain many methods and still follow SRP if those methods belong to one coherent responsibility.

And a class with only one method can violate SRP if that method mixes unrelated business rules, database operations, and external communication.

The question that matters is why the code needs to change.

If unrelated requirements repeatedly force changes to the same class, it may be time to separate those responsibilities.

Our original InvoiceService combined calculations, database operations, notifications, and logging in one place. The refactored version gave those concerns clearer boundaries and left the workflow responsible for coordinating them.

That separation also made the calculations easier to test and allowed the workflow to be tested without depending on real external services.

But SRP isn't a law that requires every class to be tiny or every operation to have an interface.

It's a practical guideline for managing change.

The next time you open a class that seems to know everything about your application, ask yourself:

"Does all this code actually belong together, or did everyone just keep adding things here because the class already existed?"

If it's the second one, you've probably found a good place to start applying SRP.


Practice questions

Question 1: What does the Single Responsibility Principle state?

Answer: The Single Responsibility Principle states that a class or module should have one, and only one, reason to change.

In practice, this means grouping together behavior that changes for the same reason and separating responsibilities that change independently.

Question 2: What does Robert C. Martin mean by an actor?

Answer: An actor is a person or group of stakeholders responsible for a particular set of requirements.

For example, the finance team may request changes to invoice calculation rules, while the communications team may request changes to email templates.

If a class contains logic controlled by several unrelated sets of requirements, it may have multiple reasons to change.

Question 3: Does a class violate SRP if it contains ten methods?

Answer: Not necessarily.

A class can have ten or more methods if they all support one coherent responsibility.

For example, a bank account may have methods for depositing, withdrawing, and checking the balance because all these operations relate to managing the account's state.

Question 4: Identify the responsibilities in this pseudocode.

CLASS EmployeeManager

    FUNCTION CalculateSalary()
        // Calculate employee salary
    END FUNCTION

    FUNCTION SaveEmployee()
        // Save employee to database
    END FUNCTION

    FUNCTION SendBirthdayEmail()
        // Send birthday email
    END FUNCTION

END CLASS

Answer: This class contains salary calculation, employee persistence, and email communication.

These responsibilities can change independently.

A possible improvement would be to introduce separate components for payroll calculations, employee storage, and notifications.

Question 5: Why can separating calculation logic from database operations improve testing?

Answer: When calculation logic is independent of the database, we can test it directly using known inputs and expected outputs.

We don't need to create database connections or prepare external infrastructure just to verify a calculation.

This makes unit tests simpler and more predictable.

Question 6: What is the purpose of an in-memory repository in testing?

Answer: An in-memory repository is a test implementation that stores data in memory instead of a real database.

It allows us to verify that a workflow requests the correct storage operations without requiring actual database access.

Question 7: Does a workflow coordinator violate SRP if it calls several components?

Answer: Not necessarily.

A workflow coordinator can have one coherent responsibility: managing the sequence of operations in a particular business process.

It may call several components without implementing their internal responsibilities.

Question 8: Consider the following class.

CLASS Rectangle

    width
    height

    FUNCTION CalculateArea()
        RETURN width * height
    END FUNCTION

    FUNCTION CalculatePerimeter()
        RETURN 2 * (width + height)
    END FUNCTION

END CLASS

Does it violate SRP?

Answer: Not obviously.

Calculating the area and perimeter are closely related geometric behaviors of a rectangle.

There is no clear need to split them merely because the class contains two methods.

Question 9: You're working on a blogging application.

A class named BlogManager creates posts, converts Markdown into HTML, compresses images, sends subscriber emails, and stores articles in the database.

Would you consider refactoring it?

Answer: Yes, especially if those responsibilities are growing or changing independently.

Markdown conversion, image processing, email delivery, and persistence are different concerns.

They could be handled by focused components such as MarkdownRenderer, ImageProcessor, SubscriberNotifier, and BlogRepository.

A publishing workflow could coordinate the components needed when a post is published.

However, the exact design should depend on the size and requirements of the application.

Question 10: Is creating more classes always better?

Answer: No.

More classes and interfaces can introduce unnecessary complexity.

The goal of SRP is to make code easier to understand, test, and change.

Responsibilities should be separated when the boundaries are meaningful, not simply to reduce line counts.

Recommended reading

Robert C. Martin — *Agile Software Development: Principles, Patterns, and Practices*. Discusses object-oriented design principles, including SRP, and how they relate to maintainable software.

Robert C. Martin — *Clean Architecture: A Craftsman's Guide to Software Structure and Design*. Particularly useful for understanding SRP through the idea of actors and independent sources of change.

Martin Fowler — *Refactoring: Improving the Design of Existing Code*. Explains how to improve the structure of existing code without changing its observable behavior, including situations where responsibilities have become mixed together.

Enjoyed this article? Explore more notes on engineering and the tools behind it.

Browse all articles