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?

  • 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
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.

  • 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'. – user251748 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.