Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Designing with immutability (in Scala)

With the emphasis on immutability in programming language like Scala (avoid "var"), does it mean "state-modifying methods" in my object will have to return a copy of the instance (with the new state)?

Let's consider turtle. I would like to move my turtle like this:

val turtle = new Turtle(0, 0, "north")
val turtle2 = turtle.turnLeft().forward(5).turnRight().backward(2)

Here turtle2 wouldn't point to the same instance of Turtle (they're two separate instances). In fact, in that sequence of movements 4 interim objects were created. This is how I would implement the method turnLeft, for example:

def turnLeft {
  self.copy(orientation = self.orientation match {
    case "north" => "west"
    case "east" => "north"
    case "south" => "east"
    case "west" => "south"
  })
}

Is that a correct design approach?

If yes, how efficient / inefficient is that (creation of new object on every method call)? If no, what would be the right one? What is wrong / missing in my understanding of immutability aspect (or maybe functional programming in general)?

Thanks in advance, Raka

like image 966
Cokorda Raka Avatar asked Jan 04 '15 01:01

Cokorda Raka


1 Answers

Creation of lots and lots of short-lived objects is a hallmark feature of scala. It is generally not very expensive, provided you run it on a JVM with adequately sized heap, having a sufficient amount of young generation memory to accommodate all of the churn.

Having said that, immutability is not a religion. Common sense should prevail, and guide the design decisions where sticking to the "paradigm" becomes too taxing.

like image 108
Dima Avatar answered Oct 10 '22 21:10

Dima