

When immutable objects can not be used in Java or is it better to use mutable?
source link: https://www.codesd.com/item/when-immutable-objects-can-not-be-used-in-java-or-is-it-better-to-use-mutable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

When immutable objects can not be used in Java or is it better to use mutable?
It is obvious that immutable objects should be used most of the time and whenever it is possible. EDIT
Here are some articles to encourage this practice: https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- are simple to construct, test, and use
- are automatically thread-safe and have no synchronization issues
- don't need a copy constructor
- don't need an implementation of clone
- allow hashCode to use lazy initialization, and to cache its return value
- don't need to be copied defensively when used as a field
- make good Map keys and Set elements (these objects must not change state while in the collection)
- have their class invariant established once upon construction, and it never needs to be checked again
- always have "failure atomicity" (a term used by Joshua Bloch): if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
http://www.javapractices.com/topic/TopicAction.do?Id=29
However are there scenarios where immutable objects are not good to be used or can't be used for some reason ?
Reflection based frameworks are complicated by immutable objects since they requires constructor injection:
there are no default arguments in Java, which forces us to ALWAYS provide all of the necessary dependencies constructor overriding can be messy constructor argument names are not usually available through reflection, which forces us to depend on argument order for dependency resolution
With immutability, any time you need to modify data, you need to create a new object. This can be expensive.
Imagine needing to modify one bit in an object that consumes several megabytes of memory: you would need to instantiate a whole new object, allocate memory, etc. If you need to do this many times, mutability becomes very attractive.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK