143 points · by thunderbong · 2y ago · 288 comments
The simple truth however is that overly going into either functional or OOP camp will hurt because strict adherence becomes subscribing to a silver-bullet.
The middle road is simply a better engineering option, use a practical language that supports both paradigms.
Keep data transforms and algorithmic calculations in functional style because those tend to become hot messes if you rely overly on mutation (even if there is performance gains, correctness is far far easier to get right and write tests for with a functional approach), then there are other concerns where an OOP derived system with inheritance abstractions will make things easier.
Agreed - I would get more specific with this too. Which arrangement makes more sense:
1. A solution that has an OOP outer shell hosting an FP inner core
2. A solution that has an FP outer shell hosting an OOP inner core
I argue that 1 makes way more sense - I look at the OOP/procedural code as the foundation layer upon which the FP code can be executed. This firewalls the messy outside world from the pure maths. For me this would be entry points like BusinessLogic.ExecuteRules() after having externally prepared all of the data contexts for execution. The results of this are then processed again by the external OOP code for downstream handling (writing to database, responding to web client, etc).
The other way around feels nonsensical to me.
And yes, i'm an advocate for the mix and match approach.
Where are you from? This reminds me of a long-since-dead grammatical construction, the "passival", in which -ing participles were used passively - the example I read about was correspondence stating "our garden is putting in order" where the modern language would require "being put".
In my English, it's still possible to say "the app needs amending" [= "needs to be amended"], or "the app's functionality needs amending" [ditto], but definitely not "the app needs its functionality amending".
Without that you would need to refactor the functional part every time any OO node wants to access any new data.
Wonder if that's because you've learned the pattern - "functional core, imperative shell"? I feel it's not a coincidence you used the terms "shell" and "core" in your comment :).
Myself, I'm very much in favor on a theoretical basis. In practice, I've got bitten by this a couple times - keeping a purely functional core didn't play nice with the modularization and testing setup we had, using C++17 with CMake and GTest/GMock. I blame this on my inexperience, filing off sharp corners as I go along. I'd sure could use a detailed study of how to apply this pattern in modern C++, on an application scale, taking account the real tradeoffs - like how to "firewall" the core from outside mess, and allow tests to poke through that firewall, and not end up in weird linking hell, and not blow a single module into 10 tiny ones, and keep the whole thing debuggable in practice[0].
One thing I occasionally do even in the "FP inner core" is apply the idea I picked up from Clojure's "transient" data structures: there is no difference between purely-functional, immutable, referentially transparent code, and imperative code carrying mutable state, if no one on the outside can tell. Sometimes it's just easier to make a typical imperative procedural or OOP solution and isolate it in a functional interface.
--
[0] - I used to like point-free coding; especially with functional style, it makes for nice, readable, highly-expressive one-liners. But each time I had to debug such code, I ended up regretting it. Now I'm starting to favor more explicit steps with intermediary variables storing results, simply to have good targets for potential breakpoints/tracepoints, and because such code is more convenient to step through. You could say I'm only doing it because the tools I use are limited, but frankly, almost all of "readable code" principles and even the shape of modern languages are driven by limitations of the tools we use, so ¯\_(ツ)_/¯.
What annoys me greatly though is kids coding various 'fancy' functional paradigms for data transformation without realizing their performance implications, still thinking they've actually done the 'smarter' thing by transforming it multiple times and changing a simple loop to three or four loops. Example : Array.map.filter.map.reduce. Also when talked about it, they have learned to respond with another fancy term : "that would be premature optimization". :|
Of you work with transducers, the map filter map reduce is still just one single loop.
GHC does for example.
https://stackoverflow.com/questions/38905369/what-is-fusion-...
In other words, you need to know which things in your language are considered to be language/compiler/runtime primitives, and which are just regular code.
Even in C# it depends on the linq provider - if you are talking to a DB, your quers should be optimized. Linq to objects doesn't do that and repeated scanning can kill your performance. E.g. repeated filtering on large lists.
If compilers consistently did this, projects like ffmpeg wouldn’t need to sprinkle assembly into their code base. And yet.
That said, FP is a great default for most code, and I try not to write any new code in languages that don't support algebraic data types. You can express things much more precisely with them.
Languages that let you use both styles (Kotlin/Swift) are probably my favorite, despite using Haskell in production at work. Haskell punishes needing to use mutability too harshly IMO.
Kay has spoken positively, for instance, of Erlang, which has nothing like Smalltalk's OO model.
https://hackage.haskell.org/package/bluefin
1. a logger that logs to stdout
2. a logger that logs to a file
The file logger also brackets the opening of the file so that if abnormal termination is encountered then the file handle is guaranteed to be cleaned up. This is similar to RAII.
I really like this solution! It's just programming against an interface, and then instantiating the interface in different ways. I think an solution using inheritance would be worse, because it would use a special language concept (inheritance) rather than a standard one (function definition).
Perhaps this is "OOP" and not "FP"? That's fine by me! But in that case I conclude Haskell is an excellent OOP language. (I already conclude that it's an excellent imperative language.)
{-# LANGUAGE GHC2021 #-}
import Bluefin.Compound
import Bluefin.Eff
import Bluefin.IO
import System.IO
import Prelude hiding (log)
newtype Logger e =
-- Log a message with a severity
MkLogger {log :: String -> Int -> Eff e ()}
withStdoutLogger ::
(e1 :> es) =>
IOE e1 ->
(forall e. Logger e -> Eff (e :& es) r) ->
Eff es r
withStdoutLogger io k =
useImplIn
k
MkLogger
{ log =
\msg sev ->
effIO io (putStrLn (show sev ++ ": " ++ msg))
}
withFileLogger ::
(e1 :> es) =>
FilePath ->
IOE e1 ->
(forall e. Logger e -> Eff (e :& es) r) ->
Eff es r
withFileLogger fp io k =
bracket
(effIO io (openFile fp ReadMode))
(effIO io . hClose)
( \handle -> do
useImplIn
k
MkLogger
{ log =
\msg sev ->
effIO io (hPutStr handle (show sev ++ ": " ++ msg))
}
) `type Logger = (String, Severity) => IO ()`
`def empty: Logger = (_, _) => IO.unit`
`def aboveSeverity(l: Logger)(minsev: Severity): Logger = (s, sev) => if sev >= minsev l(s, sev) else IO.unit`
Or Curried if you like. In Scala, you might put these on a companion object so that you can give Logger.empty to your tests, etc. You don't need the type to remember which type of logger you had. The only thing you care about is that you can call it.Pure OOP aka Java has been a mistake, even though it's probably the most popular.
I mean, Java is hardly 'pure' OOP and these days contains a lot of functional type features.
I've come to the opinion that sticking to paradigms over practicality is often the problem, and a language that helps you get things done regardless is preferable
Rust actually is in the sweet spot between both worlds with the best from each side.
Also:
> Erlang itself is pure
Very not true. erlang is extremely impure fp and that's a big part of what makes it what it is.
I mean in terms of overall spec compliance and production use cases.
Im guessing larger adoption would still be low unless Rakudo can run CPAN modules as is.
The big effort going into v.6.e (ie the 5th major release of Perl6 == 6.e) is Raku AST which is now in PREVIEW and is a big boost for writing Slangs (Raku sub languages) since you can now use the built in Grammar parsing to generate AST code - and is the precursor to macros and improved JIT optimisation.
The Raku spec is actually the ROAST test suite https://github.com/Raku/roast and Raku has been compliant to this since 6.c which was the first production release.
Raku can run Perl5 CPAN modules (Inline::Perl5) and Python modules (Inline::Python) out of the box and it has deep FFI C NativeCall facilities. There are also a couple of Raku + Rust exemplars such as Dan::Polars (note: I am the author).
Raku also has some very nice modules - Red is an ORM that leverages traits to make OO/ORM seamless, Cro is a web server framework that uses concurrent features such as Supplies to enable pluggable middleware (think WebSockets).
As to larger adoption, I would say that this is still slow - there are some reputational concerns around the Perl to Raku transition and some points have been made about slow execution speed (although I would say that Raku is no slower than Python / Ruby were at this point in the development curve and of course there is no GIL limitation and many built in features for multi core such as hypers).
At the moment, I would say the "killer app" for Raku is the use of Grammars in conjunction with LLMs (language meets language) - take a look at the work of antononcube for some great use cases... https://raku.land/zef:antononcube/LLM::Functions
Programming styles are just that, style; Language =/= style.
The word "style" generally means a superficial characteristic of appearance, but "style" in a discussion of programming languages could mean the appearance of the language, the loop/state paradigm, or the design ethos of the language itself.
For example, the design ethos of Java is entirely bound to OOP. Python on the other hand has a celebrated syntactic style, an OOP foundation, and a flexible loop/state paradigm.
Python has flaws, of course. But its development community has paid attention to syntactic style and to the loop/state paradigm. Java became a successful corporate language; Python entered the corporation because it has become a popular language.
I recommend reading "The curse of the excluded middle" paper by Erik Meijer on why this approach does not work.
In the past decade, we've seen "the middle way" has won.
- Every mainstream OOP languages now support passing functions as parameters.
- Optional type annotation became mainstream, e.g. Typescript and modern Python.
It became mainstream indeed but, in my opinion, it's still a mess. Optional type annotations seem like the worst of every possible world to me, and it leads to unprincipled [1] developers to just not use them or use them so inconsistently it doesn't matter and we revert to "no type annotations at all".
Just my experience, of course.
----
[1] which, in the wild, is the most common type of developer. And really, features should help with the most common developer, not the most principled ones.
The middle-way languages adopted the penalties, but not the benefits. So the real winner was "lose-lose".
FP needs FP data structures. Without those, any somewhat complex program will quickly desolve into very non FP style.
We've made the middle road work. It is not the magical 10x speed upgrade that some managers hoped for if you just sprinkle some FP on top of the project like icing, but it works quite well in practice because you have the right tools for dealing with different kinds of subproblems.
Meijer's paper is what I would call "FP maximalist". (Or "Haskell maximalist", as even OcaML manages without hiding all IO away in monads.) It's a defensible opinion to have, but doesn't have anything to do with the work environments that I have experience with.
For me, OOP can be done right, but FP is intrinsically better for correctness (it incentivizes correctness)
It is mutability that is incompatible with FP, but mutability is a property of imperative programming, not of OOP.
It is even possible to have 100% purely functional Java, for example, if you just eschew mutability.
But... it's not? See `catchE` [0] from Control.Monad.Trans.Except:
catchE :: Monad m => ExceptT e m a -> (e -> ExceptT e' m a) -> ExceptT e' m a
... where the callsite-provided exception handler is the second parameter to the function, which can do basically anything (especially if the monad m is MonadIO). Hardly unergonomic or overcomplicated in my view, and no effects algebras or even type declarations in sight.There is already a canonical example and it is the "Expression Problem," [1], where in FP "you optimize for extensibility of the number of operations in your model, at the cost of reduced developer ergonomics when attempting to extend the number of types you can operate upon. In the latter, object-oriented approach, you have the inverse tradeoff." [2]
[0] https://hackage.haskell.org/package/transformers-0.6.1.2/doc...
Scala, Elixir and some lisps are languages that make this nice.
TypeScript has libraries like effect-ts where you can leverage OOP where it makes sense too.
Several patterns are trivial, others are very similar and are just a linked list of objects that are searched for performing some action.
The composition over inheritance meme in the book does not make things easier (there is no "composition" going on anyway, it is just delegation).
Objects themselves for resource cleanup like RAII are fine of course.
I feel very lucky (in many ways) that I started with VB5 and Turbo C/Pascal. Sure, you can do OOP in VB6 but the books I read did not touch this area.
Then I tried Java. I hated it! This would have been around 1998.
The Java books I was reading were huge and half of it was not entirely about Java the language.. but OOP concepts. Some of it was inheritence hell! I remember looking at code that was just a bloat.. when in C it could be a couple of structs and 10 functions.
Then "Design Patterns" was thrown around in Job adverts. I had to bite the bullet and learn it to get my foot in the door. I was 18 at the time.
Once I got my foot in the door and gained the experience needed to get good as a developer, you soon get a handle of what works and what doesn't. Am I suggesting OOP is bad? No.. it has its place. I found the GoF is not as serious as it is pushed.
It was not long before I went full circle, coding more away from typical OOP mindset. I felt like the odd one out when I tried to explain this to co-workers but once we reached 2010's with the coined "Data Oriented Design" I realised my mindset is shared by many.
Personally -- and.. yes.. this is controversial.. I think OOP set us back 10 years of programming progress. Not because of OOP itself, but how large companies jumped on the bandwagon and encouraged developers that "this is the right direection" so much effort was there, creating large.. bloated.. monolothic code.
I felt like Dlang was an interesting step forward but, sadly, it is a language that tries to be everything. Now with Rust, Zig and Odin, I do believe that OOP will slowly lose in popularity but it will be a very, very slow decline.
I’m sure lots of people got value from the book. I pity that they were in a situation where it was useful.
I will always remember the first pattern I learned -- the Decorator Pattern. From memory, the example used was making hot beverage.. adding milk, sugar, etc. I looked at the code and said "So its a Link List of items?"
I understand the book was covering things in a simple manner but even this looked like bloat, with things like Milk, Sugar, etc.. being its own class (inheriting the decorator) that, in the end, is simply a enum with a couple of structs if using a language like C.
I just felt it we are adding +30 lines of code for this SIMPLE example -- how much bloat would it be for real world solutions?
It's a much larger part of programing than most people give credit, but yeah, it's only a part.
Anyway, the GoF book is about getting good abstractions from the 90s limitations in OOP languages. Nobody should read them now, except for historical reference.
C++ was originally designed as Bjarne Stroustrup was in the process to create distributed applications in UNIX at Bell Labs, and after his downgrade experience from Simula to BCPL he wasn't touching raw C for such purpose, thus C with Classes was born.
There were zero GUIs in the early days of CFront.
GUI programming exploded together with OOP, and a lot of libraries/toolkits were made when using OOP was almost mandatory.
As much as frontend programming gets a lot of flack, functional reactive is a much better paradigm. One can however argue it's just lacking better implementations for non-web applications.
Nope.
One thing I like to do in C++ is, on an embedded system, wrap an object around a hardware resource. It means that no other code needs to know about the details of talking to that hardware. Also, if there are multithreading concerns, it leaves a very small set of places to worry about mutexes.
Yeah, plenty of people like that too. That doesn't make it an application for OOP. The fact that the 90s killed the modular languages is quite a bummer, as neither modern FP nor C++ style OOP have anything nearly as useful.
Logger l;
That’s a Logger, and it will not magically become a subclass.And changing this to go through pointers everywhere and to use virtual functions, in C++, is not very performant. A good JIT compiler may be able to effectively devirtualize it, but C++ compilers are unlikely to be able to do this effectively.
The "Server" class, or whatever instantiates the Logger, will have to change, but that might not be such a big deal.
So yes, the author was wrong about not having to modify any code, but likely you won't have to modify most code.
The problem domain is things like your physical model. Your 3d mesh. Financial transactions. All things that need to be represented in software.
The software domain is things like components and queries. Things you can build in-software to realize your problem domain on a computer.
Defining a component and the behaviors of a component has nothing at all to do with the problem domain; it's purely an artifact of software to make your system more extensible/reliable/faster/whatever. But this is the part that's OOP excels at because you get to write the rules of your component taxonomy in its entirety. You have a ThingDoer class that can accept any number of Components to give it the behaviors you need, and then you start writing out components to model your problem domain. The objects and their behaviors remain at the level of "how do I put these pieces together". OOP sucks for the problem domain, though, because you're always stuck trying to munge some limited inheritance tree (animal <- dog <- wolf) onto the Real World and it's always going to miss something. Far better to build atomic building blocks that are expressive enough to compose into whatever you need.
The OOP model fits nicely into most people’s heads because of the analogy to the real world and OOP implementations generally seem to give better signals when you are doing something wrong. Rather than functional implementations which mainly rely on human expert code reviewers and linters to give negative signals instead of say exception hierarchies.
A lot of the time you don’t realize your codebase is bad until “it’s just a button how hard can it be” somehow takes 3 months and 4 rollbacks.
At least this is what I have observed working on large codebases.
It also has been the default programing language paradigm for a while now, which I think explains why experienced programmers can cling to it despite its drawbacks. Try to teach object oriented programming to a beginner and it becomes clear that it isn't as natural as you are suggesting.
> generally seem to give better signals when you are doing something wrong.
Better than what? Functional programming is a far simpler abstraction: a function. Data in, data out. That's about as simple as it gets. Also, culturally, functional programmers generally understand the downside of distributed state, and actively try to minimize it. That's a good thing.
Bad code is bad code, but OOP gives you unique weapons to hurt yourself with. Inheritance allows one to change an unbounded number of objects without you even knowing. Modeling everything as a collection of objects with state tends to lead to programs that need to synchronize distributed state rather than a central state that is easier to keep consistent.
Js is still stateful everywhere, even where you don't want it to be
I’m not sure if you correctly understand what functional programming is.
Check out Grokking simplicity, great book.
Nothing in real world resembles OOP.
It's the same thing with languages, IMO. People try to shoehorn tasks into a language when it would be better off in another language.
What are its appropriate uses? The more I program the fewer I see.
Here's the first article in the series: https://ericlippert.com/2015/04/27/wizards-and-warriors-part...
It's especially odd to compare and contrast OOP style with Functional Programming paradigm because these things are orthogonal.
The following might sound ridiculous, but I swear I'm not making them up:
- In my highschool, students on their "Computer & Information 101" class were asked to answer what polymorphism is. Most of the said students had zero programming experienece at the time.
- In my sophomore year (CS major), students were asked to finish a mini game "with design patterns" and explain what design patterns they used. For most of the said students, that was the first time they wrote a program with more than 300 LoC. Before that, all the assignments they had seen are "leetcode-like", like implementing Sieve of Eratosthenes in C.
First, examples are often unpractical and divorced from reality. The canonical meme examples of “Dog and Cat inherit from Animal” or “Car inherits from Vehicle” are not really applicable to Veterinary Clinic Software or Self Driving Cars. People use those kinds of examples to say that OOP is good at modeling reality, but business software is 90% of the time better served by a different level of abstraction.
Second, a lot of descriptive information is passed as prescriptive. Patterns are a good example of how shoehorning concepts in a piece of software without having the knowledge to come up with it by yourself can make it worse, and yet teachers spend whole semesters dedicated to it.
Third, inheritance is still being taught as a fundamental part of OOP from the beginning in every curriculum I have seen, only to have pretty much everyone else saying “prefer composition” down the line, after the damage is already done.
Of all the topics that CS programs teach, it makes intuitive sense that the practical ones in software engineering are the ones most likely to be taught in a way which is irrelevant or backwards. Academia is good at academic things, but its members are typically there in part because they do not have a calling towards practice.
Perhaps the practical courses shouldn’t exist at all, but it’s tempting to marry the department with industry in some way. We don’t require philosophy majors to take courses in legal practice or whatever job they might take after graduation, because education is one thing and a career is another.
I had Pascal, Assembly and Haskell and it was quite practical and focused on universal concepts that apply to other paradigms and to software in general, it’s just OOP that has focus on concepts that are considered superfluous or damaging.
I personally blame fashion. Patterns and inheritance became fashionable and people just assumed they are as foundational as things like “variables” or “functions” or “ifs”.
The argument here is not so much that "implementation inheritance doesn't work at all" but rather that it is a limiting way of modeling that causes more problems than it solves, and teaching it is a problem in itself.
Implementation inheritance should be a footnote given with a warning, rather than a main technique.
Dependency injection is not OOP. When used in an OOP context, it just solves an issue created by OOP. In an OOP context you can't call code from another object unless you have a reference to it. So you either instantiate the object or use DI to supply an object reference so you can call a method.
In contrast to that, if you have functions as first class citizens or your code resides in a static class, you seldom need DI because you can call the function or method from wherever you need.
Plus teaching proper separation of concerns rather than the "one line per method" from Clean Code.
All this would lead to better software than the "Dog inherits from Cat" bs.
https://dev.epicgames.com/documentation/en-us/unreal-engine/...
The reason we don't tend to see such hierarchies used in clinic software is that RDBMS engines aren't OOP and don't model inheritance hierarchies well.
Self driving cars are big piles of C++ so probably have plenty of OOP, albeit given the ML bent probably more for dealing with UI and sensors than modelling the nearby landscape.
Inheritance is taught because most real OOP codebases use it extensively and it works OK. If you don't understand inheritance you can't understand the standard libraries of most OO languages, most UI toolkits etc.
The industry (and this includes Unreal, albeit slowly) has been moving to runtime composition for a reason: it is simpler and more flexible. And much better at modeling reality.
Your last paragraph pretty much sums it up: the main reason at this point for teaching implementation inheritance is because of legacy code bases. It can be a valid technique (I personally enjoy the Template Method Pattern, although it is today a maligned pattern) but it does causes more problems than it solves.
There's just one problem: code should not deal with a model of the world. It should deal with a model of the data.
A chair is a chair you'd say? Well it depends. Is it a background texture you'd never get close enough to notice it's flat? Is it a static mesh that never moves, and could be considered part of the ground itself? Is it something you can grab and displace? Can it be swung like club, or thrown like a rock, and do damage if it hit you or an NPC?
Depending on what you want to do with that chair, the data describing it will be very different. And if you have any performance constraint that data will likely be put in very different structures or systems, from landscapes to two-handed weapons. The very concept of "chair" at this point is mostly moot.
> Inheritance is taught because most real OOP codebases use it extensively and it works OK.
Avoiding inheritance would have worked better in most such codebases. I have seen things…
> If you don't understand inheritance you can't understand the standard libraries of most OO languages, most UI toolkits etc.
Any item behind "etc"? Because so far those two are the only example of inheritance being kind of mandatory. And I'm not even sure about standard libraries, the C++ STL is very light on inheritance, and I see very little of it in Python (at least as a user). I guess Java makes heavy use of it.
When I did my CS classes (at the beginning of the 'OOP will solve all the problems' era), we had excellent introductions to encapsulation and polymorphism and the rest with detailed examples in (early, cfront) C++ and Modula-2 & Ada. But then we had FP with SML & Hope and a couple of others that were poorly taught and most of us thought "this functional stuff is awful". YMMV.
Using classes as code containers doesn't make your code OOP. I use C# which demands most code being put inside classes, but my code isn't OOP because I seldom use inheritance, encapsulation or method overriding.
So, modules in functional languages?
> I think it would be beneficial for the functional programming community to stop dismissing OOP’s successes in the industry as an accident of history and try to understand what OOP does well.
But the author has spent enough time in the haskell ecosystem, and probably has some cause for this statement. I would personally have liked to hear more about that cause, and the perceived issues in the community, rather than code examples.
But in real life, when there is a team, you run into the fragile base class [1] constantly and changing that base class causes horrible issues across your code base.
I have found that OOP with inheritance is actually a form of tight coupling and that it is best to not use class hierarchies.
I agree with encapsulation and modularity and well defined interfaces (typed function signatures are amazing.) I just completely disagree with inheritance in all forms.
There are no benefits to it (besides feeling smart because you've made an elegant but ultimately brittle ontology of objects and methods), just a ton of downsides.
[1] https://en.wikipedia.org/wiki/Fragile_base_class#:~:text=The....
What I don't understand is why many programmers still use classes even when they plan on avoiding inheritance. I've seen this sort of thing on the past few major projects I've been involved with; initial creators heavily relied on inheritance, future developers realize that was a mistake, then said future developers continue using the class construct of whatever given language.
At that point, why not just use functions and regular objects? Without inheritance, classes tend to have these other rules and complications that don't seem to really add anything when there is no hierarchy.
Before OO, you had these data structures, and they got passed around between functions. Well-designed data structures were not just a random collection of items - they had a relationship between the elements. And you kept finding structures that were in an invalid state - the relationship among the elements had been broken. Well, who did that? You couldn't tell. It could have been any function anywhere in the code that took the structure.
With OO, you could have a very small set of functions that could change the structure. If the constraints got broken, you had a very small footprint to look at to see how it could have happened. That was the OO advantage.
And this advantage did not go away with multiple programmers. In fact, it increased. If you had a class that you "owned", some other new (or incompetent) programmer could not break your code without changing that class's code. You didn't have to rely on everyone else always doing the right thing with your structure.
Note that this advantage is orthogonal to inheritance vs. non-inheritance.
But there are many advantages to doing encapsulation through modules over classes, if nothing else being able to have the internal functions organized in different files, and having "internal"/"external" functions have the exact same syntax without needing hacks like extension methods.
Which is why functions should have typed arguments and results. :)
Likewise, null was created for a reason. Not a good reason.
I have done this myself. In TypeScript I would write a class that supports an interface. There is no hierarchy, but writing as a class gives it structure, a clear name, you know how to instantiate it, what it supports, private methods, private state, static functions, etc. So I find that classes still do great encapsulation for mutable objects.
Tight coupling is the basis of oop. A method is tied to an instance. Methods cannot be composed with other methods or functions without instantiating state. Methods cannot be moved into other scope.
The literal definition of an object is a tightly bound set of methods that cannot ever be used without instantiating state.
This is not what OOP people are talking about when they talk about tight or loose coupling though.
They are talking about the relationship between classes.
Functions can be moved to different scopes. Functions don’t rely on state to exist.
You can compose functions with other functions to build new functions.
And here’s the kicker. All of these functions did the same thing as the method.
Functions are more modular. A method, is a restricted function that is tightly bounded with state and all other sibling methods.
OOP can be used to design relatively uncoupled systems.
One of the lessons learned in all these decades is what the grandparent post alludes to, which is distilled into "prefer composition over inheritance". Implementation inheritance (as opposed to interface inheritance) indeed introduces coupling and is therefore discouraged in current advice.
Never go full-Object-oriented programming.
In this case I think it is valuable to make a distinction between OOP which is a style of programming, and object-oriented languages, which are just a language designed with that style in mind.
I have seen issues in codebases where developers have used OOP as style to aspire to, using it in an academic sense. They tend to try to use inheritance frequently, have deep inheritance trees, and suffer from hidden coupling through these.
On the other hand, those who use object oriented languages in a mostly functional style (side-effect free functions, effective immutability, and almost no use of inheritance) tend to be much healthier in the long term.
So it's fine to use OO languages, but never go full OO programming.
It’s better to have all your logic be loosely coupled down to the smallest primitive.
What’s the point of tying up groups of logic together and glue it up with state and say this is the fundamental unit of composition?
You see the problem? 2 years down the line you find out that a certain class has methods that are better reused in another context but it’s so tightly coupled that the refactoring is insanity.
Better to have had state decoupled from function and to have functions decoupled from each other and not tied together by common state. If you do this you get rid of all the fundamental technical debt that arises from oop. You guys don’t see it. Oop is a major cause of technical debt because of tight coupling.
We can’t predict the future. You can’t guess that a method that exists in class A will 2 years down the line be better fit in class B or as its own class. So because you can’t know the future isn’t it logically better to not couple all your logic together into these arbitrary bundles called classes?
Break your function down into more smaller modules of computation. The object class is too large.
But then you ask how do I create bigger abstractions? Just compose functions together to form bigger functions. For state Compose struct types together to form bigger structs. Using this method to build your abstractions allows you to break down your abstractions into smaller units whenever you want!
You can’t break down the class. The class is stuck. I can’t reuse a portion of state in another context and I can’t do the same thing with my methods. What’s the point of using classes to place arbitrary and pointless restrictions on modularity? None.
There's little practical reason to build a family tree of supertypes and subtypes outside of building GUIs, yet this is how class-based OOP is designed and taught.
Trait-based OOP gets this right. The hierarchy is completely flat. You simply implement the behaviors for the types you want and don't have to think about grandparent behavior and final interfaces.
The problem IMO arises when you mix both deep hierarchies and implementation inheritance.
I didn’t mention coupling behaviors to types. I said coupling behaviors to state is the problem. When I couple method a to state it’s a big problem. I want method banana but method banana lives in the jungle and has all the other methods related to jungle.
So all I wanted was a banana now I have a jungle. Why not think of the banana as modular from the jungle? Why even use oop?
I agree with you on the inheritance thing. Thats a different issue.
But then we invented inversion of control principle to remove that tight coupling. :)
If module A is defined in terms of B or B defined in terms of A then you have a coupling.
The inversion is orthogonal to the problem right? The inversion of A defined in terms of B is rewriting B to be defined in terms of A.
Better to have A and B not know about each other and be independent instead of dependent.
It's very easy to deliberately miss the point and complain about the "tight coupling" that, by design, prevents messages to be sent to/called upon invalid states, which functional programming also has, albeit with different a approach using static type inference & pattern matching.
If you use implementation inheritance, i.e. a base class with a tree inheritance of derived classes, there's coupling between the derived classes and the base class, because changes done carelessly in the base class (for example, to accommodate one additional child class) may impact the behavior of already existing derived classes. There are all sorts of principles to minimize this risk, but they are there precisely because it's such a big risk.
Therefore "inheritance as reuse" introduces dangerous coupling, but it's not a case of the "interface being coupled to the implementation of the object".
Right and I'm saying it's the tight coupling of Objects themselves that's the main problem.
>It's very easy to deliberately miss the point and complain about the "tight coupling" that, by design, prevents messages to be sent to/called upon invalid states,
More like you missed my point. You should avoid coupling logic and state as much as possible period. OOP encourages this. You have one state called A, and A has 20 methods attached to it. Boom now All methods and A are tightly coupled.
At most one should have only a simple setter and getter on A, and all the transformational logic be pure functions and decoupled from the changing of state.
Oh and you can use type checking to prevent logic to operate on invalid state.
You are not the only one. Prefer composition to inheritance is a saying for a reason. Inheritance is powerful and useful for small problems, but as you say it introduces tight coupling and so should only be used where that is intended. Tight coupling isn't always bad, but it is bad often enough to avoid it.
When all the states of the program and all the transitions between them fit into one programmer's head - every programming paradigm works well.
Instead of inheritance I much rather prefer the composition approach, not extending classes but defining interfaces for the API, using other classes in the composition of an object rather than relying on overrides/implementations from a base class. It's much clearer to reason about (no more 3-4 layers of indirection), easier to refactor as well.
Self contained encapsulated parts with an eventbus for entirely decoupled data propagation are much easier to manage and edit. Just duplicate a bit more than you think would be best to reuse, disk space is cheap and if you get that part wrong you're screwed and will need another rewrite.
And it's probably more performant too with newer hardware since you can usually just spin out any self contained part as its own thread if need be, often with almost zero changes.
And then you start writing unit tests for everything and wait 10 hours for building and deployment, which is a good thing because your employer will need more people to do the work. Or you can't fix a bug without creating other 10 new bugs, which is a good thing because your employer will need you to solve that 10 new bugs.
OOP keeps people employed. :)
This is pretty common advice (at least IME), usually distilled into the form "prefer composition to inheritance".
I think this is why in the current JavaScript era, it is rare to find a popular library that makes significant use of inheritance (as opposed to just supporting interfaces) even though it is supported in the language.
ThreeJS is one of those exceptions, but they are few and far between.
OOP certainly has good features (e.g. encapsulation of state), but I think it tends to shine best when programmers are really aware of the trade-offs. Most aren't. The same person that agrees that mixins are a bad idea in React, will then turn around and happily organize their logic as class-based views in Django.
And due to sunk cost, it's nearly impossible to convince someone who's invested time in this paradigm that the acrobatics are often probably unnecessary.
In my opinion, newer languages expose programmers to better mental models than "the class hierarchy" to solve code organizational problems. Work with Go or Elixir for a while and see your Java and Python improve.
> However, unlike our OOP example, existing code that uses the Logger type and log function cannot work with this new type. There needs to be some refactoring, and how the user code will need to be refactored depends on how we want to expose this new type to the users.
It is super simple to create a Logger from a FileLogger an pass that to old code. In OOP you also need to refactor code when you are changing base types, and you need to think about what to expose to client code.
To me option 1 is the correct simple approach, but the author dissmisses it for unclear reasons.
> pandas.read_csv(filepath_or_buffer, *, sep=<no_default>, delimiter=None, header='infer', names=<no_default>, index_col=None, usecols=None, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=<no_default>, skip_blank_lines=True, parse_dates=None, infer_datetime_format=<no_default>, keep_date_col=<no_default>, date_parser=<no_default>, date_format=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal='.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors='strict', dialect=None, on_bad_lines='error', delim_whitespace=<no_default>, low_memory=True, memory_map=False, float_precision=None, storage_options=None, dtype_backend=<no_default>)
An OOP approach would define a Reader object that has many methods supporting various configuration options (setSkipRows(..), setNaFilter(...), etc), perhaps using a fluent style. Finally you call a read() method that returns the DataFrame.
read_csv(options: Options)
All you've shown is that Options has a lot of configurability, but you'd have the same problem if you posted the whole class with all of its fluent API methods; it would be even more characters.Also, you can use built-in control flow logic to modify options before passing them into the function rather than depend on a developer to implement a fluent API for every class.
But this isn't an example of FP vs OOP. Just replace `read_csv(options)` with `constructor(options)`.
I don't understand what that would bring as opposed to the current situation you mention, where you just call read_csv and name each parameter you want with the value you want.
If anything, I'd say the builder pattern is a crutch for languages that don't have named parameters.
https://docs.spring.io/spring-framework/docs/current/javadoc...
This is odd to me. There are solutions to make data types extensible in haskell, but for example in purescript you'd just use a record. But more importantly, why would you want existing functions to use the new type? Why not just pass the _logger from FileLogger in? The existing functions can't use the _flush ability anyway (in both OOP and FP cases)
On r/haskell, user mutantmell gave a implementation of the code (assuming such a module system) closely following the Dart code given in the original post.
https://gist.github.com/mutantmell/c3e53c27b7645a9abad7ef132...
https://www.reddit.com/r/haskell/comments/1fzy3fa/oop_is_not...
https://www.reddit.com/r/haskell/comments/1fzy3fa/oop_is_not...
>(Java-style) OOP offers a solution for this: you can code against the abstract type for code that doesn't care about the particular instance, and you can use instance-specific methods for code that does. Importantly, you can mix and match this single instance of the datatype in both cases, which I believe to be a superior coding experience than having two separate datatypes used in separate parts of your code.
>"Proper" module systems (ocaml, backpack, etc) offer a better solution that either of these: when you write a module that depends on a signature, you can only use things provided by that signature. When you import that module (and therefore provide a concrete instance of the signature), the types become fully specified and you can freely mix (Logger -> Logger) and (SpecificLogger -> SpecificLogger) functions. This has the advantage of working very well with immutable, strongly-typed functional code, unlike the OOP solutions.
>This is in essence the same argument for row-polymorphism, just for modules rather than records. It can be better to code against abstract structure in part of your code, and a particular concrete instance that adheres to that structure in other parts.
I am confused by this statement or it is going against what I understand.
If you have created a Type B variable, and you also have a new interface called A, and B implements A, then why would Type B variable's values be passed to A's values. 'A' is only an interface.
"It is not difficult to keep a functional aspect in OO."
"It is not that difficult to do OO in Pascal or similar" (quote from Wirth)
Several functional programming languages includes an OO or OO like feature.
Nothing will fit every situation better than anything else.
OP's example is trivially solved by services in both, because both treat dependencies as first class constructs and types.
PS: I really hate python style paradigm & declarative programmings. Rust is top of my ignore list.
And I feel like code culture is one place in need of some checks, on it's checking. There's so many wide-ranging beers out there, prejudices. Some have fought those battles & have real experience, speak from the heart. But I feel like over time the tribalisms that form, of passed down old biases, are usually more successful & better magnets when they are anti- a thing than pro a thing.
JavaScript, PHP, Ruby, rust. Systemd, PipeWire, Wayland. Kubernetes. OOP, CORBA, SOAP. These are examples topics are all magnets for very strong disdain, that in various circles are accepted as bad.
It's usually pretty easy to identify the darksiders. Theres almost never any principle of charity; they rarely see in greys, rarely even substantiate or enumerate their complaints at all. I've been struggling to find words, good words, for the disdain which doesn't justify itself, which accepts it's own premise, but the callous disregard & trampling over a topic is something I would like very much to be a faux pas. Say what you mean, clearly, with arguments. Manage your emotional reactions. Don't try to stir up antagonism. If you can, cultivate within yourself a sense of possibility & appreciation, even if only for what might be. Principles of Charity. https://en.wikipedia.org/wiki/Principle_of_charity
I'm forgetting what else to link, but around the aughts this anti- anti-social behavior has a bit of a boom. Two examples, https://marco.org/2008/05/21/jeff-atwood-who-knows-nothing-a... https://steveklabnik.com/writing/matz-is-nice-so-we-are-nice...
(And those on the pro side need to also have charity too.)
The idea of the Speaker For The Dead, someone who tries to paint clearly both upsides and downsides of a thing, is one I respect a lot & want to see. A thing I wish we saw more of.
(I feel like I have a decent ability to see up and down sides to a lot of the techs I listed. One I'd like better illumination on, a speaker for the dead on: CORBA.)
You can know the good and the bad, specifically about something, and that's very useful, but even that list is always going to be incomplete and possibly cherry picked.
* The human brain is not capable of evaluating and re-evaluating every possible option amongst the plethora of technical choices developers are faced with. This forces us to develop certain coarse grained mental heuristics (prejudices and biases) to navigate technology, and even if these broad generalizations are roughly true initially, we tend not to re-evaluate them over time. This leads to stale biases (e.g. some library/language was missing an API 10 years ago, and someone formed an immutable opinion on it).
* These broad generalizations lack nuance. I watched a talk recently by Dan Abramov where he calls these heuristics (I'm paraphrasing) a form of information compression [1]. That compression is lossy — it doesn't preserve the original context in which the heuristic was formed.
* There's also some insecurity at play here too. Developers want to believe that they've chosen The One True Solution, and harshly invalidating the alternatives is one way to reenforce that fantasy.
* And of course, social media has exacerbated this problem by rewarding inflammatory hot takes. You won't get nearly as many views/upvotes/likes for a sober take that says "technology X is well suited for this narrow use case" as you will for a hot take that says "why technology X failed", or "why everyone hates technology X".
You might enjoy this link: https://blog.aurynn.com/2015/12/16-contempt-culture
A typical example are all those "We rewrote our service from X to Y and got huge benefits" articles.
- They are ignoring the fact that the new version has the benefit of years of experience with the actual problem domain and can be optimized
- They also tend to use a different stack such as a more specialized database, async processing using message queues etc. that provides huge benefits.
Someone will always cherry pick some aspect of that article (language or choice of database) as proof that their point of view is correct, while ignoring the fact that they are not comparing an apple with an apple.
To get a real comparison they should have written a third system using their new architecture and the old langauge, but that would of course be hard to justify outside of academic research. The developers probably wouldn't do it anyway, because if the old language proved just as effective it would be harder to justify why they chose a new language. Resumé Driven Development is unfortunately a real thing.
Good point. You need a control group to make sure you're measuring the thing you think you're measuring.
Inheritance's problem is not that it is "intrinsically" bad, but that it is too big. It is the primary tool for "code reuse" in an inheritance-based language, and it is also the primary tool for "enforcing interfaces" in an inheritance-based language.
However, these two things have no business being bound together like that. Not only do I quite often just want one but not the other, a criticism far more potent than the size of the text in this post making it indicates (this is a huge problem), the binding introduces its own brand new problem, the Liskov Substitution Principle, which in a nutshell is that any subclass must be able to be be fully substituted into any place where the superclass appears and not only "function correctly" but continue to maintain all properties of the superclass. This turns out to be vastly more limiting than most OO programmers realize, and they break it quite casually. And this is unfortunately one of those pernicious errors that doesn't immediately crash the program and blow up, but corrodes not only the code base, but the architecture as you scale up. The architecture tends to develop such that it creates situations where LSP violations are forced. A simple example would be that you need to provide some instance of a deeply-inherited class in order to do some operation, but you need that functionality in a context that can not provide all the promises necessary to have an LSP-compliant class. As a simple example of that, imagine the class requires having some logging functionality but you can't provide it for some reason, but you have to jam it in anyhow.
It is far better to uncouple these two things. Use interfaces/traits/whatever your language calls them that anything can conform to, and use functions for code reuse. Become comfortable with the idea that you may have to provide a "default method" implementation that other implementers may have to explicitly pick up once per data type rather than get "automatically" through a subclass inheritance. In my experience this turns out to happen a lot less than you'd think anyhow, but still, in general, I really suggest being comfortable with the idea that you can provide a lot of functionality through functions and composed objects and don't strain to save users of that code one line of invocation or whatever.
Plus, getting rid of inheritance gets rid of the LSP, which turns out to be a really good thing since almost nobody is thinking about it or honoring it anyhow. I don't mean that as a criticism against programmers, either; it's honestly a rather twitchy principle in real life and in my opinion ignoring it is generally the right answer anyhow, for most people most of the time. But that becomes problematic when you're working in a language that technically, secretly, without most people realizing it, actually requires it for scaling up.
No it doesn't. Interfaces need to follow substitutability rules too. Any type you substitute for another does, and that includes things like functions too.
You also can do things like take a subset of the interface and have things that implement just that. You can't do that to a class hierarchy; once a method is put in the hierarchy, it must be implemented by all children. (Note that if you're jumping up to say "But I can just implement an interface in Java or whatever if I want to do that", you're agreeing with me, not disagreeing. That's not a legal move in inheritance, though. Languages have been very, very slowly but very surely moving away from pure inheritance for a long time now.)
Having interfaces separated from reusability means you don't have to worry about all these things at once, just the interface.
So how could we compare OOP to FP in a way that evens out this difference? It depends on how you define FP.
You can (like this article seem to) restrict the definition of FP to only purely functional programming, in which a program cannot directly execute side effects, and must return a value representing the effects that the runtime system will then execute. Then an apples-to-apples comparison would compare the FP program with an OOP program that uses an effects system to manage its effects.
How do we do that? Well, if we define FP in a way that forces us to use effects, then the definition excludes a language like Scala, which is essentially a side-effecting OO imperative language that has features that enable FP-style programming. Scala isn't FP by the article's definition, because you can write impure code, but it does let you write programs that manage effects using an effects system. So you can do a reasonably fair comparison that way. I think you would discover that the pain of using effects is the same, if not greater, in an OO language where they have to be added as a framework.
Or you could define FP more broadly to include side-effecting languages like Clojure and F#, and you could compare a side-effecting OO program to a side-effecting FP program. This would be tricky because it would be very difficult to draw a style line between OOP and FP. Would you allow the FP program use OO constructs and the OO program to use FP constructs? If so, you might end up comparing two identical Scala programs. Would you ban the FP program from using OO constructs and ban the OO program from using FP constructs? In that case, you would get an OO program in the style of the 1990s or 2000s, which wouldn't be fair to modern OOP.
I don't think either choice really leads to a meaningful comparison between OOP and FP. I think comparisons have to be more specific to be meaningful, and they have to be in the context of a particular application, so you can fairly compare programs that use effects systems with ones that don't. You can compare Java with Haskell for a particular application. You can compare C# with F# for a particular application. You can compare Scala with an effects system like Cats Effect to Scala without an effects system, again for a particular application. These comparisons are more realistic because you can take into account the pros and cons of using an effects system versus not for the given application.