Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Flux architecture examples use constants for action types instead of strings?

Throughout the examples and explanations of Flux architecture -- Facebook's counterpart to React -- action type names are referenced as enum constants rather than strings. (See examples at http://facebook.github.io/flux/) I am just looking for an articulation of why this is the preferred method.

I do not see a benefit in terms of authoring & convenience, because whether you type constants.actionTypes.UPDATE_DATA (enum constant) or 'UPDATE_DATA' (string), you have to know and type out the exact name. In fact, sometimes the use of non-strings adds complexity -- e.g. you can't as easily make an object with action types as keys and action handlers as values.

Are the benefits in organization, minification, or something else? I'm curious.

like image 321
davidtheclark Avatar asked Nov 24 '14 16:11

davidtheclark


1 Answers

You touched on it at the end of your question, but there are a couple benefits. Minification is an obvious one; another is the fact that static analysis tools can more easily find usages and catch errors.

Depending on your flux implementation, they can also help you catch typos. For example, in Fluxxor, if you try to bind a store handler to an action type of undefined, you'll get an exception; that means that passing c.UPDATE_DTA will throw, but passing 'UPDATE_DTA' will not.

Finally, they can help serve as documentation. If all the action types that your application generates are defined centrally as constants, it becomes easier to tell at-a-glance what kinds of operations the system as a whole responds to.

There's an ES6 feature that is available with Babel or Traceur (but not with the JSX transform at this time) that helps create object literals; the syntax is:

var handlers = {
  [const.UPDATE_DATA]: this.handleUpdateData,
  [const.OTHER_THING]: this.handleOtherThing
};
like image 95
Michelle Tilley Avatar answered Oct 17 '22 07:10

Michelle Tilley