brianegan / flutter_architecture_samples

TodoMVC for Flutter
http://fluttersamples.com/
BSD 3-Clause "New" or "Revised" License
8.74k stars 1.71k forks source link

Thoughts on builder pattern in redux reducers? #180

Closed elvisun closed 4 years ago

elvisun commented 4 years ago

Say I have a state with 4 properties a,b,c,d, in the reducer if I want to alter one property, I would need to do:

  TypedReducer<SomeState, SomeAction>(
    (state, action) {
      return SomeState(
          a: state.a, 
          b: action.b,
          c: state.c,
          d: state.d,
      );
    },
  ),

If we use a builder pattern for our SomeState, this can be simplified:

  TypedReducer<SomeState, SomeAction>(
    (state, action) {
      return SomeState.toBuilder()..setB(action.b).build();
    },
  ),

This way any future changes to SomeState doesn't require update to every reducer.

Thoughts on this? Also I wonder what's the best way to avoid manually writing a builder class for SomeState? it's a lot of boilerplates to write.

brianegan commented 4 years ago

Hey there -- this is definitely a common question! The default way to do it without any libraries: Add a copyWith method to the SomeState class that copies the class and only modifies what's been changed.

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

There are some popular libraries that use code generation to generate this kind of copy function / a builder for ya:

Hope that helps!

elvisun commented 4 years ago

Thanks Brian! This is super neat! 👍