flux icon indicating copy to clipboard operation
flux copied to clipboard

Proposal: Classes as identifiers

Open L8D opened this issue 11 years ago • 13 comments

Taking inspiration from the mindset of Angular's di.js 2.0 library, I think there's a better way to handle actions and callback handlers. For the time being I'm probably going to create a spinoff library of Flux using these idioms.

Classes (or really, their prototypes) are used as identifiers for the types of actions. Instead of using string constants and raw objects for payloads (and additional 'ActionCreators'), you would create a class for each action type which can store the payload on initialization, be used to identify the type and loses the need for helper functions (which could be put in the class anyways).

For example, instead of having code that looks like this:

// constants.js
var constants = module.exports = keyMirror({
  TODO_CREATE: null,
  TODO_UPDATE_TEXT: null,
  TODO_DESTROY: null,
  // ...
};

// actions.js
var TodoActions = module.exports = {
  create: function(text) {
    AppDispatcher.dispatch({
      actionType: TodoConstants.TODO_CREATE,
      text: text
    });
  },

  updateText: function(id, text) {
    AppDispatcher.dispatch({
      actionType: TodoConstants.TODO_UPDATE_TEXT,
      id: id,
      text: text
    });
  },

  destroy: function(id) {
    AppDispatcher.dispatch({
      actionType: TodoConstants.TODO_DESTROY,
      id: id
    });
  }
};

// some-where-else.js

TodoActions.create('Do something');

You could write it like so:

// actions.js
function CreateTodo(text) {
  this.text = text;
}

function UpdateTodoText(id, text) {
  this.id = id;
  this.text = text;
}

function DestroyTodo(id) {
  this.id = id;
}

// ...

module.exports = {
  CreateTodo: CreateTodo,
  UpdateTodoText: UpdateTodoText,
  DestroyTodo: DestroyTodo,
  // ...
};

// some-where-else.js

AppDispatcher.dispatch(new CreateTodo('Do something'));
// alternatively
AppDispatcher.dispatch(CreateTodo, 'Do something');

Using classes not only cleans up the code and avoids duplication, but it means your payloads have classes where you can define helper methods and further avoid duplication in your stores.

In your stores, if you want to listen for an action, you import the class for that action, and simply use an instanceof check on the payload (which could be abstracted away in Fluxxor or what-have-you). With this, you can even create action hierarchies by having actions inherit from a base class for the domain of the action.

~~In addition to that, it'd be nice to use store classes directly (instead of strings) to identify them in waitFor calls. This would require a bit of prototype magic and having extra parameters to track where a callback came from (which would be handled by fluxxor or what-have-you), but is certainly do-able, and puts us that much further away from magic strings (and keeps things more consistent with how actions would be handled).~~

L8D avatar May 09 '15 18:05 L8D

:+1: @L8D why closed?

sompylasar avatar May 10 '15 01:05 sompylasar

@sompylasar due to Flux's flexibility, you can easily do this yourself with minimal effort. All it needs is the use of a 3rd party library that abstracts the instanceof checks and waitFor calls. It's only a pattern, not really something that needs to be changed in Flux's code.

The only magic this would introduce (which can still be hidden away and implemented in a 3rd party library) is the shorthand for dispatching payloads (exa. dispatch(CreateTodo, foo) instead of dispatch(new CreateTodo(foo))).

L8D avatar May 10 '15 08:05 L8D

@L8D Flus itself is an (architectural) pattern, there are many implementations ("Flux codes"), e.g. I use https://github.com/optimizely/nuclear-js . But there are many docs and articles that describe the pattern that encourage using string constants. I thought this proposal targets these guidelines.

sompylasar avatar May 10 '15 14:05 sompylasar

These are interesting ideas, but I'm wondering how much of a problem the use of strings in the constants or dispatch tokens actually is.

In what way does the use of strings actually limit or complicate Flux? What do we gain by moving away from them? On May 9, 2015 1:26 PM, "Tenor Biel" [email protected] wrote:

Taking inspiration from the mindset of Angular's di.js 2.0 library, I think there's a better way to handle actions and callback handlers. For the time being I'm probably going to create a spinoff library of Flux using these idioms.

Classes (or really, their prototypes) are used as identifiers for the types of actions. Instead of using string constants and raw objects for payloads (and additional 'ActionCreators'), you would create a class for each action type which can store the payload on initialization, be used to identify the type and loses the need for helper functions (which could be put in the class anyways).

For example, instead of having code that looks like this:

// constants.jsvar constants = module.exports = keyMirror({ TODO_CREATE: null, TODO_UPDATE_TEXT: null, TODO_DESTROY: null, // ... }; // actions.jsvar TodoActions = module.exports = { create: function(text) { AppDispatcher.dispatch({ actionType: TodoConstants.TODO_CREATE, text: text }); },

updateText: function(id, text) { AppDispatcher.dispatch({ actionType: TodoConstants.TODO_UPDATE_TEXT, id: id, text: text }); },

destroy: function(id) { AppDispatcher.dispatch({ actionType: TodoConstants.TODO_DESTROY, id: id }); } };

You could write it like so:

