Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The true definition of immutability?

I am wondering how immutability is defined? If the values aren't exposed as public, so can't be modified, then it's enough?

Can the values be modified inside the type, not by the customer of the type?

Or can one only set them inside a constructor? If so, in the cases of double initialization (using the this keyword on structs, etc) is still ok for immutable types?

How can I guarantee that the type is 100% immutable?

like image 236
Joan Venge Avatar asked May 26 '09 21:05

Joan Venge


People also ask

What is the meaning of immutability?

the state of not changing, or being unable to be changed: His poetry conveys a sense of the immutability of nature.

What is the biblical definition of the word immutability?

The Immutability of God is an attribute that "God is unchanging in his character, will, and covenant promises." The Westminster Shorter Catechism says that "[God] is a spirit, whose being, wisdom, power, holiness, justice, goodness, and truth are infinite, eternal, and unchangeable." Those things do not change.

What is the law of immutability?

Something that is immutable will never change or cannot be changed.

Why is immutability so important?

Immutability allows you to track the changes that happen to these objects like a chain of events. Variables have new references that are easy to track compared to existing variables. This helps in debugging the code and building the concurrent application.


2 Answers

If the values aren't exposed as public, so can't be modified, then it's enough?

No, because you need read access.

Can the values be modified inside the type, not by the customer of the type?

No, because that's still mutation.

Or can one only set them inside a constructor?

Ding ding ding! With the additional point that immutable types often have methods that construct and return new instances, and also often have extra constructors marked internal specifically for use by those methods.

How can I guarantee that the type is 100% immutable?

In .Net it's tricky to get a guarantee like this, because you can use reflection to modify (mutate) private members.

like image 55
Joel Coehoorn Avatar answered Sep 20 '22 08:09

Joel Coehoorn


The previous posters have already stated that you should assign values to your fields in the constructor and then keep your hands off them. But that is sometimes easier said than done. Let's say that your immutable object exposes a property of the type List<string>. Is that list allowed to change? And if not, how will you control it?

Eric Lippert has written a series of posts in his blog about immutability in C# that you might find interesting: you find the first part here.

like image 42
Fredrik Mörk Avatar answered Sep 18 '22 08:09

Fredrik Mörk