by whizzter · 2y ago · 0 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".
I'd say the thing you're commenting on is normal, if not altogether correct, in British English (Where are you from? I'm from the UK).
https://dictionary.cambridge.org/dictionary/english/need-hea...
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.
It's much better to just have a way of expressing efficient algorithms naturally, which is what transducers excel at.
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.
It's not the lower-order terms or constant factors we care about, but the relative rate of growth of space or time usage between algorithms of, for example, linear vs. logarithmic complexity, where the difference in the highest order dominates any other lower order terms or differences.
What annoys me greatly is people imprecisely using language, terminology, and/or other constructs with very clearly defined meanings without realizing the semantic implications of their sloppily arranged ideas, still thinking they've done the "smarter" thing by throwing out some big-O notation. Asymptotic analysis and big-O is about comparing relative rates of growth at the extremes. If you're talking about operations or CPU or wall clock time, use those measures instead; but in those cases you would actually need to take an empirical measurement of emitted instruction count or CPU usage to prove that there is indeed a threefold increase of something, since you can't easily reason about compiler output or process scheduling decisions & current CPU load a priori.
If compilers consistently did this, projects like ffmpeg wouldn’t need to sprinkle assembly into their code base. And yet.
No compiler is perfect, if you need the best performance you need to run a profiler and see where the real bottlenecks are. I'm not sure if ffmpeg really needs to do that, but I trust they ran a profiler and showed it was helpful (cynically: at least at that time with the compilers they had then, though I expect they do this often), and thus it wasn't premature optimization.
Regardless, compilers mostly get this right enough that few people bother with that type of optimization. Thus almost nobody even knows what premature optimization is and so think the wrong thing. Premature optimization is not an excuse to choose a O(n) algorithm when an O(1) exists or some such.
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.
My experience is with Common Lisp, which has a quite sophisticated object system (CLOS) with a metaobject protocol. Theoretically, pretty much everything there can be altered on the fly at runtime - classes and methods can be added, modified and deleted, inheritance hierarchy changed, method invocation rules arbitrarily altered, etc. In practice, efficient implementations like SBCL (which tries to eagerly compile everything down to machine code, including at runtime) tend to have a lot of logic for keeping track how how things currently are.
99.9% of the time, the current shape of the object model is fixed, so it's kept optimized in advance. For example, calling (my-method my-obj) can do anything, depending on what my-method, my-obj, (class-of my-obj), etc. are at the moment - however both you and the runtime know that, right now, my-method is only defined on class-foo, which uses standard object model rules, so the runtime ensures the call is just a fixed-address jump. Define my-method for another class, the runtime will make calls to my-method a simple lookup on a tag (or something equivalent). Mess with the method combination order, or class definitions, and the runtime will redo its own book-keeping and keep the calls as efficient as possible. So you still pay for the flexibility - but mostly just-in-time, in the 0.1% of the time you invalidate some optimization, forcing the runtime to re-optimize itself.
I don't have as much experience with Smalltalk, but I hear that the story there is similar - you usually have a fat runtime with gnarly, stateful internals that re-optimizes itself on the fly to keep the flexibility performant. It's a nice benefit of image-based languages, where the compiler is an integral part of the runtime.
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.
It’s still used in a lot of places and having these features available makes that a much nicer experience.
Whether I would choose it for a new project… maybe not. But we don’t always get that choice either.
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.