Skip to content

rlpt

Github

Redux state variable naming

redux

Redux reducers can call other reducers, requiring variables to store intermediate steps of state. What should these intermediate state variables be called? I have tried a few different naming styles over the years, and now have settled on a style which I think is very convenient. Skip to the end if you just want the final optimal style, because I'm going to describe the previous styles I tried first.

Style 1: With Lots of Extra Typing

It's 2016. The gorilla is dead. I'm working on my first non-trivial project using redux.

Not sure what inspired this style, but I started to name the intermediate state variables after the last change that happened e.g:

With with with. With is a short word, but still these variable names are quite long. Also the variable name is often similar to the name of the function it gets it's value from, so not adding much useful information. Considering these issues I now rate this style as ok, so so, tepid.

I stuck with this scheme, and variations of it, for a few years. I'm glad I stuck with it for so long, as the next style I tried had a serious flaw.

Style 2: A Sense of Order

Maybe I was motivated to gain some efficiency, or maybe the lead paint in the office was starting to get to me. Either way I started using a new naming style:

Shorter variable names! No thinking required! This must be an improvement, right?

No. This style has a massive flaw: Inserting a new step means you have to rename all the state variables that follow. e.g

Ugh what a waste of time. It's also easy to miss renaming a variable, leading to bugs which can be hard to spot.

This naming style is very suboptimal and should not be used. I feel bad inflicting this on my colleagues, but one of them (hi Steve!) did come up with a more efficient way of inserting a new step, which I spotted during a code review:

2a?! Initial horror quickly turned into admiration. They had found a simple solution to the renaming problem. Like turning a single house into two flats, it can be done with only a small inconvenience to the neighbours.

Final Form: Be Divine, Rebind

The redux immutability rules only apply to values. Variable names are irrelevant when checking an object for changes. This means we can declare a variable using let and reuse that variable for our intermediate state steps e.g

No thinking about variables names! No mass renaming when inserting a new step!

This superficially looks like we are breaking redux immutability rules, but we can check it's ok using a test:

Convenience achieved.