Skip to content

Add ofClass method to Actions - #160

Closed
karptonite wants to merge 2 commits into
ngrx:masterfrom
karptonite:patch-add-of-class
Closed

karptonite wants to merge 2 commits into
ngrx:masterfrom
karptonite:patch-add-of-class

Conversation

@karptonite

@karptonite karptonite commented Jul 23, 2017 •

Copy link
Copy Markdown
Contributor

This adds an ofClass method to Actions, similar to the ofType method.

It allows you to filter actions that are classes in a type safe way:
$actions.ofClass(MyAction) This is a bit simpler than the current method: $actions.ofType<MyAction>(MY_ACTION_TYPE), and will work well with the toPayloadTyped function proposed in #157.

I should add that, while it seems to work, I'm sort of pushing the limits of my TypeScript understanding here, and I'm not 100% certain this is right. In particular, there may be an issue with the type inference and that spread operator; if that doesn't work right, I'm pretty certain that we could do ofClass with a single class and not have that issue.
In that case, ofClass would instead look like:

ofClass<T extends V>(allowedClass: new () => T): Actions<T> {
  return  action instanceof allowedClass;
  );
}

I'm not sure I can think of many use cases for filtering on multiple classes with ofClass, but if it works, there is no reason not to keep that functionality.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.019% when pulling 7463519 on karptonite:patch-add-of-class into 27cdd36 on ngrx:master.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.03%) to 90.019% when pulling 68d1672 on karptonite:patch-add-of-class into 27cdd36 on ngrx:master.

@karptonite

karptonite commented Jul 23, 2017 •

Copy link
Copy Markdown
Contributor Author

By the way, although this works, it also highlights something about ngrx that I'm not sure I'm entirely comfortable with: the fact that ngrx actions can be class instances, as opposed to just plain objects. I could imagine that being limiting in the future, since it may be harder to pass around class instances than plain objects which can very easily be converted to JSON. It also might tempt users to engage in questionable practices such as adding methods beyond the constructor to their Action classes. Action as a class instance allows us to do things like ofClass in runtime, but I'm not 100% sure it is a good idea in the long run.

An alternative would be to move toward encouraging actions to be exclusively plain JavaScript objects, using interfaces and functional action creators in place of classes with constructors. I believe that could be accomplished with only changes to the example app--as far as I know, nothing in ngrx itself suggest that Actions should be class instances. But adding ofClass works against that. Or I think it does... my understanding of JavaScript classes is somewhat limited.

@kylecordes

Copy link
Copy Markdown

Over here, we have been building systems which assume (and rely on) actions being "just data" - trivially serializable to/from JSON without breaking anything. We had assumed the fact that this wasn't enforced by Store, was for performance and simplicity reasons.

It will be interesting to see whether this PR goes in - that clarify that our assumptions were just plain wrong :-) that that we need to switch to a more complex JS <-> text serialization mechanism.

@karptonite

Copy link
Copy Markdown
Contributor Author

Even if this goes in, it wouldn't prevent you from making actions plain objects. It is an optional convenience function--I can't imagine to would affect your use case. It may have more significant implications for future features that might be added to ngrx, however.

Honestly, it looks like the platform is already going down the route of Action as class instance with the reliance on the readonly type for inference in reducers. I may be mistaken, but I don't think you can accomplish that sort of inference without using class instances. There is a lot of power in using the class instances, but as long as they aren't mandatory, it won't break your use case.

@kylecordes

Copy link
Copy Markdown

@karptonite Its not just about my code though. If changes go in that shift Store away from JSON-able Actions, code written by other people will use it. The things we work on here typically sprawl to involve code written by other people (broad teams, external libraries, etc.). Therefore, whatever Store encourages, my code will need to work with.

It sounds like maybe the ship has sailed - hopefully one of these serialization libraries is sufficiently solid to make it a non-problem, just a bit more bundle size.

@karptonite

Copy link
Copy Markdown
Contributor Author

@kylecordes Yeah, I'd say if you are relying on other teams by default creating actions that are plain objects, not class instances, that ship has sailed, based solely on the fact that the example app uses (and used even in ngrx 2) class instances for actions.

