Development Concepts: What is Immutability?
What is Immutability?
One of the concepts that is popular (and for good reason) is understanding and using immutability with your structures. There a few languages that enforce that (mostly functional programming) but most of the time you have the freedom to manipulate your structures however you want.
The idea of immutability is simple but seems complex. It is the concept of forcing you to create a copy of any structure you are using instead of manipulating the current one you are accessing.
The reason for this is actually very useful. In the case of our example in the image above, our variables are actually given a location in memory and any function that uses that variable and modifies it could cause you to get wrong data or unstable data. If two functions can manipulate the same data then there is no guarantee that you will get what you expect in either case. It makes it complicated to produce consistent results and track down bugs.
A function that manipulates data outside of itself can be problematic like we talked about above. Most of the time when you talk about immutability it goes hand in hand with pure functions. These are functions that do not change anything outside of themselves. If you pass in a parameter it will not mutate it and instead with perform an operation and return a new structure leaving the original one the same.
In the example above you can see two examples of methods on arrays that perform operations differently. You can see that
push will simply mutate the array and add something to it. So if you had a function that expected
watchMeGetMutated to have a length of 2 and then sometimes another function that performs this
push operation on it executes before it and sometimes after it then you have no guarantee that it will return the value or perform the operations that you need. This can cause random difficult bugs.
The array method
concat on the other hand does not mutate the array. As you can see the array
watchMeStayTheSame does not change. All that
concat does is take the array and return a copy with the new values added. So it keeps it pure. You could have multiple pure functions using
watchMeStayTheSame in various times and they will always work the same. You could use
watchMeStayTheSame thirty different times and any functions using that array would not be impacted.
You can see in the image below that when I assign the value from
newArray that we get the copy that is made:
Using immutability is something you need to be mindful of and it is a key component of the Flux pattern which is used by Redux.
Sidenote: quokkaJS is the cool addon that is allowing for real time logging in the editor.