Mutable or immutable class?

后端 未结 8 1904
死守一世寂寞
死守一世寂寞 2020-12-17 21:44

I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class inc

8条回答
  •  没有蜡笔的小新
    2020-12-17 21:47

    Immutability is generally used to achieve scalability, since immutability is one of the enablers when it comes to concurrent programming in java. So while, as you point out, there may be more objects in an "immutable" solution, it may be a necessary step to improve concurrency.

    The other, equally important use og immutability is to consume a design intention; whoever made an immutable class intended you to put mutable state elsewhere. If you start mutating instances of that class, you are probably breaking the original intention of the design - and who knows what the consequences may be.

提交回复
热议问题