Does the Single Responsibility Principle work in OOP?

…衆ロ難τιáo~ 提交于 2019-11-28 10:18:26

I like to state the single responsibility principle this way: "Every thing you write -- every module, class, interface, or method, should have one job. It should do the whole job and only that job.

Notice that some of these things you write are big (modules), some are small (methods), some are in between (classes), and some of the big things are made of smaller things.

That is not a problem, because jobs or responsibilities also come in various sizes and can be decomposed hierarchically. The job of the police force, for example, is to "protect and serve" -- one job, that decomposes into "patrol the streets", "solve crimes", etc., which can each be handled by a different unit. That creates the need for coordination (a different job), and the job of each unit breaks down into jobs for individual officers, etc.

For every big job, there are many ways to break it down into smaller jobs, and every one of those can be modeled by a software design that adheres to SRP and the other SOLID principles. Deciding how to break a problem down is a big part of the art of software design.

A class shall handle one topic, that's its single responsibility. A class Car could contain methods like startEngine() or attributes like weight:

class Car
{
    int weight;
    void startEngine();
    void stopEngine();
}

Of course you can break up this class more. For example by defining a class for the engine:

class Engine
{
    start();
    stop();
}

class Car
{
    Engine engine;
    int weight;
}

But you shall not define seperate classes for starting and stopping the engine like:

class EngineStop
{
    stop();
}

class EngineStart
{
    start();
}

class Car
{
    EngineStart engineStart;
    EngineStop engineStop;
    int weight;
}

The principle says to break up classes as reasonable as possible to achieve abstractness. Abstracting too deep violates this principle.

Single Responsibility term was introduced by Rober C. Martin. Main motto of this principle is a reason to change. A class or module should have one, and only one, reason to be changed.The major benefit of this principle is that is makes the class more robust. Changes in one class or module doesn't break the other part.

It prevents an object from becoming a God Object that is an example of Anti-Pattern. It also prevents from Ravioli code (A source code with lots of tiny, tightly-coupled objects).

Hence, Single responsibility principle is an important part of good source code design in OOP.

Before you go into decomposing responsibilities, you should have an idea on what the class is supposed to do. It's supposed to do that thing and only that thing as Matt mentioned in his answer. Implement that idea in the simplest way possible just to make it work. That's when you go about decomposing the code you wrote into responsibilities.

The important thing to consider when you break down your code is to make sure that it is readable after breaking it down.

Tracy Moody

I tend to think of the Single Responsibility Principle (and really a lot of the rules of thumb, patterns, and models) as a general way of thinking about problems. It's meant to guide you toward improvements to your code, but not necessarily prescribe exactly what a solution looks like. Because ultimately software design is a wicked and subjective problem.

I don't think that SRP should always lead to a bunch of single function classes. Though these may sometimes occur if you have some complex logic that you want to abstract away. In general, though, you should trend toward classes with highly cohesive functionality where methods:

  1. Are all related to the same abstraction(s)

    • Don't have a mish-mash of functionality that isn't related to each other in the same class.
    • Keep things like business logic separate from UI separate from I/O
  2. Share common dependencies

    • Related functionality usually has related dependencies.
    • I usually consider breaking up a class when I start getting more than around 7 dependencies. Often there's a class I can extract to move a few of the dependencies into a more cohesive unit.
  3. All operate at the same level of abstraction

    • Your abstractions should be hierarchical; some classes should orchestrate other classes to accomplish a workflow. Other classes will handle the specific implementation-level details.
    • Avoid having orchestration-style classes getting into the nitty-gritty. You don't want detailed operations to live side by side (in the same function or even the same class) with abstractions of more complex operations.

You actually want to try to group as much functionality as you can, while maintaining the above conditions and keeping in mind how understandable your abstraction is. Ultimately the goal of the Single Responsibility Principle is to help manage complexity and make the code more understandable.

This is one of the common misunderstanding of Single Responsibility Principle that a class should have only one function. A class is responsible for only one thing doesn't mean a class should have only one function. Single Responsibility Principle means logically separate your functionality into different classes instead of mixing up things.

One very simple example is, say if you are creating a Calculator you can add all functionalities purely for the calculator in the same class (add, subtract, multiply, divide etc.). You don't need to create a separate class for each of the functionality of calculator. But if you want to print calculated result to a printer then don't write the logic of printing to printer inside calculator class because printing to the printer is not the responsibility of calculator class. Create a separate class for the printer and write printing related logic in that class. If you are writing printing functionalities inside Calculator class then you are violating Single Responsibility Principle.

I quote Robert C. Martin from his book Clean Code:

The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change. This principle gives us both a definition of responsibility, and a guidelines for class size. Classes should have one responsibility—one reason to change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!