0

Assume we have the following class:

class Foo
{
public:
    void func()
    {
    _func1();
    _func2();
    }
private:
    virtual void _func1();
    virtual void _func2();
};

This class, from one side, specifies the interface (foo method), and, from the other side, it defines the implementation (first we call _func1, then _func2). So does it violate the Single Responsibility principle?

undermind
  • 117
  • 1
  • 3
    It does one thing: provides `func()`. How it implements `func()`, in this case by spreading the functionality over `_func1()` and `_func2()` is an implementation detail unrelated to the SRP. – David Arno Sep 15 '17 at 12:26

2 Answers2

1

No. Not per se.

If you rephrase SRP as »doing one thing only«, you would be right, but that is not, what SRP means.

You should read SRP more like: »dealing with one level of abstraction«

What »one level of abstraction« is, is left to the reader as an exercise.

Thomas Junk
  • 9,405
  • 2
  • 22
  • 45
  • 2
    That is the fun thing about principles: they say, "it should look like this" and then you have to interpret 'it', 'should', 'look like' and 'this'. –  Sep 15 '17 at 13:16
0

Indeed, it does - to some degree. That's why there is another pattern to achieve effectively the same, but without violating the SRP: the strategy pattern, used in a "context class" like this:

class Context
{
private:
    IStrategy *_strategy;

public:
    void func()
    {
      _strategy->_func1();
      _strategy->_func2();
    }
};

However, as always when making design decisions, this is a trade-off: using the strategy pattern produces a little bit more boilerplate code, and the virtual functions now must be made public instead of protected, so it loosens encapsulation to some degree. You will have to trade "YAGNI" vs. "SRP" here.

For small classes or template methods, the "template method pattern" is totally sufficient, for bigger ones, "strategy" may be the better choice. And sometimes, using no pattern at all is the best solution of all.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565