The true definition of immutability?

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

    Lots of questions there. I'll try to answer each of them individually:

    • "I am wondering how immutability is defined?" - Straight from the Wikipedia page (and a perfectly accurate/concise definition)

      An immutable object is an object whose state cannot be modified after it is created

    • "If the values aren't exposed as public, so can't be modified, then it's enough?" - Not quite. It can't be modified in any way whatsoever, so you've got to insure that methods/functions don't change the state of the object, and if performing operations, always return a new instance.

    • "Can the values be modified inside the type, not by the customer of the type?" - Technically, it can't be modified either inside or by a consumer of the type. In pratice, types such as System.String (a reference type for the matter) exist that can be considered mutable for almost all practical purposes, though not in theory.

    • "Or can one only set them inside a constructor?" - Yes, in theory that's the only place where state (variables) can be set.

    • "If so, in the cases of double initialization (using the this keyword on structs, etc) is still ok for immutable types?" - Yes, that's still perfectly fine, because it's all part of the initialisation (creation) process, and the instance isn't returned until it has finished.

    • "How can I guarantee that the type is 100% immutable?" - The following conditions should insure that. (Someone please point out if I'm missing one.)

      1. Don't expose any variables. They should all be kept private (not even protected is acceptable, since derived classes can then modify state).
      2. Don't allow any instance methods to modify state (variables). This should only be done in the constructor, while methods should create new instances using a particular constructor if they require to return a "modified" object.
      3. All members that are exposed (as read-only) or objects returned by methods must themselves be immutable.

      Note: you can't insure the immutability of derived types, since they can define new variables. This is a reason for marking any type you wan't to make sure it immutable as sealed so that no derived class can be considered to be of your base immutable type anywhere in code.

    Hope that helps.

提交回复
热议问题