4 ms·
Is the (pseudo?) code there for state mutation representative of a widely used pattern? It looks like using a pattern from a functional programming book, but a
by alkonaut 9y ago
Is the (pseudo?) code there for state mutation representative of a widely used pattern?
It looks like using a pattern from a functional programming book, but applied to mutable data. What I mean is this snippet:
function handleAddTodo(state) {
if (!newTodoField) {
state.error = 'Empty field!'
}
state.todos.push(state.newTodoField)
state.newTodoField = nil
return state;
}
This looks like a function newState = fun(oldState) but there is one huge problem: the new state is the same data as the old state? In a Rust-like type system this might be OK because you couldn't accidentally keep using the original state after sending it to this method, and in an immutable scenario there would be no problem because you created a new state instead of mutating. But this looks exactly like mutating the argument sent to a function.
So out of curiosity, do any modern UI frameworks in JS (this looks like that type of code) do this, or was it just an unfortunate example?
- 1_player 9y agoVuex works like this: you actually mutate the state instead of creating a new one as it's expected with Redux. But this mutation takes place is a single, controlled place (in the store mutation functions), so you get the benefit of centralising the state management code and avoid the cumbersome immutable transformations patterns which Redux requires. That said, after having worked with Vuex, I much prefer the immutable newState = f(oldState) pattern used with Redux.
- nevon 9y agoThat's an unfortunate example. What you described as `newState = func(oldState)` is (conceptually) how practically all of this generation's state management libraries are modelled.
- l_pan_ 9y agoThis is not an unfortunate example. With the absence of persistent data structures it is inefficient or difficult to write the state transition functions as pure functions.