you-dont-need / You-Dont-Need-Loops

Avoid The One-off Problem, Infinite Loops, Statefulness and Hidden intent.
1.08k stars 53 forks source link

Question about statefullness #4

Closed halfzebra closed 4 years ago

halfzebra commented 4 years ago

Hi Steve!

Thanks for the write-up, I like it very much and it's very relevant! 👍

What confuses me is the promise of having no statefulness in recursive implementations. I probably don't know what I'm talking about, but as far as I understand there's an option to have a state in functions that allow collection traversal by leveraging recursion.

function statefulTraverse(list, state) {
  // Sorry for the naive example,
  // just trying to come up with some illustration
  return statefulTraverse(list, nextState)
}

In JavaScript or other languages allowing access by a reference, recursive functions can even share mutable state.

[ 1, 2, 3 ].reduce((acc, curr) => {
  performSomeMutationsOnNestedState(acc.someOtherState)
  acc.counter += curr
  return acc
  },
  {
    counter: 0,
    someOtherState: { /* some object */ }
  }
)

I completely understand, that this example might look contrived, but I've seen this happening in my personal professional experience a few times. Deep cloning might solve the issue, but it gets less efficient as the object gets more nested stuff to the point where it's tempting to mutate it.

That's why I feel like raising awareness of the fact that using recursion does not guarantee the absence of the mutable state in JavaScript.

What do you think?

stevemao commented 4 years ago

You must not mutate a variable.


I think this article needs to add a prerequisite section to explain things like side effects and immutabilities, etc.

halfzebra commented 4 years ago

Thanks for the reply, I think adding the prerequisite makes perfect sense! :+1:

stevemao commented 4 years ago

@halfzebra please check the updated readme and let me know if it's not clear :)

halfzebra commented 4 years ago

Looks good to me! Thanks for adding the prerequisites! 👍