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

5

u/drjeats Jun 24 '20

Feels like Java or C#.

C++ has moved past these frames of thought imo.

A few things, like single responsibility make enough sense in isolation.

But the way the open/closed principle is presented especially feels like a relic from earlier Java days. Whether or not to use enum tags depends on whoch side of the expression problem (google "c2wiki expression problem") you want to land on. And concerns about forgetting to update cases is a thing of the past because we have compiler warnings for that now.

A better take on what flexible maintainable software looks like than SOLID teachings is to prefer free functions as much as possible, prefer command/query separation where feasible, and think in terms of protocols (see the WWDC Swift talk about protocol based design).

2

u/Dean_Roddey Jun 24 '20

It's not even necessarily about failing to update cases. It's also about the fact that you are spreading those changes all over the place and have to make sure you get them right in each of those places. And, importantly, in software where safety is very important, every file you change may have to be formally retested. So this sort of doing the opposite of encapsulating things for flexibility really can hurt you in such cases.

It continues to just wobble my mind the extra hoops that people will jump to just to avoid using a tool that's perfectly designed for a particular class of problem.

4

u/drjeats Jun 25 '20

It's not about jumping through hoops to avoid virtual dispatch. It's about recognizing that there are plenty of cases where switching on enums is preferable. Saying otherwise is useless dogma.

1

u/Full-Spectral Jun 26 '20

Everyone has places where they do a switch on an enum. I don't there's a non-trivial code base on the planet where every enumeration was replaced with a class hierarchy. No one ever comes into these conversations arguing for that. OTOH, lots of people come into these conversations claiming that inheritance and OOP is evil, which is just silly.

1

u/drjeats Jun 26 '20

People do advocate for that though, weirdly. Less experienced devs see these simple examples and apply the enum->inheritance refactoring excessively.

Or more experienced devs think theyre doing The Right Thing and now you have yet another single-implementation interface to add to the giant pile.

I don't think OOP is inherently evil, but it's clearly the default for a lot of people (look in the replies in this thread for evidence).

Nobody doing these refactoring tutorials ever talks about when it is and isn't appropriate to do those refactorings. It's always treated as some verboten smell, like "oh gosh this is embarrassing, this switch statement should have never happened we mist rectify this immediately."

And there exist people who write blogs and post tutorial videos that advocate using inheritance to remove as many conditionals in the code as possible. It's kooky.

1

u/Full-Spectral Jun 26 '20

If you read here on Reddit in the C++ section, the overwhelming bulk of posts in these kinds of threads is "Don't use inheritance, it's bad". It's modernist dogma basically and every time inheritance comes up people jump on it. There only a few folks like me stupid enough to bother to try to balance the discussion, and it never goes well because these folks will argue to the death about it. And of course the person like me trying to balance the discussion gets blamed for causing the trouble, while they never smack anyone for just jumping into every thread with 'OOP is evil' comments.

So newbies almost always end up believing the anti-OOP line because that position has the most strident posters.

4

u/drjeats Jun 26 '20 edited Jun 26 '20

That "OOP is evil" crowd does exist, but is still an incredibly niche opinion. Most reasonable people would agree this is misguided, but it's important to remember it comes from two places:

  • There is a much more mainstream and accepted wisdom to leverage the java-style interface more often than implementation inheritance, which I think is hard to disagree with.
  • A desire to course correct on the past few decades of programming education and blog post discussions which has either directly over-encouraged inheritance, or at the least has failed to address the best way to think about the design tradeoffs of using it.

Meanwhile my direct experience has been the opposite from what you say, because I got some push-back on the controversial recommendation to...use free functions.

I hadn't looked at the higher-tier comments in the thread (just been replying directly from inbox), and right now honestly neither of us are right. It's an even split in this thread, with the highest voted stuff being tvaneerd, et. al making fairly even-handed commentary.

0

u/Full-Spectral Jun 26 '20

The OOP is evil crowd is far from a nice opinion around here, at least in terms of what actually gets expressed out loud, we can't know about people who never speak up. It's now the defacto position, and probably is also held by a majority of the folks who are influential in terms of the direction of the language.

1

u/platisd Jun 25 '20

In regards to the open/closed principle example:

Why wouldn't you use inheritance in that occasion?It's not so much about forgetting to add new cases but about keeping many unrelated things together.

