How Object Oriented Programming and Functional programming can be used together? - functional-programming

Scala claims than OO and FP can be combined.
I wonder how this can be achieved in practice. I mean object can change, so making them immutable means i have to create a new object whenever something changes right? This doesn't seem too effective to me.
By the way, if i make external reference to an object property from a function, doesn't it hurts referential transparency?

Don't think of this as one paradigm imposing restrictions on the other but as how can one take the best of both paradigms.
As a simple example:
Objects have functions which can be internal to an object. Now the internal functions can be immutable within an object and those results of a function can be used to change the state of a object.
Thinking at a different level one can use functions to create a library that can be used by objects.
How I like to make the best of both is I tend to make libraries (modules) for the more abstract processing using a functional language and then use OO languages for the layers closer to human and external processing. This is not a hard and fast rule but a guideline from where I start.

Related

Immutablejs within plain objects - Monads

The redux best practices says not to mix plain javascript object with immutablejs objects. I'm trying my hand at functional programming and it seems like the monads require the computations/values to be stored inside an object, or some container of sorts. AFAIK immutablejs maps can't store methods. Are there any issues with using FP libraries like Folktale? I haven't noticed any noticeable issues with the basic todo app (which is all I can try at the moment), so I'm hoping for some clarification on immutablejs best practices, hopefully FP leaning.
Never mix plain JavaScript objects with Immutable.JS
Ok, I feel like a fool. I read the linked article again and saw that it's not about performance, but to avoid confusion as to when data passed is immutable or a pojo. Here's the relevant section from the article
In fact, sometimes you might be tempted to put a normal JavaScript object inside an Immutable map. Don't do this. Mixing immutable and mutable state in the same object will reap confusion.
http://jlongster.com/Using-Immutable-Data-Structures-in-JavaScript

Objects Referential transparency for functional programming in Java 8

I have been studying functional programming and one of the requirements is that they are pure in the sense that they only return the computed value and not touch anything else or throw exceptions, they don't also access shared mutable objects - this makes them inherently thread safe.
So then what would be the correct approach to implement a pure function that takes objects as arguments rather than primitive values. Would I have to deep clone them when passing to a function ?
If the function is a pure function, i.e. does not modify existing objects, whether they are passed as parameters or lying around somewhere else, there is no sense is copying or cloning the argument objects.
You could also see it the other way round: if cloning arguments is necessary, the invoked code is not functional and cloning the arguments doesn’t turn it into functional code, it’s actually working around a design flaw.
In the best case, you would be working with immutable objects which prevent modifications intrinsically, however, using immutable objects doesn’t change the way how the functional code should behave, they just enforce some aspects of it. When a particular class does not offer immutable objects, you can still use it in the right way, without the need to re-implement it in an immutable way.
Generally, it is not a good idea to develop your code assuming that all other code will misbehave and that it was your code’s task to solve the issues of that misbehavior.
The objects should ideally be immutable. Immutability and functional programming go hand-to-hand.
If having all immutable objects isn't feasible, yes, you would ideally need to make deep copies of everything to ensure changes to them don't effect anything else outside of the function.

Passing several primitive type members vs passing the outer mutable object - does functional programming express any preference?

