redux initial state as first parameter is a bad practice

Viewed 1351

In redux the initial state is provided by using a default parameter for the first argument state, while the second argument action does not have a default. However, I consider this a code smell (and so do others such as Airbnb guidelines) since you always need to provide the first argument (and then would use undefined to get the default which is cumbersome). I totally understand why you would want to provide that initial state, but why do they not switch the arguments so the default is 2nd to bring code in compliance with common guidelines?

// bad
function someReducer(state = 0, action) {
  switch (action.type) {
  default: return state;
}

// good
function someReducer(action, state = 0) {
  switch (action.type) {
  default: return state;
}

redux forces our developers to use a bad practice which encourages them to do it in other places. Why would redux-developers still decide for such architecture?

UPDATE

The reason, why it is a bad practice to have defaults going first comes from language design itself. In JS the interpreter cannot tell what the intention of the developer was. As an example:

const giveMe = (goodHuman = true, candy) => (goodHuman && candy) ? 'candy' : 'tea';

So, will I get candy?

giveMe(true) // not clear! (but it is 'tea')

I cannot access the candy with a single parameter! But I guess the developer would have liked me to get some, right? However, candy is always undefined making the conditional expression evaluate to undefined. As a fallback the else-part is executed. It is not a clear intention and hard to guess what the developer wanted to express. Such code would not come through our review-process / QA.

So, in the following example, the developer made sure that we can access that candy if we want it and he beliefs that we by default are good humans who should get that candy.:

candy giveMe = (candy, goodHuman = true) => (goodHuman && candy) ? 'candy' : 'tea';
giveMe(true) // finally we get the candy!

Since people say that putting the default in front is a best practice with redux, I would consequently argue that redux has a bad design on the reducers' signature! It might origin from the fact that reducer-functions in general have a similar signature, but they do not make the first argument optional which would not make any sense! It argue that it is a bad design decision of redux to make it a "best practice" calling a function using undefined.

1 Answers
Related