Is Object Oriented Programming Compatible with Functional Programming?

I grew up learning Java and over the past few years I have started learning a lot of PHP using the popular open source CMSs. I really like the natural feel of OOP, but I recently discovered the concept of functional programming, which seems like a tricky yet elegant way of doing things.

In rtperson excellent answer to the question " What is functional, declarative and imperative programming? [Closed] ," he says, "Then there is an object-oriented programming, which is actually just a new way to organize data in an imperative program."

I think I understand what he means, but is it true? Can OOP coexist with functional programming?

+3


source to share


3 answers


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

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



Examples of such languages ​​are:

  • Scala (I really like this)
  • Boost :: function, Boost :: bind in C ++
  • .NET F #
  • javascript (aka ECMAScript)
+1


source


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



If you think about it, o.something(y)

simple osomething(o, y)

, and as long as you don't mutate o

or do other non-OO side effects, it's functional.

+1


source


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

Also, there is nothing about mutable state that makes it "not purely functional"; which is impure when the normal evaluation of an expression changes the state visible to the program. This way you can combine OO and purely functional programming by making your object methods return actions in the IO monad (or any other monastic monk) that mutate the common baseline set (not available to the rest of the program).

0


source







All Articles