Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix apparently incompatible paradigms: OOP and FP? [closed]

Reading back some of my Scala code, I noticed that it is either functional or object oriented.

Indeed, I have no idea on how to conciliate the no-side effects rule implied by immutable types and pure functions and the premise of OO, where methods modify instance state in-place, which is obviously side-effects.

One solution I am investigating is to make all methods return a clone of the current instance with the appropriate state modifications. Seems eager, but might help when I'll decide to paralelize the code, right ?

What are the best practices on mixing those 2 paradigms ? What is the balance ?

Thanks.

like image 561
Alexandre Mazari Avatar asked Oct 27 '11 15:10

Alexandre Mazari


People also ask

Can you mix functional and object oriented programming?

Combining functional and object-oriented programming methodologies in a large commercial application. Abstract: Functional programming concepts of referential transparency and lazy evaluation combine effectively with object oriented encapsulation.

Is language which uses both OOP and FP paradigm?

Several programming languages, such as TypeScript and Python, are multi-paradigm and support both OOP and functional programming to some capacity. These languages have certain allowances to utilize pure functions, and immutable objects at the developer's will.

Can FP replace OOP?

Lisp is a popular procedural functional language, Java is an object-oriented imperative language. @ventr1s: Yes, functional programming can replace OOP but it is most likely to be used together with OOP in languages like Scala and F#.


1 Answers

Immutable classes are a very good way to bridge OO and FP. Scala's Collection Library is a great example of blending OO, immutable objects and functional programming.

In your own code, Scala's case classes really help implementing immutable object, since they have a copy method which can be used as a replacement for the builder pattern.

// begin cheesy example
case class Circle(center: (Double, Double), radius: Double) {
  def move(c: (Double, Double)) = copy(center = c)
  def resize(r: Double) = copy(radius = r)
  def area = math.Pi * radius * radius
}

You may also benefit watching Rich Hickey's talks Persistent Data Structures and Managed References, and Are We There Yet? Both do an excellent job explaining the need for immutability, and how it helps us reason about state. He talks about everything with respect to Clojure, but his points apply equally well to Scala.

like image 71
leedm777 Avatar answered Oct 21 '22 15:10

leedm777