Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are immutable objects good practice? [closed]

Tags:

Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety) Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them? Or is it not worth the inconvenience you have to create them?

like image 798
magnattic Avatar asked Jan 21 '11 20:01

magnattic


People also ask

Is it better to use immutable objects in Java?

References to immutable objects can be cached as they are not going to change. As a good programming practice in Java one should try to use immutable objects as far as possible. Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it.

Should you create an immutable class?

Creating an immutable class seems at first to provide an elegant solution. However, whenever you do need a modified object of that new type you must suffer the overhead of a new object creation, as well as potentially causing more frequent garbage collections.

What are the disadvantages of immutability?

Immutability can have a performance cost, since when an object cannot be mutated we need to copy it if we want to write to it. When you care a lot about performance (e.g. programming a game) it may be necessary to use a mutable object. Even then it is often better to try to limit the mutability of objects.

Is it possible to implement immutability in imperative programming languages?

@PéterTörök In an imperative language mutable objects are the default behavior. If you want only immutable objects, it is best to switch to a functional language. – emory Jun 8 '12 at 1:15 3 @PéterTörök It's a little naive to assume that incorporating immutability into a program involves nothing more than dropping all setters.


1 Answers

The immutable Eric Lippert has written a whole series of blog posts on the topic. Part one is here.

Quoting from the earlier post that he links to:

ASIDE: Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change. Since they cannot be modified, they are automatically threadsafe. Since they cannot be modified, you can maintain a stack of past “snapshots” of the structure, and suddenly undo-redo implementations become trivial. On the down side, they do tend to chew up memory, but hey, that’s what garbage collection was invented for, so don’t sweat it.

like image 167
Thomas Avatar answered Sep 30 '22 09:09

Thomas