What is immutability and why should I worry about it?

前端 未结 15 1081
无人共我
无人共我 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:53

    Look, I haven't read the links that you have posted.

    However, here is my understanding.
    Every program holds some knowledge of it's data (State), which can change either by user-input/external changes etc.

    Variables (values which change) are kept to maintain state. Immutable means some data which doesn't change. You can say, it is same as readonly or constant in some way (it can be seen it that way).

    AFAIK, functional programming has things immutable (i.e. you cannot use assignment to a variable holding the value. What you can do is create another variable which can hold the original value + changes).

    .net has string class which is an example.
    i.e. You can't modify string in its place

    string s = "hello"; I can write s.Replace("el", "a"); But this won't modify the contents of variable s.

    What I can do is s = s.Replace("el","a");
    This will create a new variable & assign its value to s (overwriting content of s).

    Experts can correct mistakes if I have, in my understanding.

    EDIT: Immutable = Unassignable once it is holding some value & can't be replaced in place (maybe?)

提交回复
热议问题