@hccampos

Copy link
Copy Markdown

I am very much against using classes as actions. The type inference can be done with plain data and interfaces. Using classes goes away from functional programming (which is a bad thing) and can give people ideas like adding methods (as mentioned above).

@karptonite

Copy link
Copy Markdown
Contributor Author

@hccampos Using class instances as actions is pretty baked in by now--if you are against that, you are suggesting a significant change to the library. https://github.com/ngrx/platform/blob/master/docs/store/actions.md
I agree that it is problematic if you want to serialize actions, but if you are trying to draw the line at using the classes at all (vs making use of the fact that classes were used for runtime effects), that is going to be a tough sell.

@bfricka

bfricka commented Jul 24, 2017

Copy link
Copy Markdown
Contributor

Using classes goes away from functional programming (which is a bad thing)

No it's not. It's neither good nor bad. Functional programming is particularly good at solving certain sets of problems, and it's weak at solving others. If you want pure functional programming you're not using the correct framework, as Angular is in no way built on functional foundations (even if it does support some functional-related patterns)

@hccampos

Copy link
Copy Markdown

@bfricka Completely agree with that, but it really is a shame. Ngrx is (was?) based on functional principles and is bringing them to Angular. If things move towards OOP, it loses its purpose and you might as well just stick to old and tested patterns like the command pattern.

Regarding the framework choice, well, at the moment we are stuck with Angular (personally I only ever use React/Preact or Elm and had no choice in it), and we are trying to bring as much FP as possible to Angular, leaving nearly only the components as classes. If ngrx moves away from FP principles I guess we can always move back to Redux or pure rxjs.

@edcarroll

edcarroll commented Jul 25, 2017 •

Copy link
Copy Markdown

Your PR gave me a bit of an idea, so I've run with it:

Rather than extend Actions with an ofClass method with limited type inference abilities, why not generalize the concept and make it support actions that aren't actually initialized as classes, while retaining full type support.

The result was class-discriminators, a small library that helps to alleviate these problems.

Essentially, it uses a simple decorator to attach the type of the action to the class constructor, and then lets you filter the action arrays exactly how your PR does:

First, attach the decorator to the action class:

import { DiscriminatorValue } from "@edcarroll/class-discriminators";

@DiscriminatorValue("MY_ACTION")
export class MyAction implements Action {
    public readonly type = "MY_ACTION";

    public exclusiveProperty = "only on MyAction";
}

Next, create a guard factory (explained in the lib) that discriminates based on the type field:

import { configureGuardFactory } from "@edcarroll/class-discriminators";

export const guardActions = configureGuardFactory<Action>("type");

Finally, you can use this to filter actions:

actions$
    .filter(guardActions(MyAction))
    .do(a => console.log(a.exclusiveProperty)); // this compiles and type checks correctly

Note: guardActions in this example is actually variadic, and the output is a union of the provided classes (so you can have guardActions(ActionA, ActionB) which will give you Observable<ActionA | ActionB>.

Another Note: Because the discriminator values are attached to the class constructors, and not the instances, this method works perfectly with actions that aren't instances of your provided action classes, a worry expressed rather a lot in this comment thread (and one I agree with!!)


Please let me know your comments as I'm interested to see what people think of this approach.

@MikeRyanDev

Copy link
Copy Markdown
Member

As discussed in another issue:

Despite using classes for actions everything is serializable today. Classes merely add compile-time type checks and don't impact the ability to serialize them. Bringing this operator into the API promotes classes as a run-time necessity and would break serialization.

Because the ngrx team plans on making use of serialization this year as we focus on universal and offline apps, I don't think this is a change we are willing to make. I suggest packaging this up as a community library.

Thanks though!

@karptonite

Copy link
Copy Markdown
Contributor Author

@MikeRyanDev fair enough. Do your plans that make use of serialization involve having deserialized action actually going through effects? If so, I wouldn't want to make this a community library for ngrx, since I wouldn't want to be responsible for people adopting a feature that breaks future use of ngrx for them.

Either way, I think this calls for a pull request to the docs making the purpose of the Action classes explicit, and discouraging the addition of any methods to them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants