What are the advantages of an immutable structure over a mutable one?

I already know the advantage of immutability over variability in the ability to talk about code and introduce fewer errors, especially in multi-threaded code. However, when creating structures, I see no benefit from creating a completely immutable structure over a mutable version.

Let as an example of a structure that stores a certain score:

struct ScoreKeeper {
    var score: Int
}

In this structure, I can change the value of the estimate for an existing structural variable

var scoreKeeper = ScoreKeeper(score: 0)
scoreKeeper.score += 5
println(scoreKeeper.score)
// prints 5

An immutable version will look like this:

struct ScoreKeeper {
    let score: Int

    func incrementScoreBy(points: Int) -> ScoreKeeper {
        return ScoreKeeper(score: self.score + points)
    }
}

And its use:

let scoreKeeper = ScoreKeeper(score: 0)
let newScoreKeeper = scoreKeeper.incrementScoreBy(5)
println(newScoreKeeper.score)
// prints 5

, , , . , . , mutable, , .

, , . - , ?

+4
5

. , . , , , , - .

, , , . , PhoneNumber AreaCode, LocalExchange LocalNumber , , "" , , , LocalExchange LocalNumber, , , AreaCode, .

+1

. , () ( ), , , , , , , . .

, . - , . ;) , , , .

+1

, , .

, , - , .

0

, , , - - . , .

0

, , . Mutable , , .

, - .

, , .

NSNumber . NSNumber, , , , .

, - , , . , , "factory", , .

Such a scheme can simplify parallel code, as mentioned above. In this case, you do not have to protect the values ​​of your structures changing in another thread. If you used such a structure, you might know that it will never change.

0
source

All Articles