The true definition of immutability?

后端 未结 10 1840
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 03:15

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

相关标签:
10条回答
  • 2021-02-09 03:58

    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.

    0 讨论(0)
  • 2021-02-09 03:58

    Here is the definition of immutability from Wikipedia (link)

    "In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created."

    Essentially, once the object is created, none of its properties can be changed. An example is the String class. Once a String object is created it cannot be changed. Any operation done to it actually creates a new String object.

    0 讨论(0)
  • 2021-02-09 03:58

    An immutable is essentially a class that forces itself to be final from within its own code. Once it is there, nothing can be changed. In my knowledge, things are set in the constructor and then that's it. I don't see how something could be immutable otherwise.

    0 讨论(0)
  • 2021-02-09 04:00

    One thing that I think might be missed in all these answers is that I think that an object can be considered immutable even if its internal state changes - as long as those internal changes are not visible to the 'client' code.

    For example, the System.String class is immutable, but I think it would be permitted to cache the hash code for an instance so the hash is only calculated on the first call to GetHashCode(). Note that as far as I know, the System.String class does not do this, but I think it could and still be considered immutable. Of course any of these changes would have to be handled in a thread-safe manner (in keeping with the non-observable aspect of the changes).

    To be honest though, I can't think of many reasons one might want or need this type of 'invisible mutability'.

    0 讨论(0)
提交回复
热议问题