Functional Programming IS NO BETTER than Object Oriented Programming

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
one of my most successful videos on this channel so far Compares functional and object-oriented programming this is an interesting topic and clearly not just to me but there's more to this debate than we discussed in that episode this is one of those debates that to be honest seems a little weird to me my stance is not that I hate functional programming in love oo or vice versa but rather that I think of each of these approaches as tools rather than things to go to war about so what are the arguments for and against oonfp oh [Music] hi I'm Dave Farley of continuous delivery welcome to my channel and if you haven't been here before please do hit subscribe and if you enjoy the content today hit like as well there is no always best or FPS best for me there are times when functional programming is the best choice for some things and times when object orientation is best for others most of the systems that I can remember building had some aspects of both approaches despite the fact that I'm mostly still think of myself as primarily in our programmer this is not because of language support but because oo ideas or functional ideas made most sense in the context of the code that we were writing at that time I was an AR programmer in C for a long time and some of my C code was passing around pointers to functions that I could call polymorphically and using immutable data structures so my C code was both oo and functional before I get much further in this let me just thank our sponsors we're extremely fortunate to be sponsored by equal experts trisentis transfig and Roost all of these companies offer products and services that are well aligned with the topics that we discuss on this channel every week so if you're looking for excellence in continuous delivery and software engineering then click on the links in the description below to check them out the difference between oonfp is one of those debates though that seems to polarize people we can end up trying to score points in an argument rather than just shedding much light if we're not careful the first thing to say may be obvious but general purpose programming languages are general purpose in that you can write any system in any language there is nothing that you can do in an oo language that you can't do in a functional language and vice versa that's really what general and in general purpose means there's a difference between a general purpose language and a domain-specific language domain-specific languages have by design a narrower focus on whatever it is that their domain is for example SQL is a good example of a DSL and it's great at finding a collection of Records in a set but it would be a rather poor choice for writing Space Invaders this doesn't mean that every general purpose language is always an equally good choice for any problem but it does mean that any general purpose language could be used to solve any problem in computer science this is the idea of Turing completeness which describes the universality of computation it may be a bad idea to write an operating system in Python but we could so while it may be easier to write immutable code and pass functions as arguments in Haskell we can write code that has the same effect in C Java or any other general purpose language too well it may be more difficult to write code with side effects in closure or half score we can still do that if we try hard enough so the real difference between these different paradigms is not that they what they allow us to do but how easy they make it to do the things that we want to do this is about syntax more than capability but syntax matters it can change how we think about the problem that we're trying to solve different languages in and different paradigms make some ideas easier to express that's it really let's look at a really simple example a popular idea from functional programming is the idea of mapping as in map and reduce in this context the map is a higher order function that means apply some function to each element in a collection this is often seen as one of the preferred ways to process lists one way in which map is deemed to be better is in terms of performance now the real answer to whether Maps process lists faster than Loops is it depends and it depends on a lot of things one of the common advantages cited for functional programming is that it makes concurrency easier this is true writing immutable pure functions means that we can automatically parallelize them but why is that a good idea the naive assumption is that parallelizing like this means that we'll get the results faster but this is almost never the case if you measure it the problem here is that concurrency is fine but it only improves performance when we don't need to join the results back together again as soon as we need to rejoin the results the costs of locks semaphores cache misses and even the most efficient mechanism of all to manage that kind of concurrent join compare and swap operations dominates performance comparing swap is often hundreds of times slower than a single thread for example so you need a hundred threads to get the same performance as what a single thread and then your concurrency problems would be worse so map can be great for splitting problems into parallel processes but will always be much slower if you need to rejoin the data again to look at it so if you don't gain in performance what are the other benefits is the solution simpler or easier to read I think this is a matter of taste but I confess I don't really care very much I see no real advantage in either representation here as an old school programmer I'd probably prefer the explicit nature of the loops a little bit but it really doesn't really make that much difference to me the verbose nature of java in this example certainly doesn't show the map in its best light here as a result of that I thought I'd write it in Python instead and I have to show you this little Quirk because it's funny you can't call print from a Lambda in Python so you end up doing this instead which is certainly worse than the loop more technically though functional program is an oo programmers talk about the value of different ideas each picked to show off the advantages of their preferred approach usually oo programmers talk about the value of modeling the problem I value the higher level navigability of the problem that I get from oo that's true but this modeling isn't only the province of object orientation there's a good presentation from Marco emrich about a functional approach to domain-driven design that I particularly enjoyed I liked Marco's idea that the core domain of the system is functional and the i o at the edges is always not because it has side effects after I've stored something in a file or a database which is shared mutable State I really want the state to have changed this is an interesting insight and certainly Bears some relationship to how our usually Design Systems even though as I've said before I think of my Approach as more object oriented than functional definitions of oo usually include abstraction which allows us to hide unnecessary details inheritance defining one type of thing in terms of another polymorphism being able to access things of different types through the same interface and encapsulation which allows us to hide on interesting detail I think that most functional programmers would agree that all of these are good things perhaps with the exception of inheritance in fact all of these are principles that also underpin functional programming it's just that we describe those things in somewhat different terms functional programmers talk about declarative programming which is really a form of abstraction and information hiding and the use of types which is based on the idea of polymorphism inheritance though is tricky because while it is clearly true that it has some strong benefits it's also often been misused and can have some serious drawbacks if you create a new window or button on your display it's through inheritance that you can resize or click it object orientation was the technical step that really liberated code sharing and it's no surprise that oo and the GUI came from the same place Xerox Park the GUI is deeply an object-oriented inspired idea when non-or programmers poke fun at oo though they're often poking fun primarily inheritance that's because you can make horrible messes with inheritance to the extent that people who prefer simple binary answers to things will often say inheritance is bad of course inheritance isn't bad but bad inheritance is certainly bad the big mistake in inheritance and I'd probably say programming in general is not to model the problem that you're trying to solve well enough tactical programming is often at risk of being tactical crap for example in Java a set inherits from a vector and properties inherit from hash tables this is tactical crap a set isn't a vector properties are not hash tables this was a lazy choice because it made implementing sets and properties easier but it is nonsense really a set is not a vector and results in all sorts of features of sets in Java that make no sense at all what does index of an entry mean for a set or why would I ever wish to rehash my properties this isn't the fault of inheritance per se this is just poor tactical design choice and we can certainly make poor design choices in any language even functional languages I think that the key decisions in software are outside the technical detail of individual languages largely all programming language paradigms for that matter if you'd like to see what I mean take a look at my training course better software faster it describes what it takes to build high quality software and why that matters there's a link in the description below in Marco's presentation he quotes functional programmers saying functional programming is great because it has immutable data structures a stateless programming model pure functions and no loops these things make it easier to reason about your code they say well in most IO languages I can easily make immutable data structures program stateless code create pure functions and avoid Loops if I choose to even before choosing to use the functional features that have been added to most modern oo languages these days the real value in a more functional approach to programming as I perceive it is really in three areas treating functions as variables immutability and declarative programming functions as variables is a significant step once again you don't need a functional language to do this though I used to do versions of this in assembler C C plus plus Java and python but having direct language support certainly makes it nicer to use this allows us to pass one function as an argument to another which can then call that function if you have ever come across two very similar bits of code but there are just slightly different like this then this ability to patch a function as an argument is a really nice tool to use to simplify and generalize the code this is also the idea behind things like event handlers oh hang on isn't that an hour idea immutability is an important tool but it's never the only tool at some point you want to change things because otherwise what's the point of your code this is one reason why I liked Marco's point the i o at the edges of your system always has side effects because if it didn't your code isn't doing anything I agree that minimizing side effects in code can make things easier to reason about but it's also never the whole answer at least in the purest sense of no mutable state at the level of whole systems there are very few Corner cases where genuinely stateless systems make any sense and then only in very narrow contexts where code is acting as some kind of pipe that changes the data in some way this idea is extremely valuable as part of a system a simplifying step but in whole systems there's always State changing somewhere so the idea of stateless systems is never an absolute it is much more about where you deal with the state changes rather than eliminating them all together minimizing side effects is great in the right place and has been with hindsight an important aspect of my own approach to object-oriented design for a very long time as Michael feathers said to me in our chat a few months ago object-oriented programming looks a lot like functional program when it's done right but whether you are developing an object-oriented fashion or functional there are times when you want side effects we've already talked about the obvious times when you're doing I O of some kind if you want to write it to a file the state that the file is in matters sure you can clone any mutable snapshot of a picture of that file but immediately you do that it is at least potentially out of date because the real file on the disk is shared maybe someone else changed the file or the operating system deleted it while you were in the process of dealing with your copy now your immutable snapshot copy of the files rung the changing the file or in the database is always a side effect for another reason too it's a side effect of working with computers that forget things when we turn them off if I change the balance in my account the fact that I need to store that change somewhere isn't my goal the change in the balance is my goal so the storage is just a side effect functional programming languages of course support this kind of thing and some support ideas like monads that allow us to break the pure functions rule but in of functional programming by adding side effects but I'd argue that this is only a special case of a more general idea one of my favorite architectural approaches is to build message-based reactive systems these things are like state for actors communicating only via asynchronous messages one reason that I like these systems quite so much is that they allow me to separate The Accidental complexity and the essential complexity in my system let's imagine I have a bank account of some kind and I want to credit it in my favorite actor-based approach I may send a credit message with the value that I want to add my infrastructure will manage the i o it will save the message on its way to my service and only if the message is safely stored or clustered or whatever else will it forward it then to my service at this point my service will update the value of the account that it holds to its to to create a new total balance is this mutable state or not is this oo or not I'd say that this is a very oh way of thinking and working my actors embody a rich state for domain models of the problem I'm solving but here my side effects the storage are isolated more isolated perhaps than in some functional systems and The Changing State an important one that must be represented somewhere is clearly expressed and easy to understand and can't happen without the side effects that matter having taken place after all I don't want my hundred euros to disappear and I want to know that my total is even after a crash or a restart if I want to know what the balance is for my account I can query this stateful copy but I can also discard this copy and recreate it into exactly the same state as before by replaying the message of the messages that I stored but I can also discard this copy and recreate it in exactly the same state as before by replaying the message that I stored earlier so once again is this state here mutable or not actually I think it's kind of both my point here is not to sing the Praises of reactive systems well maybe just a bit but to point out that the line between object orientation and functional programming and maybe even actors is all a bit more blurry than the culture wars would sometimes suggest yes it is sensible to minimize side effects in your code whatever the nature of your code but is there really a big difference between having a function that takes two arguments one of them supplied by another function that defines its value and an object with a private member variable that is used instead of the function supplied variable sure the oo code here is more verbose but that's a different question really all that's really going on here is how we decide to represent the sequencing of the function calls we could debate which one's easier to read and there are arguments on both sides but I do believe that if we're optimizing only to minimize typing we're already looking in the wrong place there isn't an awful lot of typing in assembler programs after all optimizing for thinking is much more important my point here is not to rubbish functional programming my point is that I think that the debate should be a lot more nuanced than oh well bad functional programming good or vice versa there are certainly times when functional programming is more terse and terse can be good but it can also be bad ultimately depending on how easy the code is to read and understand the last of the ideas that functional program is often cite as the real value of functional programming is the advantage of declarative over imperative programming I've spoken about this before there are certainly significant advantages to expressing some ideas declaratively my approach to test driven development is all what is to always aim to declare in my tests what I want the system to do without attempting to test how it does it or say how it does it this means that my tests are a lot more durable to change than tests that attempt to assert the implementation detail in the code this is the same idea as declarative programming if you can clearly Express the outcome that we'd like to achieve without worrying about how the outcome is achieved then great I see lots of example of this in examples of functional code but to be honest it's less obvious in people's real code as far as I can see to be fair my exposure to reading other people's functional code is somewhat limited I don't read lots of it so this may be down to the limits of my experience but if this is the case if the levels of abstraction that functional languages give to us are genuinely as advantageous as functional programmers tell us that they are then shouldn't functional Pro projects prove to be a lot faster to develop and produce fewer bugs than non-functional this is the claim that functional programmers sometimes make but I have looked and I don't find much evidence to support this claim functional programming does appear to produce fewer bugs but the research that I've read says that this is at or close to the level of statistical noise resulting in about a one percent fewer bug fix commits than imperative languages when measured by comparing the ratio of commits that that are for new things versus commits that are intended to fix bugs to put this into context the data for unit testing says that you get somewhere around 58 reduction in production defects overall though measured in a completely different way so it may not be fair of me to make this comparison but the difference if any in the quality of the code produced by functional programming versus object-oriented programming languages seems to be tiny I think that both functional programming and object orientation are valuable tools but I also think that there are some extravagant claims made for functional programming in particular that to me at least don't seem to stand up to scrutiny my conclusion is that it pays to understand both functional programming and object-oriented programming the idea that functional programming is a Step Beyond object orientation in the evolution of programming languages seems just a complete misinterpretation of the history and of what's going on in reality our ownfp are both valuable tools for building complex systems use them in the right context and each will help you to build better systems but neither is the deciding factor thank you very much for watching and if you enjoy my stuff please do consider supporting our work on this channel by joining our patreon community there's a link in the description below thank you [Music]
Info
Channel: Continuous Delivery
Views: 47,115
Rating: undefined out of 5
Keywords: object oriented programming, object oriented coding, object oriented programming vs functional programming, oo programming, object oriented programming is bad, functional programming, functional programming example, functional programming tutorial, what is functional programming, functional programming explained, Continuous Delivery, software engineering, software development, Dave Farley, programming, what is object oriented programming, oop, computer science, software paradigm
Id: Ly9dtWwqqwY
Channel Id: undefined
Length: 23min 0sec (1380 seconds)
Published: Wed Mar 15 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.