Is object-orientated programming compatible with functional programming?

544 views Asked by At

I grew up being taught java, and I've started to learn a lot of PHP over the last few years using popular open-source CMSs. I really love the natural-feeling of OOP, but I've more recently discovered the concept of functional programming, which appears to be a difficult but elegant way of doing things.

In rtperson's great answer to the question "What is functional, declarative and imperative programming? [closed]", he says that "Then there's Object-oriented programming, which is really just a new way to organize data in an imperative program."

I think I understand what he means by that, but is it strictly true? Can OOP co-exist with functional programming?

3

There are 3 answers

1
Martin Meeser On

Yes, there is a term of "object functional programming". Basically in those languages a function is a "first class citizen" - an object.

I guess most agree it is not so easy to get there just because you have to know about all concepts - functional, OO and imperative.

Examples for such languages are:

  • Scala (I like it very much)
  • Boost::function , Boost::bind in C++
  • .NET F#
  • javascript (aka ECMAScript)
0
Jonathan Cast On

Yes. There is something called a 'functional object', which is basically an object where the mutator methods, instead of changing the state of the object, return a new object with modified state. Clean combines that idea with uniqueness types to keep the modified states single-threaded, which allows the compiler to implement methods by modifying the storage for the object behind the scenes.

Furthermore, there's nothing about mutable state that makes it 'not purely functional'; what's impure is when ordinary expression evaluation mutates state that's visible to the program. So you can combine OO and purely functional programming by making your object's methods return actions in the IO monad (or any other stateful monad) that mutate a common set of underlying state (not available to the rest of the program).

0
Sylwester On

Yes it's compatible. You can program in a functional way in any language. An example would be Java String which is immutable and returns a new object if you do altering methods such as change case etc.

If you think about it o.something(y) is just osomething(o, y) and if you don't mutate o or do other side effects not related to OO it's functional.