The true definition of immutability?

后端 未结 10 1899
被撕碎了的回忆
被撕碎了的回忆 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.

提交回复
热议问题