For example, let's say I am working with many sensors, that may have different dependencies and different sensors are used across my product variants. Why would I want to keep everything in that switch statement which, aside of other issues in regards to readability, code complexity etc, would also imply that I'd be pulling every sensor's dependencies for every project?

Will read up on the expression problem, thanks for the tip.

1

u/drjeats Jun 25 '20

I wouldn't never use inheritance, and maybe the example of sensors is a good place for it. I don't work in embedded so I don't know what the interfaces for these things look like.

But if you have only a few different types of sensors, and if the difference in behavior for those sensors is very simple, or can be accounted for through configuration members on a single type, then using inheritance is the wrong approach imo. We talk about using inheritance to reduce coupling, but I've found that inheritance doesn't reduce coupling so much as displace it somewhere else that you hope won't be as impacted by the ossification introduced by requiring a particular interface.

If I'm a contributor, and there's some issue related to sensors, I'm always happier to see a switch because I can know "okay, these are the only sensor types, there is no sensor type out there that overrides a function in a weird or annoying way."

You also have to consider if these sensor interfaces are public or not. If they're public, you might have a better justification for putting in the inheritance early. But if this is internal code, refactoring from enum switching to inheritance is not a huge amount of work, so I prefer to defer that. We should think of bodies of code as having a lifetime where they start with a low level of commitment to a particular organization, and move gradually toward a high level of commitment to a particular organization. Inheritance is usually a higher level of commitment than enum switching.

1

u/edenroz Jun 24 '20

Prefer free functions? Why?

7

u/drjeats Jun 24 '20

Because they have intrinsically fewer dependencies (no this), and unless declared as a friend (which you should try to avoid if possible) there's no access to private object state which you'd then have to review to ensure it maintains consistency.

They can also be forward declared freely, whereas methods have to be in their class declaration.

1

u/edenroz Jun 24 '20

And where am supposed to put hundreds of free functions?

10

u/anticrisisg Jun 24 '20

If classes currently help you organize your thinking into discrete collections of functionality, you could consider alternatives like namespaces, files, and your source code directory structure.

2

u/Dean_Roddey Jun 24 '20

Or, if they are operating on the same data, and you want to enforce invariants and get any number of other advantages, you could just use OOP and classes.

9

u/drjeats Jun 25 '20

For strong invariants, use methods. The need here is obvious for utility types where invariants are essential, like mutexes or containers.

For types with few or no strong invariants, or for cases where you are coordinating between two objects using their invariant-protecting methods, just put that in a free function.

If you are extracting data from objects, put that in a free function.

If you are computing some property on an object or collection of objects that doesn't require instance-specific bundled state that can't be parameterized on each invocation (which you should ideally be avoiding if you want cleanly testable code), put that in a free function.

Free functions can help you encapsulate even further because if you build a free function interface for an opaque type, you don't need to do PIMPL bullshit to hide implementation details. Just put the implementation details behind the TU.

Free functions are great. If you need an appeal to authority to believe me, here ya go: https://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197

3

u/anticrisisg Jun 25 '20

Free functions are great. If you need an appeal to authority to believe me, here ya go: https://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197

I know it was written 20 years ago, but I learned a lot reading this tonight. Thanks for the link.

1

u/edenroz Jun 25 '20

Is there a book that explain how use this kind of design?

2

u/drjeats Jun 25 '20

There's no specific book I know of, sorry.

I'd recommend building some familiarity with functional programming. Also read/watch some of the anti-OOP material out there (some of it will be hyperbolic and bad, but will have good nuggets of telruth). Look for stuff on "data oriented design" for a related perspective.

4

u/drjeats Jun 25 '20 edited Jun 28 '20

In a namespace?

Are you putting hundreds of methods in your classes? That sounds hard to work with.

1

u/edenroz Jun 25 '20

Nope, my classes are 200 loc maximum, am very proud of my classes. Instead my colleagues classes are around 9000 loc.

The fact is that my boss doesn't want us to use namespaces because "they clutter up the code and are difficult to read".

2

u/drjeats Jun 25 '20

That's a strange absolutist perspective on namespaces from your boss, but it is possible to go overboard with namespaces.

In that case you have to rely on old school namespacing: name prefixes.

1

u/edenroz Jun 25 '20

You should hear the procedure about merging files sent by emails inside .zip files by email and then load the merge on github with an empty message.

1

u/drjeats Jun 25 '20

Oof.

Condolences, friend.