Parkour-Labs / dust

State management all-in-one: reactivity, persistence and synchronisation.
Apache License 2.0
2 stars 0 forks source link

Implement `generateForwarding` for @Model. #6

Open wxxedu opened 5 months ago

wxxedu commented 5 months ago

Motivation

This has been a debate between me and @bridgekat, regarding whether we should automatically generate easy forwarding getters and setters for the fields. This has been a new issue raised by #5, as that enabled us to generate such redirections. Suppose given the following code:

@Model()
class Todo with _$Todo {
    Todo._();

    factory Todo({required String name}) = _Todo;
}

Without Redirections

mixin _$Todo {
    Atom<String> get name$;
}

Redirections

mixin _$Todo {
    Atom<String> get name$;

    @pragma("vm:prefer-inline")
    String get name => name$.get(null);

    @pragma("vm:prefer-inline")
    set name(String value) => name$.set(value);
}

The benefit of having redirections is that it allows much simpler code when observability is not required:

// without redirection
final name = todo.name$.get(null);
todo.name.set("New Name");

// with redirection
final name = todo.name;
todo.name = "New Name";

However, since the Observer of the get method, despite being nullable, is required, it would remind the user to subscribe to an observer whenever possible. This would potentially reduce the amount of developer errors in the frontend.

Solution

Add a boolean flag called generateForwarding to the code generator. By default, this flag is set to false. You can turn it on if you want more convenience.

wxxedu commented 5 months ago

The field has been added to code in the branch, but nothing has been implemented yet.

wxxedu commented 5 months ago

Maybe we should remove this field and only generate the convenience setters.