Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need mutable classes?

Tags:

java

I read a chapter of Effective Java today. The chapter is about minimizing mutability of objects. I pretty understand why immutable objects are good, such as thread-safe, simplicity, etc. My question is since immutable objects have so many advantages, are there any cases where mutable objects are preferred?

like image 934
Ryan Avatar asked Dec 08 '22 08:12

Ryan


1 Answers

You need mutable classes to deal with situations when transforming a class from state A to state Z would produce a lot of intermediate objects, which you would rather not spend time creating.

One classic example is concatenating an array of strings. Let's say that you need to concatenate 100 strings, and produce a single result. Without a mutable string, you would need to produce 98 intermediate objects that would become eligible for garbage collection almost immediately. This is rather wasteful on the CPU, making a mutable object the right solution.

There are other situations when mutable objects are desirable. For example passing mutable objects into methods lets you collect multiple results without jumping through too many syntactic hoops. Another example is sorting and filtering: of course, you could make a method that takes the original collection, and returns a sorted one, but that would become extremely wasteful for larger collections.

like image 149
Sergey Kalinichenko Avatar answered Dec 10 '22 21:12

Sergey Kalinichenko