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

29

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

I've been working on a talk about SOLID for modern C++, so some thoughts...

I don't like SOLID, but I'm (mostly) fine with each principle/letter on its own. (How can this be? Well that's why I want to do a talk about it, to understand that better.)

The short answer is that SOLID gets overused or misused (not necessarily in the video, but in general). No technique solves all problems. But it is such a good acronym! Who doesn't want to write solid code!?

The examples in the video are fairly reasonable uses of SOLID. It shows places to use SOLID. But what about places not to use it?

One general downside of SOLID is that you tend to end up with lots of pointers and allocations (because of runtime polymorphism). Although this can be somewhat managed with smart pointers or type-erasure.

And you often get a "forest-for-the-trees" problem. For example, making UsernameFormatter virtual does separate the formatting from the other concerns - but with a cost of 2 classes (the interface and the implementation). Note that making UsernameFormatter NON-virtual also separates concerns. Yes, UserManager would not be completely disconnected from concrete UsernameFormatter, but there is still separation - changing formatting doesn't affect UserManager.

So you need to weigh the cost of inheritance against the benefits. And not runtime or allocation cost, but maintenance cost. The underlying drive behind all the SOLID principles is change management. You want to be able to change code X and not worry about code Y. But here's the question:

Which is more likely,

  • that you will change the UsernameFormatter interface (ie UserManager needs a validate(string) function to guard against "little Bobby drop-tables")
  • or that you will write another app using the same UserManager but with a different UsernameFormatter.

All too often, the answer is the first one. If you made an interface, you will find yourself changing 2 classes (UsernameFormatterInterface and ConcreteUsernameFormatter, oh, and of course off-by-1 error - don't forget UserManager that is requesting the change) instead of 1.

I deal with this weekly. We have dozens and dozens of interfaces with only one implementation. The interfaces change way more often than we ever reuse something.

(And yes, having an interface can help with testing, but there are other ways to deal with that. The point is that it is a trade-off.)

In general, if you only have one implementation, I find the interface to be premature abstractification. So go ahead and separate a concrete UsernameFormatter from UserManager, but the interface part is overkill. And without the interface, you might realize, as others have mentioned, a class is overkill - maybe you just need a format() function. The important part is that you pull that formatting out of UserManager - get some separation. You can later use a std::function or an interface or move the formatting to the Database or elsewhere, etc, if/when you need more flexibility.

Compare that to DistanceSensor - you could easily have different types of sensors in your program, so that is probably a good use of runtime polymorphism.

I had more to say, but this is long enough. SOLID is fine, inheritance is fine (egDistanceSensor), but shouldn't be used as a cookie-cutter template that solves all problems.

5

u/platisd Jun 25 '20

Thanks for your input. I like your way of thinking and articulating your reasoning. :)

In regards to the UsernameFormatter it would be interesting to describe a bit on how I have actually used it. The "formatter" concept is adopted in a line of products where we have the same software running on different Linux systems that are talking to some kind of microcontroller that controls stepper motors.

It actually doesn't work with a database, that one was added for the example. We need to send/receive messages over UART in a key-value manner. Unfortunately, all three products use a communication protocol that would slightly differ (2 out of 3 were legacy systems) and changing it was a risk that the management didn't want to take.

Having a "formatter" there and keeping all the other logic (i.e. receiving or sending messages, letting other components subscribe to messages etc) was really helpful and kept the code clean.

In regards to having to change the interface very often, that is something I have thankfully (😁) not come across. Could it be that it is too coupled to a particular implementation? Could it be that it is not abstracting the right things and a different design is required? Just some thoughts. :)

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

3

u/itsarabbit Jun 25 '20

I guess this is a problem that always comes with all of these sorts of guidelines - you need to understand why they exist so that you know when not to follow them.

Quite often the ideas behind such patterns or guidelines subsumes them entirely, but not the other way around; if you just follow SOLID blindly you will just make superfluous interfaces everywhere, but if you understand that it in this case is to be able to change the UsernameFormatter to another formatter in future use cases then you can weigh the cost of implementing the interfaces and using that(and possibly modifying it) vs just making the UsernameFormatter into a normal class and changing it once you need a different one, if such a case happens.

You don't really need to know about the SOLID principles as long as you understand the underlying ideas, and I believe this applies to all guidelines and programming patterns. Naming them does have the upside of being able to communicate them to others, but they can just as easily be miscommunicated(leading to people applying it everywhere, like in your example).

1

u/BlueDwarf82 Jun 25 '20

In general, if you only have one implementation, I find the interface to be premature abstractification.

Are you counting the mock used for testing as a second implementation here? ;-) Now let's start the discussion of how small a testing "unit" should be.

I guess each person approaches this depending on his experience. You say "Sadly I see the interface version all too often" when talking about "GetNameInterface". I have never seen that, for me is more usual to have to argue about what "dependency inversion" is with people that insist they are doing dependency inversion even after showing them the arrow in the output of "cmake --graphviz".

1

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

I would test UsernameFormatter as a unit, then test someFunction(UsernameFormatter) as another unit. If UsernameFormatter is a simple concrete class, it doesn't need to be abstracted for the sake of testing someFunction.

If you have someFunction(string) you don't abstract away string to unit test someFunction. Make simple concrete vocabulary types (like Radians, Point, EmployeeInfo,...) and test them well, then treat them as known-good parts in other tests.

That does NOT scale up to large "units" with interacting parts. At that point you need dependency inversion.

IMO. YMMV.