toddmotto / ama

Ask me anything!
20 stars 3 forks source link

why/how should we prefer immutable behaviours in Angular2+? #72

Open chrisrudman opened 7 years ago

chrisrudman commented 7 years ago

Hi Todd,

I spent most of yesterday going through your Angular 2 course - I'm enjoying it. I had a basic understanding from Ionic already, but this is filling in many gaps I didn't know I had! You mentioned several times it's best to change your data in an immutable fashion, without really saying why, except that it's better for change detection. Perhaps that's something that will come in the advanced course, but in the mean time I'm after a bit of clarification.

In one example you filtered an array of objects instead of splicing it... so we get an entirely new array object, even though it's referencing the same objects within it. I can see why this is preferable because Angular is watching the array variable itself (not the objects within it) so replacing it means it's obviously been changed. But what if we want to change the data inside the objects instead of the structure of the array itself? How deep does the immutability have to go for Angular to benefit? An example:

Say I have a button that should increment the 'age' property of each 'Person' object in the array. I could: a) Create a new array, which references new copies of each person object - using Object.assign() - with the 'age' properties updated. Therefore we are completely immutable... none of the original objects have changed. b) Create a new array that references the same objects, each of which has been updated directly. Here the array isn't mutated, but the data referenced by it is.

Option a) is the ideal, but is it necessary? In my mind, option b) will still be friendly to Angular as the class variable being watched is still updated to point to a new array object.

Similarly, if I want to update just one of the objects in the array, should I create a new array which references the same objects except the one to be updated, which is a new object from Object.assign() with the updates applied? This is totally immutable, but is more complex code, so I'm wondering if it's really that beneficial.

And what about Immutable.js? Do you think it's a good idea to just ingrain these List/Set/Etc objects into my coding, instead of javascript arrays, to ensure immutability from the start?

hope that makes sense,

Thanks

Chris

blowsie commented 7 years ago

Simialr to https://github.com/toddmotto/ama/issues/50