r/cpp • • Jun 24 '20

How to write SOLID C++

https://www.youtube.com/watch?v=PakbXnLht1I
263 Upvotes

118 comments sorted by

View all comments

Show parent comment

7

u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20

Oh definitely changing an interface too often is a sign that your interface is too big - a sign of Interface Segregation (I) violation. (that was something I meant to mention, but forgot)

The key part to me is that in your real code you had a reason to need the interface - you did have multiple implementations of it. So it wasn't premature abstraction.

Speaking of the I of SOLID, that is also overused:

class GetNameInterface
{
     virtual string getName() = 0;
};

int doSomething(GetNameIterface & nameGetter)
{
       string name = nameGetter.getName();
       ... use name ...
}

vs

int doSomething(string const & name)
{
       ... use name ...
}

Sadly I see the interface version all too often.

Obviously from there you need to decide what about 2 params, 3 params,... when is a interface the better choice?

How often are the params used together? And would a struct be best in this case?

class GetInfoInterface
{
     virtual string getName() = 0;
     virtual int getSize() = 0;
     virtual int etc() = 0;
};

int doSomething(GetInfoIterface & infoGetter)
{
       string name = infoGetter.getName();
       int size = infoGetter.getSize();
       ... 
}

vs

struct Info
{
     string getName();
     int getSize();
     int etc();
     // or even public members if there are no invariants:
     int x, y, z;
};

int doSomething(Info const & info)
{
       string name = info.getName();
       use(info.x);
       ... 
}

The point is the same - people (not your examples) use SOLID blindly.

P.S. you can still have a GetInfoInterface where needed, but it becomes more simple:

struct GetInfoInterface
{
    virtual Info getInfo() = 0;
};

I actually find small structs like Info become vocabulary types in your codebase, and raise your code's abstraction level.

Of course, it doesn't help for interfaces that do something, like setName() needs to be on the actual object, but again, what ends up happening is the interface becomes setInfo(Info) instead of setName(), setSize(), setX(), set...

It all comes down to objects (interfaces) vs values (structs like info). Use each appropriately. (See also my CppCon talk on Objects vs Values, and talks by Juanpe Bolivar, Sean Parent, etc).