Mutable or immutable class?

后端 未结 8 1873
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2020-12-17 21:46

    As cletus said, immutable classes simplify class design and handling in synchronized methods.

    They also simplify handling in collections, even in single-threaded applications. An immutable class will never change, so the key and hashcode won't change, so you won't screw up your collections.

    But you should keep in mind the lifecycle of the thing you're modeling and the "weight" of the constructor. If you need to change the thing, immutable objects become more complex to deal with. You have to replace them, rather than modify them. Not terrible, but worth considering. And if the constructor takes nontrivial time, that's a factor too.

提交回复
热议问题