Design with immutability (in Scala)

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

Let's look at the 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 will not point to the same Turtle instance (these are two separate instances). In fact, 4 temporary objects were created in this sequence of movements. Here is how I could implement the turnLeft method, for example:

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

Is this the right design approach?

If so, how effective / inefficient (creating a new object with every method call)? If not, what will be right? What is wrong or missing in my understanding of the aspect of immutability (or, possibly, functional programming in general)?

Thanks in advance, Raka

+5
source share
2 answers

Creating lots and many short-lived objects is a hallmark of scala. This, as a rule, is not very expensive, provided that you run it on a JVM with a sufficient heap size, having a sufficient amount of memory of the younger generation to accommodate the entire outflow.

Having said that, immutability is not a religion. Common sense should prevail and be guided by design decisions when adhering to the โ€œparadigmโ€ becomes too taxable.

+9
source

I think it's important to think about whether you want to treat your Turtle as an entity.

If I have a car, and I turn the wheel to the right, the car goes to the right (in the best case: P), then I turn the wheel to the left, and it goes to the left, but it's still the same car. The same goes for the tortoise. Although immutability usually makes programs more understandable, there are times when it is less intuitive.

Think about the difference between the right headline and the left turtle. Of course, checking the equality can be excessive, so the theoretical difference is rather that the old and the new turtle (with the same name / id) are the same only by equality or also by reference.

+1
source

Source: https://habr.com/ru/post/1210336/


All Articles