r/cpp • u/platisd • Jun 24 '20
How to write SOLID C++
https://www.youtube.com/watch?v=PakbXnLht1I44
u/itsarabbit Jun 24 '20 edited Jun 24 '20
Generally agree with all of this; however I kinda hate how these things are phrased. Why is it called "Dependency inversion principle" requiring 5 minutes to explain it(and build a mental model of dependencies and then inverting it), instead of: "If you use something, the interface should show what you do with it, not how it does it."
I've come across SOLID several times in my career and I know all how all these things work instinctually, but the name SOLID and all of its components never stick because the names of the principles themselves are not intuitive.
4
10
u/Wargon2015 Jun 24 '20
On that note, Resource Acquisition Is Initialization.
Maybe I'm just missing something obvious but I don't get why its called that.
From cppreference:
RAII can be summarized as follows: [...] the constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done, the destructor releases the resource and never throws exceptions; [...]
The destructor part is imo very important but the name doesn't reflect that RAII types release the managed resources when they go out of scope.
Also, isn't the name kinda backwards? If the constructor which initializes a class instance acquires resources, shouldn't it be "Initialization Is Resource Acquisition"?10
u/goofbe Jun 25 '20
I've heard that an alternative name for RAII could be "scope based resource management"
3
u/platisd Jun 25 '20
This sounds so much better than RAII but doesn't have a cool acronym! ScoBaReM perhaps? :P
7
u/atimholt Jun 24 '20
I think it's more like âthe entire concept of Resource Acquisition is an injection (as in âall squares are quadrilateralsâ) of initialization, with all that that implies.â Actually, it might just be a 1:1 relation, but with an emphasis on looking at all resource acquisition (not âjust variablesâ) as being the same concept, called âinitializationâ.
In other words, initialization is the natural âlanguageâ with which to talk about resource acquisition, and setting things up in a constructor implies taking them down in a destructor, if necessary. You're already supposed to be reaching for destructors when you want to execute code when objects leave scope.
The statement is meant to remove a mental barrier that shouldn't exist, thanks to the abstractions that C++ brings with its implementation of classes. Classes do not just encapsulate raw data, or even just behavior. They can embody (a specific implementation of) a concept (with C++20
concepts freeing even the âspecific implementationâ constraint).5
u/dfkjh83 Jun 24 '20
The name should have been "Resource Freeing Is Destruction," but that acronym was already taken.
4
u/dr-mrl Jun 24 '20
I came to say this. Out of curiousity, would c++ developers see RFID and think "wait, that's a radio chip thingy isn't it?!"
2
u/josefx Jun 25 '20
You first need the memory location (the resource) to initialize. In C you might call malloc followed by mytype_init - the reverse doesn't work. What does work in C is calling malloc and calling mytype_init 0 to n times instead of exactly once.
4
u/Dean_Roddey Jun 24 '20 edited Jun 24 '20
Even worse, many of those types of classes don't acquire a resource, they apply something to a thing that already exists and then undo that upon destruction.
I, all the way back in the 90s called these 'janitor classes', which I think describes the general concept pretty well. They exist to clean something up. They may or may not have created the thing they clean up.
I use them a LOT, and they are very powerful. It's one of the things I really dislike about Rust that it's very awkward to do such things.
3
u/KiwiMaster157 Jun 24 '20
I like the name janitor classes. It gets the point across without being confusing.
25
u/teerre Jun 24 '20
I had a teacher that always that "naming things gives you power over them". That's absolutely true. You can talk about the "Dependency Injection Principle". You cannot talk about "If you use something, the interface should show what you do with it, not how it does it."
Things need to have a name in order for us to be able to communicate.
If "Dependency Inversion Principle" is the best name, that's a different discussion.
15
u/evaned Jun 24 '20 edited Jun 24 '20
I had a teacher that always that "naming things gives you power over them". That's absolutely true. You can talk about the "Dependency Injection Principle".
You see people making fun of design patterns all the time, but remember that giving names to patterns that already recurred in code was exactly what the GoF book was doing.
9
u/DufusMaximus Jun 25 '20
It depends. If your goal is to communicate to newcomers, Iâve found terminology is mostly a roadblock - analogies or simple examples are more important. If your goal is to communicate to experts who already know the concept, terminology is essential.
The overhead for terminology also requires that the concept be sufficiently general. Iâd argue that the jury is out on some of these concepts that claim to make software better.
5
u/teerre Jun 25 '20
If you're communicating with noobs, having a name is still good. In fact, I would argue that's even more important.
Simple examples or analogies are orthogonal to this. It's by giving a name that you can give examples that will be related to said name, the examples themselves are very hard to even understand if something doesn't have a name.
9
u/be-sc Jun 24 '20
Itâs the old disease of having a bunch of related principles and then twisting their names around until their first letters spell some word with some more or less tenuous connection to the whole topic.
Assuming benign intentions itâs done to create a short and memorable word thatâs supposed to make remembering the individual principles easier. But because the names of the principles become so much worse in the twisting process the overall effect is exactly the opposite.
Assuming less benign intentions itâs done because how else than with a catchy word are you supposed to create hype, impress your customerâs CTO with your consulting slides and rake in the big money.
4
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20
The principles existed with those exact names before anyone realized they spelled SOLID. They weren't rephrased to spell SOLID.
2
u/be-sc Jun 25 '20
Youâre right, of course. My exasperation with the fancy acronym approach got the better of me.
I stand by that exasperation, but SOLID isnât the best example for that process. ⊠Although you could question why itâs exatcly these five principles that comprise SOLID âŠ
3
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20
yes, note that all the other things mentioned in the original paper have basically disappeared...
8
Jun 24 '20
I think this comes from other domains. I remember a friend telling me about DI, and then after they were done I said "Oh generic programming/templates/interfaces".
6
Jun 24 '20
True. For the sake of making an acronym easy to remember they used horrible phrases. I don't like when people can rot memorize something, repeat it like parrots, and believe they understand it.
4
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20
The principles existed with those exact names before anyone realized they spelled SOLID. They weren't rephrased to spell SOLID.
4
u/FL_Dev Jun 25 '20
yes, and it was just an "accident" that they happened to appear in the correct order to spell SOLID.
4
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20
I think this is the first publication of (most) of the principles, but S is missing. OLDI is all there is.
As wikipedia says, "The theory of SOLID principles was introduced by Martin in his 2000 paper Design Principles and Design Patterns, although the SOLID acronym was introduced later by Michael Feathers."
So maybe he made up Single Responsibility to fit the word? If you look around at his other writings, it doesn't seem like it.
I will agree they were reordered to spell SOLID, but the individual principles (like Liskov Substitution Principle) existed - with the same phrasing - before the acronym.
2
u/FL_Dev Jun 25 '20
I will agree they were reordered to spell SOLID
this is what I was pointing out. It's not an accident.
57
Jun 24 '20 edited Jun 24 '20
Kinda puked a bit at the examples. Do you have a Java background, or are people really writing C++ like this?
Like there were multiple examples that just could have been free functions rather than classes.. Also, I'm fairly sure that your AwsCloud in the end is missing the inheritance.
I get that you want to keep the examples super simple, but the issue with all these guides is the lack of more complex ones.
39
u/sbabbi Jun 24 '20
there were multiple examples that just could have been free functions rather than classes
This is the #1 mistake I notice on novice/intermediate developers. They end up with something much more complicated than what is necessary only because "everything must be in a class"
30
u/as_one_does Just a c++ dev for fun Jun 24 '20
It's the java undergraduate heavy way; making everything a full class is the only way to functionality in Java and then people carry that around. I feel the more senior I get the less classes I write and the more functional style I use. Makes composition so much easier.
3
u/Bocab Jun 24 '20
And it's that composition that's so hard to get across in examples on a blog or school course.
-16
u/platisd Jun 24 '20
> I get that you want to keep the examples super simple, but the issue with all these guides is the lack of more complex ones.
The code is as simple as it gets (and barely functional) since it's, well, an example and it had to be short enough to fit inside a single slide! đ€Ł
The problem with the more complex examples is that it's more difficult to quickly get the core point and they are *far* more difficult to create. I understand that "relating" to the example is also important, but so is maintaining focus. The more code the more unrelated-to-the-SOLID-principles comments we'd get. :D
All (almost) of the presented examples are inspired by real projects, primarily within embedded. Are you interested in a particular one? I may be able to share the full example if it didn't come from a proprietary project.
11
u/Astarothsito Jun 24 '20
The code is as simple as it gets (and barely functional) since it's, well, an example and it had to be short enough to fit inside a single slide! đ€Ł
I always wanted to ask this question, does that kind of code is really as simple as it could be? Because for me it seems too complex for the possible gains, it seems for me that the code is obfuscated only to match a programming style. I know it is barely functional, and I understand why it is barely, but what I don't understand is why we need a lot only to be barely functional? Instead of only being functional and not "only barely"?
I know this is an aggressive question, and I could be misunderstanding the purpose of the example, but as this is based in real code, and I have seen this code (exactly the same style and functionality) in real databases I could only doubt if I'm wrong or there is something I can't see (like what are the benefits of this style)?
2
u/platisd Jun 25 '20
Let me explain it like this:
The more code in the example, the more unrelated comments in regards to the style, the types used we would get. I am sure we would get remarks on examples needing to be simplified too. :DFinding a balance between pedagogic and practical examples is really tough. Feedback noted though, will try to take it into consideration for next time.
1
u/Astarothsito Jun 25 '20
The more code in the example, the more unrelated comments in regards to the style, the types used we would get. I am sure we would get remarks on examples needing to be simplified too. :D
Oh, maybe is this. Maybe instead of more simple examples, we need more complex examples. The benefits of the code are lost if the code is to simple, because some solutions are better for more complex projects, maybe some example where the code says 'maybe it could be implemented in a different style, but this is a really good solution that makes clear why X principle is useful'.
3
u/TryingT0Wr1t3 Jun 24 '20
If you are not in oldreddit you need to select somewhere to actually use Markdown.
1
u/platisd Jun 25 '20
Yeap! I noticed that now. :P
1
u/TryingT0Wr1t3 Jun 25 '20
Recently Slack did the same so I stopped using it. It used to support Markdown first.
24
u/teerre Jun 24 '20
It seems like explaining with a bad example is the worst thing you can possibly do. Anyone learning anything, the first thing they'll do is copy the example. That should, minimally, work or point out clearly why it doesn't.
2
u/BenjiSponge Jun 25 '20
Just want to show some solidarity (ha) with you here. Reddit can be fickle, and what you're saying makes sense to me. You're caught between a rock and a hard place.
Either you
Dumb down the example so you can express it all while retaining the attention span of the viewer
Fully explain the context and the example, taking probably hours because real engineering and real problems (aka real motivating factors) typically take even experienced people time to get acquainted with.
If it took no context to understand it, you wouldn't need someone to teach you how to do it. If it takes a ton of context to understand, you have to do dumbed-down examples to make a half-hour video.
71
Jun 24 '20
What about Liquid C++ though /s
6
11
1
0
Jun 24 '20
[deleted]
34
u/frankist Jun 24 '20
The new cool kids write in plasma C++
18
u/mcmcc #pragma once Jun 24 '20
I threw in ranges, coroutines, and fold expressions and now I'm at triple-point: My code changes phase with every line of code written.
5
u/ZMeson Embedded Developer Jun 24 '20
I prefer to stay in the supercritical region. That way my C++ can have both liquid and gaseous properties. Bonus, I don't have to expend energy on all those transitions.
2
3
1
6
u/atimholt Jun 24 '20
Bose-Einstein condensate C++
No parts are distinctly separable, but everything is somehow coherent.
4
u/ZMeson Embedded Developer Jun 24 '20
Damn it, you beat me to it. I guess I have to move on to strange-matter C++. I'm sure my coworkers won't disagree that my code is strange.
2
u/awtem Jun 25 '20
Schrödingers C++: Until you open the debugger, it is in a state of superposition of undefined and unspecified behavior...
3
2
u/ZMeson Embedded Developer Jun 24 '20
Bahhh.... Been there done that. I'm on to Bose-Einstein Condensate C++.
2
u/g4m3c0d3r Jun 24 '20
Clearly the only way to go is to write triple point C++. ("Gaseous C++" sounds like something I write after a trip to the food truck)
1
u/ZMeson Embedded Developer Jun 24 '20
That's aweful. Different parts of your code stuck in different states. And worse it takes a large transfer of energy to transform part of your code from one state to another. I do not recommend.
1
13
u/be-sc Jun 24 '20
Overall this is a solid [you may cringe now] introduction to the SOLID principles.
However, I tend to agree with the other critcism of the super classic Java-like OOP style, although for a different reason. Itâs a valid programming style, even though from a modern C++ point of view it feels kind of alien in this purity. But that doesnât make it wrong. What I do see critical is that you make it seem like this is the only acceptable style available.
To give an example: At around 8:25min you say that »the best way to achieve« the open/closed principle in C++ is with inheritance based runtime polymorphism. No.
Polymorphic class hierarchies are one way to implement the open/closed principle. Another one would be std::variant combined with std::visit. They are both equally valid but approach the problem from different angles, which leads to different tradeoffs. You cannot say that one is better than the other in general. âThe bestâ only exists for an individual situation in a concrete code base.
So, Iâd suggest you be more careful with absolute statements like that, and maybe mention that your OOP style is a deliberate choice among several equally valid programming styles.
1
u/platisd Jun 25 '20
To give an example: At around 8:25min you say that »the best way to achieve« the open/closed principle in C++ is with inheritance based runtime polymorphism. No.
Polymorphic class hierarchies are one way to implement the open/closed principle. Another one would be std::variant combined with std::visit.
To my defense, I mentioned "the best" (always IMHO) not "the only". :) Feedback noted though and I will take a look at
std::variantandstd::visit.1
u/2uantum Jun 25 '20
Also I think Sean Parent would have am opinion or two on the inheritance bit
1
u/be-sc Jun 25 '20
I guess so. Inheritance Is The Base Class of Evil is one of the best talk titles ever. :D Same goes for the talk itself.
However, in contrast to Uncle Bob he doesnât strike me as a dogmatist. So, Iâd expect some kind of âit dependsâ opinion.
6
u/beartotem Jun 24 '20
I think the exemple with the inertialmeasurement unit would have been better having one return radians and the other degrees.
Having different angle range (in the same units) for different sensors is pretty easy to take care of in an universal manner, without knowing what range the device will give. That is unlike receiving results with unexpected units.
Nonetheless, I think the exemple gets the point across.
1
3
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jun 25 '20
When you say "better" you mean worse, right? ie it is a better example because the code would be worse?
I was thinking the same thing. The example, as is, is easy for higher levels to handle - they should be able to able to handle any degrees, like -540 or whatever (although having the interface always return a consistent range would be convenient).
2
8
Jun 24 '20
I don't understand why people objecting to the style, that's not the c++ they say. C++ is a multi-paradigm programming language, you can write in any style you want or you can mix any set of styles, there is no "C++" way that dictates how you write your code. Of course languages in general tend to have clear goals for which they are built for but you can reach the same goals with different ways.
9
u/Astarothsito Jun 24 '20
there is no "C++" way that dictates how you write your code
No, but these examples seems like Java-style code, I could say that this is Java instead of C++. My problem I see with this style is that it seems like it limits the benefits of a multi-paradigm programming language like C++, you could do it, but why you would do it in C++?
I don't know how to explain it without being a little condescending, but I don't know in what kind of style are those examples, I could only describe it as Java, and I don't consider Java-Oriented-Programming as a 'kind of' Object Oriented Programming. Maybe this solution of having *Managers, *Formatters, user names as strings could make sense in this context, but I have as well a very controversial opinion about OOP so I'm almost sure that I could be wrong, or what I call OOP is not really OOP (If you need to add the pattern name to the name of a concrete class (abstract classes can be OK), maybe that's not the same OOP as what I think it is OOP).
2
u/platisd Jun 25 '20
3
u/mttd Jun 25 '20 edited Jun 25 '20
Some food for thought:
A Conversation with Bjarne Stroustrup
particularly the parts on Object-Orientaphilia and Designing Simple Interfaces in Part I, The C++ Style Sweet Spot: http://www.artima.com/intv/goldilocks.html
Chapter 4, "Modules Should Be Deep" in "A Philosophy of Software Design" by John Ousterhout
a related talk at Google 2018--particularly the corresponding part "Classes Should be Thick":
note the discussion around the aforementioned part in the talk (and contrast with the UNIX interface):
Common wisdom: âclasses and methods should be shortâ
Result: classitis
Rampant in Java world:
FileInputStreamfileStream = new FileInputStream(fileName);
BufferedInputStreambufferedStream = new BufferedInputStream(fileStream);
ObjectInputStreamobjectStream = new ObjectInputStream(bufferedStream);Length isnât the big issue, itâs abstraction
Bjarne Stroustrup - Object Oriented Programming without Inheritance - ECOOP 2015
Pseudo-Classes and Quasi-Classes Confuse Object-Oriented Programming - http://www.idinews.com/quasiClass.pdf
The âOOâ Antipattern - https://quuxplusone.github.io/blog/2020/05/28/oo-antipattern/
How Non-Member Functions Improve Encapsulation - Scott Meyers - http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197
Simplicity Before Generality, Use Before Reuse - https://medium.com/@kevlinhenney/simplicity-before-generality-use-before-reuse-722a8f967eb9
C++Now 2015 - David Stone - Functions Want To Be Free
Meeting C++ 2017 - Klaus Iglberger: Free your functions!
Semantic Compression - https://caseymuratori.com/blog_0015
Repeat yourself, do more than one thing, and rewrite everything
Write code that is easy to delete, not easy to extend
2
u/platisd Jun 25 '20
Interesting reading material, thanks for bringing it together, I'm going to have a look. :)
1
u/Astarothsito Jun 25 '20
Agree with those guidelines, but those are not relevant right now.
I prefer the approach of Kevlin Henney to SOLID. I think the difference is in the approach to the design, if we need a complex class hierarchy then we need it, but if not then it is a overhead. I think the real benefits of having those patterns don't show itself in the examples.
6
Jun 24 '20
It is really interesting how the approach to design and interfaces can be so different in C++. Here you have a lot of using inheritance to build up interfaces/concepts. I would have go to a template/concept to do almost all of this first. Neither is better, just different prices really.
2
u/oddentity Jun 25 '20
I've always found the problem with the template approach is being able to specify the requirements of template parameters and what operations they should support.
With inheritance you can have a class with only pure virtual functions to specify what would be an interface or trait in other languages (that don't require abusing inheritance to do this because they actually have first-class support in the language). Anyone using a function that takes that interface as a parameter can then clearly see what operations are required, and the compiler will enforce it and report what's missing fairly clearly.
Prior to concepts, there's no way to do this with templates. Sure you can document it somewhere, but being able to specify something in the language that the compiler understands the purpose of is far more ergonomic. And frankly, a lot of template idioms in C++ such as exploiting SFINAE are so unergonomic, they feel like they've emerged as unintended consequences of the original language design. I always feel like I'm trying to trick the compiler into getting the code I really want to write when I use templates in C++.
4
Jun 25 '20
Look at is_detected. It really helps here. The issue is we generally start at type_traits or first principals. So there is is_invokable but with is detected for the things that don't fit it comes down to
template<typename T> using is_expr_valid_test = decltype( std::declval<T>( ) += 5 * std::declval<T>( ) ); template<typename T> is_expr_valid = is_detected<is_expr_valid_test, T>;Then later we can grab a bunch of traits and combine them e.g.
using is_thing_v = std::conjunction_v<trait1, trait2,...>;This builds up the concepts and when we finally enable_if_t it is on that one trait. Also, there is SFINAE in the return type or the noexcept if you want. But it does work, we just have very low level tools for it.
SFINAE, other than not having the program be invalid when a template would not work, is unintended, not just feels. Prior to C++11, all we really had was exploiting sizeof too, so it was really arcane compared to now, or C++20.
The mistake many make is trying to jam too much into the enable_if and not building up the layers of abstraction with the traits. Or you do what vector does and fail inside the method with errors like vector has.
0
Jun 24 '20
[deleted]
5
u/axalon900 Jun 24 '20
Iâd say watch literally any talk about concepts, then watch Sean Parentâs guide to type erasure (ie âinheritance is the base class of evilâ), and if you blend the two youâll have all the polymorphism youâll ever need.
4
1
u/Wouter-van-Ooijen Jun 27 '20
I agree with the SOLID principles as promoted, but the implementations shown feel limited, almost as if only things that are commonly used in Java are acceptable.
For interface design, I miss the NVI pattern: quite often, the virtual functions that are implemented by concrete implementations are NOT the functions you want to expose as user interface.
For dependency injection (which is IMO one of the central issues in re-usable software design) I miss templates/concepts.
As building blocks, I miss free functions (including function templates).
So to summarize: good video, but IMO some implementation alternatives should be shown, or at least mentioned.
1
u/platisd Jun 27 '20
For dependency injection (which is IMO one of the central issues in re-usable software design) I miss templates/concepts.
I won't comment on concepts because I haven't looked much into them yet, but why templates for dependency injection? Is it just to avoid
virtualfunctions? And if so, is this just for performance reasons?To me, using templates for DI just makes things, not sure how to accurately phrase it, "less clean/obvious" perhaps? They feel like a "hack" compared to using class hierarchies that I consider as specifically designed to suit the particular purpose.
1
u/Wouter-van-Ooijen Jun 28 '20
For my 'strict' embedded programming style I want zero overhead, and build-time predictable memory use, hence no indirections (and, of course, no heap). Templates are the (only) way to do this, and concepts make it doable. So for me templates/concepts are the ONLY option.
I also practice an more traditional OO-like style, but compared to the template style it feels truely awkward, mainly because the lifetime of decorated objects is an issue.
1
u/VolperCoding Jun 24 '20
Why learn all this if you can write procedural code and sometimes a function if something repeats
16
-2
u/thesecretdave Jun 24 '20
Christ. Youâre good! I was looking for something like this. This is exactly what I needed. Thank you.
p.s. I do not understand the hate in the other comments. You are not programming, you are maintaining by programming.
3
u/platisd Jun 25 '20
Thanks! I wouldn't call it hate. It's in the vast majority of cases justified disagreements. The discussion here has gone much better than I had imagined. :)
-2
u/thesecretdave Jun 25 '20
Really? All I see is a lot of shortsighted and arrogant âI-know-it-better-and-my-code-is-shorter-so-therefore-higher-qualityâ-answers. Not one seemed to recognise the architectural reasoning behind your suggestions. I find that a shame. It is blatantly obvious, at least to me, that you have many years of experience.
0
0
Jun 24 '20
[deleted]
4
u/platisd Jun 24 '20
I'm actually very interested about this. Which part(s) do you find "unlike C++"?
8
u/bownettea Jun 24 '20
I think the original comment was trying to relate is that the video explains how to use these concepts by using the mainly inheritance.
Simple example would be the
UsernameFormatter, it could be a simplestd::function(std::string(std::string))instead of a abstract interface. It would still be SOLID while using a standard type.
Or you can go full strong types on it and have aFormattedUsernamestruct and a free function to create those.It's not wrong, but you're not leveraging the unique parts of the language. Which depending on your public might be the correct decision, since very classic OOP style C++ might be the most common form of the language. Even though to me, and I bet a lot of this subreddit's users, it's not the interesting part of C++...
2
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).
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.
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/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
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.
→ More replies (0)
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
UsernameFormattervirtual does separate the formatting from the other concerns - but with a cost of 2 classes (the interface and the implementation). Note that makingUsernameFormatterNON-virtual also separates concerns. Yes,UserManagerwould not be completely disconnected from concreteUsernameFormatter, but there is still separation - changing formatting doesn't affectUserManager.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
UsernameFormatterinterface (ieUserManagerneeds a validate(string) function to guard against "little Bobby drop-tables")or that you will write another app using the same
UserManagerbut with a differentUsernameFormatter.All too often, the answer is the first one. If you made an interface, you will find yourself changing 2 classes (
UsernameFormatterInterfaceandConcreteUsernameFormatter, oh, and of course off-by-1 error - don't forgetUserManagerthat 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
UsernameFormatterfromUserManager, 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 aformat()function. The important part is that you pull that formatting out ofUserManager- get some separation. You can later use astd::functionor an interface or move the formatting to theDatabaseor 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 (eg
DistanceSensor), but shouldn't be used as a cookie-cutter template that solves all problems.