Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of Immutable objects

I know that Immutable objects offer several advantages over mutable objects like they are easier to reason about than mutable ones, they do not have complex state spaces that change over time, we can pass them around freely, they make safe hash table keys etc etc.So my question is what are the disadvantages of immutable objects??

like image 337
Aamir Avatar asked Dec 08 '22 00:12

Aamir


1 Answers

Quoting from Effective Java:

The only real disadvantage of immutable classes is that they require a separate object for each distinct value. Creating these objects can be costly, especially if they are large. For example, suppose that you have a million-bit BigInteger and you want to change its low-order bit:

BigInteger moby = ...; 
moby = moby.flipBit(0);

The flipBit method creates a new BigInteger instance, also a million bits long, that differs from the original in only one bit. The operation requires time and space proportional to the size of the BigInteger. Contrast this to java.util.BitSet. Like BigInteger, BitSet represents an arbitrarily long sequence of bits, but unlike BigInteger, BitSet is mutable. The BitSet class provides a method that allows you to change the state of a single bit of a millionbit instance in constant time.

Read the full item on Item 15: Minimize mutability

like image 137
Ali Dehghani Avatar answered Dec 28 '22 17:12

Ali Dehghani