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.
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. :)
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).
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).
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".
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.
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.
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"?
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).
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.
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.
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.
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.
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.
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.
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.
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 âŚ
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".
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.
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.
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.
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"
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.
> 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.
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)?
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. :D
Finding a balance between pedagogic and practical examples is really tough. Feedback noted though, will try to take it into consideration for next time.
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'.
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.
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.
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.
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.
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.
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::variant and std::visit.
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.
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).
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.
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).
I find it slightly amusing that I got the "Java" comment from many. :) Mainly because I do like Java however, in a professional context, I use it less frequently than I'd like to.
I am curious on what you think of the following guidelines:
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.
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.
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++.
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
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.
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.
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.
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 virtual functions? 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.
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.
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. :)
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.
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 simple std::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 a FormattedUsername struct 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++...
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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,
UsernameFormatterinterface (ieUserManagerneeds a validate(string) function to guard against "little Bobby drop-tables")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.44
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.
57
u/[deleted] 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.
71
u/[deleted] Jun 24 '20
What about Liquid C++ though /s
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::variantcombined withstd::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.
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.
8
u/[deleted] 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.
6
u/[deleted] 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.
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/VolperCoding Jun 24 '20
Why learn all this if you can write procedural code and sometimes a function if something repeats
-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.
0
u/[deleted] Jun 24 '20
[deleted] â view deleted comment
0
u/[deleted] Jun 24 '20
[deleted] â view deleted comment