// actions.jsfunction CreateTodo(text) { this.text = text; } function UpdateTodoText(id, text) { this.id = id; this.text = text; } function DestroyTodo(id) { this.id = id; } // ... module.exports = { CreateTodo: CreateTodo, UpdateTodoText: UpdateTodoText, DestroyTodo: DestroyTodo, // ... };

Using classes not only cleans up the code and avoids duplication, but it means your payloads have classes where you can define helper methods and further avoid duplication in your stores.

With this style, dispatching an action would either look like dispatcher.dispatch(new CreateTodo('Do something')) or dispatcher.dispatch(CreateTodo, 'Do something'). Both could be supported.

In your stores, if you want to listen for an action, you import the class for that action, and simply use an instanceof check on the payload (which could be abstracted away in Fluxxor or what-have-you). With this, you can even create action hierarchies by having actions inherit from a base class for the domain of the action.

In addition to that, it'd be nice to use store classes directly (instead of strings) to identify them in waitFor calls. This would require a bit of prototype magic and having extra parameters to track where a callback came from (which would be handled by fluxxor or what-have-you), but is certainly do-able, and puts us that much further away from magic strings (and keeps things more consistent with how actions would be handled).

— Reply to this email directly or view it on GitHub https://github.com/facebook/flux/issues/203.

fisherwebdev avatar May 10 '15 22:05 fisherwebdev

Constant values are a little messier and end up making you write helper functions. Classes would put both the identifier/token logic and construction-helping logic in one place, removing the need for an external 'ActionCreators' module. Classes allow you to add methods onto your payloads, and integrate way better with a type system. Classes also give you the ability to organize actions into separate domains through inheritance.

In general, this means you no longer are restricted to a system-wide or dispatcher-wide set of possible actions. With this approach, there would be no namespace collisions or need for a monolithic token set, allowing actions to be far more cohesive.

L8D avatar May 11 '15 00:05 L8D

Better integration with type checking is a pretty compelling argument, but I'm not sure I see the others. I just haven't seen or heard of anyone having an actual problem with the action types as strings, once they are made into constants. But I would really like to look at an example implementation to see the real value of doing this.

With the dispatcher, the dispatch token (that is, the id of the registrant) allows us the flexibility of registering anything, not just stores, and I think it would be good to preserve this degree of flexibility. At FB, I know the dispatcher has been used at least once outside of a Flux architecture, so it can be a very generic tool.

fisherwebdev avatar May 11 '15 16:05 fisherwebdev

The strings aren't actually made into constants. They are made into properties of some object, so they are not type-checked by the compiler (objects are allowed to have or not have any set of properties). You could easily make an unnoticeable typo (and get an undefined instead of the string value), or have a clash in naming in a large code base (and get an undesired behavior via the global dispatcher).

The implementation of reference-based (versus string-based) actions: https://github.com/goatslacker/alt (they use functions as factory methods, not as type/class constructors).

class TodoActions {
  updateTodo(id, text) {
    this.dispatch({ id, text });
  }
}
// ...
    this.bindListeners({
      updateTodo: TodoActions.updateTodo
    });
// ...

I have no objections over the dispatch token being an identifier (we've already got these setTimeout's to cope with), though I'd rather have a function to unregister the handler as the return value (because the identifier loses its meaning when the JavaScript context reloads, so there is no point in it being a serializable value-type, not a transient reference-type, except for debugging and error reporting).

sompylasar avatar May 11 '15 17:05 sompylasar

We're experimenting with actions as classes in some of our Flux stores at Facebook. I really want to be able to get strong typing through the dispatcher and this seems like one of the best ways.

kyldvs avatar May 11 '15 18:05 kyldvs

@kyldvs @fisherwebdev Great, then let's reopen this proposal? @kyldvs Is there anything you've come up with in your experiments?

sompylasar avatar May 11 '15 19:05 sompylasar

@fisherwebdev ignore the part about using store classes as identifiers. That part can and should be done in the 3rd party framework.

L8D avatar May 12 '15 04:05 L8D

We're still looking into this, and it will probably be a little while before we see how this idea actually pans out in some of our applications. Personally, I would prefer to be publishing things here that Facebook is actively using and that FB engineers stand behind as proven ideas.

But I want to reopen this issue so that it stays on our radar, and we will provide updates here as things progress.

We will be publishing some base store classes very soon, and will provide overridable methods that will allow the actions-as-classes idea to work. Kyle and I will include documentation about that here in this thread, and possibly on the website if it seems appropriate.

I very much doubt that we will be modifying the dispatcher to support class identifiers for the registrants, however.

fisherwebdev avatar May 12 '15 16:05 fisherwebdev

With #243 we have now shifted away from classes to using a disjoint union for actions. Flow is able to refine a disjoint union within a switch based on a type field: http://flowtype.org/blog/2015/07/03/Disjoint-Unions.html

This makes defining actions very clean, you define the type once in the disjoint union, and then nowhere else. No need for action creators, you can safely dispatch directly (assuming you're using flow) without worrying about messing up the shape of the action. (you can still use action creators if you prefer though)

kyldvs avatar Jul 28 '15 06:07 kyldvs

Closing this out, we recommend #243 rather than actions as classes. Here is a full example: https://github.com/facebook/flux/blob/master/examples/flux-utils-todomvc/js/flux-infra/TodoStore.js

kyldvs avatar Aug 17 '15 22:08 kyldvs