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

Avoid The One-off Problem, Infinite Loops, Statefulness and Hidden intent.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question about statefullness

halfzebra opened this issue Β· comments

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?

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.

Thanks for the reply, I think adding the prerequisite makes perfect sense! πŸ‘

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

Looks good to me! Thanks for adding the prerequisites! πŸ‘