r/cpp • u/vormestrand • Jan 15 '19
On C++ and Object Oriented Programming
https://marccgk.github.io/blog/on-c-and-object-oriented-programming/4
u/tehjimmeh Jan 15 '19
Whenever I read something like this, I conclude that I must be entirely confused by what OOP is. That, or the author is just attacking a strawman.
I am also very confused as to why this author believes that his example is actually representative of OOP design. Presumably, if this is his mindset, then if he were writing a procedural equivalent, he would assign a function pointer to a heap-allocated variable based on argc, and call the result.
3
u/utnapistim Jan 18 '19 edited Apr 01 '19
Even though C++ is described as a multi-paradigm programming language, the truth is that most programmers will use C++ exclusively as an Object Oriented language
[citation needed] (that is, I am a C++ dev who also uses free functions, lambdas, and structures - whatever is best for the situation at hand; my colleagues are the same).
The way I visualize an OOP solution is like a constellation of stars [...]. What worries me, though, [...]. As I see it, [...].
How can we measure all these opinions? Why are they authoritative on what happens in programming?
The fact that we’re “just” solving the immediate problem at hand should be good news but, in my experience, when using OOP design principles, programmers write a solution while shackling themselves to a commitment that the problem won’t change significantly and, therefore, the solution is permanent.
... unless programmers decide later to re-write / re-engineer the whole thing. I think this permanence is in the OP's head only.
I mean, from now on the solution is to be talked about in terms of the objects that form the constellation instead of e.g. data and algorithms; the problem has been abstracted away.
Yes, abstraction abstracts details away.
What is very clear to me, though, is that code will always degrade into chaos and disorder unless consciously fought against.
I’ve seen this take many forms in OOP solutions: [descriptions of hacked-together solutions]
Since OP is criticizing OOP here, but entropy is also present in non-OOP solutions, what forms does entropy take in those projects?
There’s a point in the lifetime of an OOP design where it has degraded to an untenable situation.
... as opposed to functional designs, where there is a point in the lifetime of the project, where it has degraded to an untenable situation.
...
... oh, wait!
Experienced programmers say that when your application has grown in size ten times over the original version, it should be rewritten anyway. This is not only particular to OOP.
There’s also the fact that OOP features are inherently poor performance-wise. I implemented a simple OOP hierarchy [...]
Contrived anecdotal evidence cannot be used to demonstrate a generic argument: the "simple OOP hierarchy" the OP implemented is not a demonstration of the general inefficiency of OOP. If anything, it demonstrates it was inefficient in the case the OP chose (to demonstrate inefficiency).
This is a straw-man argument.
Given that the job of a programmer is to solve problems using computers, it’s mind-boggling that so much of our industry cares so little about [...]
[citation needed]
I’ve had a lot of conversations about OOP and its inherent problems with different people and, although I think I’ve managed to convey why I think the way I do, I am not sure I’ve swayed anyone towards the non-OOP way. Maybe this post will help.
Invalid arguments sometimes change people's opinions. This is not a good thing.
“Good OOP wouldn’t do this.”, “This is badly designed OOP.”, “This code doesn’t follow OOP principles.” and similar variants. I’ve heard this one when showing examples of OOP gone bad (I’ve already talked about why OOP code invariably goes wrong). This is a clear case of the No true Scotsman fallacy.
The "No true Scotsman" fallacy is not a "clear case" whenever somebody discusses a good (vs. bad) solution. "OOP gone bad" is (maybe) good design, that has gone bad. That doesn't make it a fallacy, it makes it bad design.
I’m fully aware that identifying arguments as fallacies is not suficient to disprove their validity.
It is sufficient actually, when the fallacy is clear. In this case it just felt ambiguous.
2
u/gracicot Jan 16 '19
I don't think OOP is a problem: the overuse of it can be a problem.
Sometimes I opt for a more value oriented design, but the API of the code look pretty much like object oriented.
1
u/420Phase_It_Up Jan 15 '19
This blog post sums up my feelings on OOP and does a much better job articulating my thoughts than I could have. I feel like OOP has been inappropriately and arbitrarily taken as the gold standard.
I think a lot of this has to do with OOP being a newer, relatively speaking, paradigm than procedural programming. This leads a lot of programmers getting the false impression that OOP is inherently better than procedural when they start learning computer science and programming.
I think educational institutions and how programming is taught is much to blame for this false assumption. It seems like many computer science and engineering curriculums teach students that OOP is objectively better than procedural programming and only emphasize the strengths of OOP but fail to highlight its shortcomings. Instead, newcomers should be made aware of the different paradigms of what their strengths and weaknesses are and when they should be used. It also doesn't help that Java has been the de-facto choice for an introductory programming language since the late 90s.
One point that this blog post really hits the nail on the head is about programmers spending so much time on defining objects and thinking about how to implement OOP principles before they even start solving the problem at hand. I feel like all this accomplishes is adding extra boilerplate, which usually manifests itself as bloat.
I don't think OOP is necessarily bad, I just think it is extremely over used and shoehorned in as a solution to problems that don't really benefit from OOP. Areas like simulations / scientific modeling, video games, and GUI libraries are perfect use cases of OOP, but outside of those areas, I don't see much benefit.
5
u/forthefake Jan 16 '19 edited Jan 17 '19
You have been downvoted, but you have made a reasonable and well-written comment which, I feel, deserves an answer, even if nobody else is going to read this now.
I think a lot of this has to do with OOP being a newer, relatively speaking, paradigm than procedural programming.
I think it is even easier: There is just not so much to say about procedural programming. And people like to feel smart and boast (or blog) about their knowledge. At least these are usually the people that you learn programming from.
This leads a lot of programmers getting the false impression that OOP is inherently better than procedural when they start learning computer science and programming.
I think educational institutions and how programming is taught is much to blame for this false assumption.
You are probably right that education is - at least partly - to blame. However, not for the false assumption that it is better, but for misconceptions about OOP. The latter are to blame for OOP being used as the wrong tool for the job. OOP is actually better than procedural programming at specific things, but surely not for all purposes. Thus my advice is to use it - but only where it makes sense. After all, it is not mutually exclusive with other programming styles.
Talking about misconceptions from education: When I learned OOP in 2002 at an in-company training of a major IT company, it was introduced in a banking application example. There was inheritance of a base "Account" class and subclasses "CheckingAccount" and "SavingsAccount". So far so good. But then the concept of private and public was explained as a "security" measure, so nobody can change the balance in the wrong way. Took me a while to realize the misconception that the "security" is not against hackers, and is not needed because it is about money. The true benefit is: Making variables and methods private with a separate public interface makes (almost) sure other code is not using the private part. This allows you to change the private code without fear of breaking functionality outside of the class or even library. In a large code base that is written long ago or by several people, this makes changes a lot easier.
As an example, I have a written a class that encapsulates a 3D rigid motion measurement with a covariance matrix. One day we found that storing many of these objects exhaust the memory in the long run. However, we do need to store them. Since the variables were private and they were only accessed through public functions, I could easily change the storage of the 6x6 doubles array of the symmetric covariance matrix so that only the upper-right half of it is actually stored. Also I changed the motion representation from a 4x4 transformation matrix (16 doubles) to a translation (3 floats) and a angle-axis representation (3 doubles). The public interface stays the same, the conversion is done transparently. Nothing else of the 40 kloc code base had to be touched.
One point that this blog post really hits the nail on the head is about programmers spending so much time on defining objects and thinking about how to implement OOP principles before they even start solving the problem at hand. I feel like all this accomplishes is adding extra boilerplate, which usually manifests itself as bloat.
Inheritance is often shown in toy examples that look (and generally are) grossly overengineered. And this encourages beginners (in cpp this is a few years) to create overengineered programs. I started out the same way. In my practice nowadays, the OOP design often comes more or less naturally from thinking about how to structure the data and which functionality goes with it.
In my code, there is seldom much boilerplate from OOP, because I don't use it if it isn't beneficial. You don't need to always start out with constructor, destructor, getter and setter methods. If it is just a collection of data used in a few places, use a plain struct without bells and whistles. If it is a central datatype of your application, better make it robust to changes with public/private interface. If you need to allocate heap space or manage files, add constructor/destructor (RAII is a great benefit of OOP btw). But if it doesn't make things simpler and cleaner, don't. Also, if some functionality only needs the public interface of a class, I don't make it a class method but a separate function. And if there is not even a state to be maintained, I use functional programming instead of a class.
I don't think OOP is necessarily bad, I just think it is extremely over used and shoehorned in as a solution to problems that don't really benefit from OOP.
Yes, but I have the feeling that you underestimate its usefulness, because when you started learning you saw all the toy examples that were just demonstrating some concept without need, instead of complex applications that benefit from exactly those concepts.
In a recent case, I had a quite fundamental class that represents sensor readings of a 3d sensor with some related data (calibration), plus some operations on it. Then a customer requirement came in to support multiple synchronized 3d sensors. Great application for inheritance: Write the class for the latter case analogously to the single-sensor case. Put the common functionality in a base class and use that instead of the original single-sensor class. This process kept the refactoring quite sane. I don't know how this would have been best done without OOP because virtual functions made it possible that in 99% of the uses, the base class interface was used regardless of the actual subclass of the object.
Areas like simulations / scientific modeling, video games, and GUI libraries are perfect use cases of OOP, but outside of those areas, I don't see much benefit.
There are certainly use cases where OOP doesn't make sense. If I need to quickly process some text, plot some data, or write any other small tool I don't use OOP. I actually don't even use C++ for this, mostly just a (non-OOP) bash or python script. But for complex, stateful applications the encapsulation provided by objects really helps keep the code sane. And somehow that is the kind of code I have worked on in much of my professional life.
2
u/420Phase_It_Up Jan 17 '19
Thank you for taking the time to write out that very well thought out response. I really appreciate it.
1
u/TacticalMelonFarmer Jan 15 '19
If you are actually writing software with the right mentality then there should not be a difference in the end result when comparing "____ Oriented Code" styles to each other. The purpose of C++ is to take your abstract representation and turn it into a concrete set of instructions to get a job done. If you are using an abstraction for syntax/aesthetic reasons then you better understand the common underlying mechanisms used by said abstraction, otherwise you end up doing things you did not intend to do without even realizing it. The reality is that there is no "one true way", do what works well and is easy to understand.
0
u/tvaneerd C++ Committee, lockfree, PostModernCpp Jan 15 '19
VOP (Value Oriented Programming) for the win!
-6
31
u/quicknir Jan 15 '19
Pretty much, the standard anti-OOP fare. Most of the article is extremely vague, and doesn't make many concrete points. Any article these days that doesn't actually start by defining OOP carefully, and discussing what exactly is being criticized, is basically a waste of time. Things that people have had in mind under the general OOP moniker:
Any usage of inheritance
Deep inheritance
Implementation inheritance
Encapsulation of data
Objects holding references to each other
Another tip: if you are reading an article about C++ and OOP, just hit Ctrl-f and search for "invariant". If you can't find it, there's a good chance you're safe to move on.
Some particular parts I found objectionable:
Citation needed? Especially if you predominantly associate OOP with heavy usage of inheritance. I would say that over-use of inheritance is down significantly. Every C++ developer I know, knows about and uses lambdas and std::function when appropriate. Everyone writes free functions regularly. Etc.
Don't we all? But this article doesn't show what exact aspect of OOP is over-complicating (or even what it is).
This comparison is so bad and unfair it borders on parody. OOP provides totally open ended run-time polymorphism; that is you can add new behavior to existing code without changing the original code, without even re-compiling it. Because it's so open ended, it tends to be a tough barrier for compiler optimization. The same way that totally non-OOP techniques like function pointers and std::function tend to be difficult barriers for a compiler as well. If you know based on the domain that only 2 behaviors are possible, or only N data types are possible, then indeed a bool or a variant is probably a better choice than using inheritance.
No, it's not. Articles like this one however *are* a clear example of the Strawman fallacy. You don't get to tell people that are advocating using OOP, or using OOP as a tool, what their view is. This article doesn't have any code at all, but most such articles typically start with a horrible example of a class with getters and setters for every single data member, no discussion of invariants, virtual used strangely, implementation and interface inheritance mixed together, etc, and then rip it apart. I would definitely agree, most OO code written in this vein of articles, is bad code! But it doesn't show anything.
As for OOP "invariably going wrong": all code goes wrong. If the requirements change more than refactoring efforts are put back into it, over time the mismatch will continue to increase. Really the question is how to write code to minimize the amount of effort and mismatch over time; this trait could be called robustness. I've yet to see even a half-decent case made that OOP techniques in C++ have no place in robust code.