Mutable or immutable class?

后端 未结 8 1879
死守一世寂寞
死守一世寂寞 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:55

    The main benefit of immutable classes however is that you can expose internal data members that are immutable because the caller can't modify them. This is a huge problem with, say, java.util.Date. It's mutable so you can't return it directly from a method. This means you end up doing all sorts of defensive copying. That increases object proliferation.

    The other major benefit is that immutable objects do not have synchronization issues, by definition. That's where the scalability issues come in. Writing multithreaded code is hard. Immutable objects are a good way of (mostly) circumventing the problem.

    As for "static classes", by your comment I take it to mean classes with factory methods, which is how it's usually described. That's an unrelated pattern. Both mutable and immutable classes can either have public constructors or private constructors with static factory methods. That has no impact on the (im)mutability of the class since a mutable class is one whose state can be changed after creation whereas an immutable class's state cannot be changed after instantiation.

    Static factory methods can have other benefits however. The idea is to encapsulate object creation.

提交回复
热议问题