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.
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.
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.
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#.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With