Does the Single Responsibility Principle work in OOP?

前端 未结 7 1069
面向向阳花
面向向阳花 2020-12-03 15:17

I am struggling to understand how the Single Responsibility Principle can me made to work with OOP.

If we are to follow the principle to a tee, then are we not left

7条回答
  •  庸人自扰
    2020-12-03 16:11

    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.

提交回复
热议问题