Functional programming attempts to ensure freedom from side-effects when invoking functions. Passing a mutable object as a parameter that is NOT returned gives a developer the ability to modify a non-returned object. In other words, side-effects are possible. If you pass primitive or immutable types, you are free from this extra layer of complexity when reasoning about a program. So does good Functional Programming practice dictate anything when you have the choice between passing a mutable object vs passing primitive types?
I am aware of the following properties of PURE functional programming:
If all your types are immutable, it doesn't matter whether they are object types
The mutable object cannot exist outside the scope where it is expected to be mutated
but in reality when you are dealing with huge code bases that have existed prior to Functional Programming gaining a newfound respect, you will often be dealing with data structures that have no corresponding immutable representation, and code will be a mixture of functional and imperative styles.
(Background - I am exposing C++ logic via Java Native Interface and am wondering when to avoid passing objects, but I'm not looking for an answer that directly applies to this use case. I just want some help applying good programming practice in a situation such as this)
I think the only thing that functional programming has to say about this matter is that you should ideally wrap all impure stuff that you expose, in a monad, such as the famous IO monad.
But this is probably too radical for your users.

If globals are bad, why does every web framework use them?

Every web development framework I've come across, including the best designed ones (Web2Py, Kohana) make use of some form of global variables to represent objects that are global within the application domain- for example, objects representing 'request' and 'response'.
On the other hand, the idea that global variables are bad is one of the fundamental axioms of programming. Indeed the now common disparagements of the singleton pattern usually point to the fact that it's nothing more than globals in disguise, as if that were explanation enough.
I'm trying to understand once and for all how globals can be so condemnable and at the same time be a seemingly indispensable part of all our web frameworks?
What is a global? Taking your text I assume you mean a variable that's declared at global scope. Such variable could be overridden by any assignment and break existing functionality.
However, in OO languages, everything is inside a class and assignment can be wrapped in gettors and settors for properties, or completely hidden behind methods. This gives a safe way of dealing with globals. Note that in proper OO languages (Java, C#, VB.NET etc) it is not possible to have global variables (sometimes a language construct suggests otherwise, but static fields in C# or modules in VB, mixins in Ruby are all wrapped in classes and thus not truly global).
A singleton, you mention it, is a special kind of global. As a designer you can control how many instances run of it. A car only needs one engine, a country only one government (or war breaks loose) and a program needs only one main thread. Globals are a necessity to programming, the real discussion should not be, do we need them, but how to solidly create and use them.
You say that request and response objects are globals in web development. They are not. They are (usually, depending on your toolset) convenience variables set in scope before your code is run. Since a web application can have multiple request objects at any given time, I think these are a poor example of a global variable. They are not (but they are usually local and a singleton to your current thread).
One important feature that you cannot cover in traditional procedural languages (like Basic, Pascal, C) is access control and thus concurrency and thread safety for global variables. In .NET for instance, any static method or property in the BCL (one could say that any static variable is global by definition) is thread-safe by design. Guidelines for user-defined static methods or properties suggest you do the same.
EDIT: the danger is with languages that allow global variables but at the same time propagate themselves as truly OO. While these are wonderful languages, it is indeed dangerous to step out of the protection of OO and create globals in for instance Perl, Python, Ruby, PHP.
I don't know exactly in what context those globals are used in web frameworks, but anything global starts to create problems as soon as you need to have solid access control. If you start to use such a global in concurrently executing program, it's quite hard to say who and when accessed and changed it. It creates so-called shared state. This makes debugging even more difficult.
Anyway, I am not really in favour of such statements. This only leads to oversimplifications. You have to weight you requirements and then decide if this or that pattern brings more positive or negative effects...

Function Programming and Mock Objects

I was recently watching a webcast on Clojure. In it the presenter made a comment in the context of discussing the FP nature of Clojure which went something like (I hope I don't misrepresent him) "Mock objects are mocking you".
I also heard a similar comment a while back when I watched a webcast when Microsoft's Reactive Framework was starting to appear . It went something like "Mock objects are for those who don't know math")
Now I know that both comments are jokes/tongue-in-cheek etc etc (and probably badly paraphrased), but underlying them is obviously something conceptual which I don't understand as I haven't really made the shift to the FP paradigm.
So, I would be grateful if someone could explain whether FP does in fact render mocking redundant and if so how.
In pure FP you have referentially transparent functions that compute the same output every time you call them with the same input. All the state you need must therefore be explicitly passed in as parameters and out as function results, there are no stateful objects that are in some way "hidden behind" the function you call. This, however, is, what your mock objects usually do: simulate some external, hidden state or behavior that your subject under test relies on.
In other words:
OO: Your objects combine related state and behavior.
Pure FP: State is something you pass between functions that by themselves are stateless and only rely on other stateless functions.
I think the important thing to think about is the idea of using tests help you to structure your code. Mocks are really about deferring decisions you don't want to take now (and a widely misunderstood technique). Instead of object state, consider partial functions. You can write a function that takes defers part of its behaviour to a partial function that's passed in. In a unit test, that could be a fake implementation that lets you just focus on the code in hand. Later, you compose your new code with a real implementation to build the system.
Actually, when we were developing the idea of Mocks, I always thought of Mocks this way. The object part was incidental.

Resources