Let’s say we are writing a reducer that holds an object of users. Let’s say one user follows another one in state and we want to mutate both of these users in our reducer. Moreover, we want some additional data to be passed to these objects.
How the traditional way looks like?
Yes, this could be refactored a bit, instead of overusing ES6 destructuring, we could use Object.assign or something else. Or we could try introducing some functions like
followUser, but anyway we are dealing with a creation and mutation of an object at the same time and I haven’t seen it looking nice with more complex scenarios.
BUT, what if we tried to split the reducer state object mutation into little functions and then be able to do the mutations line by line? Let’s say we had a little helper that mutates a field:
And then a function which constructs a functional abstraction that would hold the state and implement some methods used in FP (functional programming) world:
Then, we could write our reducer so that it mutates the object line by line, that you can chain:
Pros: when editing a single line, you don’t have to care about the whole object; you can introduce more helper functions for mutation and then reuse them among many reducers instead of writing many single responsibility functions like
followUser and similar.
Cons: it might be harder for your team mates to grasp this, if they are not very much into FP.
Let me know your thoughts!