What is immutability and why should I worry about it?

前端 未结 15 1047
无人共我
无人共我 2020-12-07 09:51

I\'ve read a couple of articles on immutability but still don\'t follow the concept very well.

I made a thread on here recently which mentioned immutability, but as

相关标签:
15条回答
  • 2020-12-07 10:37

    An immutable object is something which you can safely assume isn't going to change; it has the important property that everyone using it can assume they're seeing the same value.

    Immutability usually also means you can think of the object as being a "value", and that there's no effective difference between identical copies of the object and the object itself.

    0 讨论(0)
  • 2020-12-07 10:38

    An example of the potential performance benefits offered by immutable objects is available in the WPF API. A common base class of many WPF types is Freezable.

    Several WPF examples suggest that freezing objects (making them immutable at runtime) can improve application performance significantly as locking and copying is not required.

    Personally I wish the concept of immutability was easier to express in the language I use most often, C#. There is a readonly modifier available for fields. I would like to see a readonly modifier on types as well that would only be allowed for types that only have readonly fields that are of readonly types. Essentially this means that all state would need to be injected at construction time, and that and entire object graph would be frozen. I imagine that were this metadata intrinsic to the CLR then it could be easily used to optimise garbage analysis for GC.

    0 讨论(0)
  • 2020-12-07 10:45

    Making things immutable prevents a large number of common mistakes.

    For example, a Student should never have their student # change on them. If you don't provide a way to set the variable (and make it const, or final, or whatever your language supports) then you can enforce that at compile time.

    If things are mutable and you don't want them to change when you pass them around you need to make a defencive copy that you pass. Then if the method/function you call changes the copy of the item the original is untouched.

    Making things immutable means you do not have to remember (or take the time/memory) to make defencive copies.

    If you really work at it, and think about each variable you make, you will find that the vast majority (I typically have 90-95%) of your variables never change once they are given a value. Doing this makes programs easier to follow and reduces the number of bugs.

    To answer your question on state, state is the values that variables of an "object" (be that a class or a struct) have. If you took a person "object" state would be things like eye colour, hair colour, hair length, etc... some of those (say eye colour) do not change while others, such as hair length do change.

    0 讨论(0)
  • 2020-12-07 10:47

    Good question.

    Multi-threading. If all types are immutable then race conditions don't exist and you're safe to throw as many threads at the code as you wish.

    Obviously you can't accomplish that much without mutability save complex calculations so you usually need some mutability to create functional business software. However it is worth recognising where immutability should lie such as anything transactional.

    Look up functional programming and the concept of purity for more information on the philosophy. The more you store on the call stack (the params you're passing to methods) as opposed to making them available via references such as collections or statically available objects the more pure your program is and the less prone to race conditions you will be. With more multi-cores these days this topic is more important.

    Also immutability reduces the amount of possibilities in the program which reduces potential complexity and potential for bugs.

    0 讨论(0)
  • 2020-12-07 10:47

    "... why should I worry about it?"

    A practical example is repetitive concatenation of strings. In .NET for example:

    string SlowStringAppend(string [] files)
    {
        // Declare an string
        string result="";
    
        for (int i=0;i<files.length;i++)
        {
            // result is a completely new string equal to itself plus the content of the new
            // file
            result = result + File.ReadAllText(files[i]);
        }
    
        return result;
    }    
    
    string EfficientStringAppend(string [] files)
    {
        // Stringbuilder manages a internal data buffer that will only be expanded when absolutely necessary
        StringBuilder result=new SringBuilder();
    
        for (int i=0;i<files.length;i++)
        {
            // The pre-allocated buffer (result) is appended to with the new string 
            // and only expands when necessary.  It doubles in size each expansion
            // so need for allocations become less common as it grows in size. 
            result.Append(File.ReadAllText(files[i]));
        }
    
        return result.ToString();
    }
    

    Unfortunately using the first (slow) function approach is still commonly used. An understanding of immutability makes it very clear why using StringBuilder is so important.

    0 讨论(0)
  • 2020-12-07 10:49

    To put it simple: Once you create an immutable object, there's no way to change the contents of that object. Examples of .Net immutable objects are String and Uri.

    When you modify a string, you simply get a new string. The original string will not change. An Uri has only readonly properties and no methods available to change the content of the Uri.

    Cases that immutable objects are important are various and in most of the cases have to do with security. The Uri is a good example here. (e.g. You don't want a Uri to be changed by some untrusted code.) This means you can pass a reference to a immutable object around without having to worry the contents will ever change.

    Hope this helps.

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