Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating only selected fields of immutable #21

Closed
Cretezy opened this issue Mar 8, 2018 · 8 comments
Closed

Updating only selected fields of immutable #21

Cretezy opened this issue Mar 8, 2018 · 8 comments

Comments

@Cretezy
Copy link

Cretezy commented Mar 8, 2018

Coming from the JavaScript world, seeing something like this in a reducer is common:

return {
    ...state,
    foo: "bar"
};

This is basically creating a new object, but replacing (not setting) the foo field, making it "immutable" (doesn't change the original, just creates a new with the updated field). This is usually compiled down to use Object.assign when using Babel.

In Dart and redux.dart, when making a new state, I found no way to "copy" the old object and replace a value. The only way I found was to fully recreate the object, reassigning all the fields from the old. This quickly becomes a problem when scaling, because if you creating a new field, you must check and add every single reducer branch. By failing to do so, you'll have an empty property when running that branch/action.

Is there any solution for this problem?

@Cretezy
Copy link
Author

Cretezy commented Mar 8, 2018

The best solution (which I think could be considered right/correct) is to use an intermediary class for mutations. Like so:

class AppState {
  final int counter;
  final String name;

  AppState({this.counter = 0, this.name = "John"});
}

class AppStateBuilder {
  int counter;
  String name;

  AppStateBuilder({this.counter, this.name});

  AppStateBuilder.fromAppState(AppState state) {
    counter = state.counter;
    name = state.name;
  }

  AppState toAppState() {
    return new AppState(counter: counter, name: name);
  }
}

class IncrementCounterAction {}

class SetNameAction {
  final String name;

  SetNameAction(this.name);
}

AppState counterReducer(state, action) {
  var builder = new AppStateBuilder.fromAppState(state);

  switch (action.runtimeType){
    case IncrementCounterAction:
      builder.counter++;
      return builder.toAppState();
    case SetNameAction:
      builder.name = action.name;
      return builder.toAppState();
    default:
      // No change
      return state;
  }
}

Basically it creates a mutable object (the builder) from the immutable one, does the mutation needed, then creates a new immutable object for the store.

@Cretezy Cretezy changed the title Object.assign in Dart Updating only selected fields of immutable Mar 8, 2018
@brianegan
Copy link
Collaborator

brianegan commented Mar 8, 2018

Hey @Cretezy! There are a couple patterns I've used to solve this problem.

1. Future Dream

I really hope Dart supports data classes or case classes in the Future! This would give us the ability to write something like state.copy(user: new User). It would return a new copy of the object updating the parts you've provided.

2. copyWith method

Since we don't have that baked in, you can write your own copyWith method! It will take only the params you provide it, and default back to the old values if you don't.

https://github.com/brianegan/flutter_architecture_samples/blob/master/example/redux/lib/models/app_state.dart#L23

3. built_value

You can generate all of the copyWith code using a package called built_value. https://pub.dartlang.org/packages/built_value

(built_value will generate a method called rebuild that does the same thing as copyWith).

How do these options work for ya?

@Cretezy
Copy link
Author

Cretezy commented Mar 8, 2018

The copyWith method is very clean! It's basically a simpler version of my solution, I like it very much, and avoids code generation. I hadn't thought about using it that way. Thank you very much!

@brianegan
Copy link
Collaborator

Cool, I'll close this issue for now! Let us know if you run into anything else :)

@Cretezy
Copy link
Author

Cretezy commented Mar 8, 2018

Just as a final remark, this is what I've ended up with as a result, very clean!

class AppState {
  final int counter;
  final String name;

  AppState({this.counter = 0, this.name = "John"});

  AppState copyWith({counter, name}) {
    return new AppState(
        counter: counter ?? this.counter,
        name: name ?? this.name
    );
  }
}

class IncrementCounterAction {}

class SetNameAction {
  final String name;

  SetNameAction(this.name);
}

AppState counterReducer(state, action) {
  switch (action.runtimeType) {
    case IncrementCounterAction:
      return state.copyWith(counter: state.counter + 1);
    case SetNameAction:
      return state.copyWith(name: action.name);
    default:
      // No change
      return state;
  }
}

The only small problem is you can't set a value to null using this solution. You'd need to set it to an empty object ("", 0), to "reset".

@santervo
Copy link

I used Symbol.empty as placeholder for "not defined" value, allowing to set value to null also.

For example:

class AppState {
  final int counter;
  final String name;

  AppState({this.counter = 0, this.name = "John"});

  AppState copyWith({counter = Symbol.empty, name = Symbol.empty}) {
    return new AppState(
        counter: counter != Symbol.empty ? counter : this.counter,
        name: name != Symbol.empty ? name : this.name,
    );
  }
}

@afnx
Copy link

afnx commented Apr 18, 2020

This could be helpful if you want to update without giving all parameters:

class AppState {
  final int counter;
  final String name;

  AppState({this.counter = 0, this.name = "John"});

  AppState.rebuild(AppState state, {int counter, String name}) 
          : counter = counter ?? state.counter,
            name = name ?? state.name;
}
var updatedState = new AppState.rebuild(state, counter: 1);

@iakbar
Copy link

iakbar commented Jun 1, 2020

A clean way to set a value to null in the copyWith() method is to use an Optional.

class Optional<T> {
  T value;

  Optional(this.value);
}

class AppState {
  final int counter;
  final String name;

  AppState({this.counter = 0, this.name = "John"});

  AppState copyWith({Optional<int> counter, Optional<String> name}) {
    return new AppState(
      counter: (counter == null) ? this.counter : counter.value,
      name: (name == null) ? this.name : name.value,
    );
  }
}

class IncrementCounterAction {}

class SetNameAction {
  final String name;

  SetNameAction(this.name);
}

AppState counterReducer(state, action) {
  switch (action.runtimeType) {
    case IncrementCounterAction:
      return state.copyWith(counter: Optional<int>(state.counter + 1));
    case SetNameAction:
      return state.copyWith(name: Optional<String>(action.name));
    default:
      // No change
      return state;
  }
}

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

No branches or pull requests

5 participants