Home:ALL Converter>BLoC pattern best practice - is it legit to store data in the BLoC class?

BLoC pattern best practice - is it legit to store data in the BLoC class?

Ask Time:2020-05-11T14:16:23         Author:Avi

Json Formatter

I am new to Flutter and the BLoC design pattern. However, the concept of BLoC looks pretty straightforward and I think I understand it pretty well.

Occasionally, when reviewing my coworkers' code, I see that when implementing a BLoC, they tend to store data inside the BLoC class. I believe this is wrong, and that the data belongs in the state class. If it needs to be passed around or stored somewhere until the state can be created, it should be stored in the event instance that triggers the change, not the BLoC itself.

My understanding is that the BLoC class is a state machine whose sole purpose is to map events to states and have no other state besides the defined "state" class. This is separation of concerns - the event class(es) should store the data triggering the change, the state class(es) should store the data after the change, and the BLoC should handle the operations manipulating that data and mapping it from event to state.

If you store data inside the BLoC class, the state machine changes its functionality from (event, state0) => state1 to (event, state0, blocData) => state1. It's clear that if you want to unit-test your BLoC, the complexity of your tests increases, because you will need to test |event| X |state| X |blocData| cases instead of |event| X |state| cases (meaning cartesian multiplication of number of possible values for each type). One can claim that it doesn't really affect the number of possible values, because we would just move blocData to state. However, my claim is that if you encapsulate the data together, you will usually find that they are dependent and some combinations are irrelevant, but you can maintain this dependency only when encapsulating them together, or at least protect it from breaking only when encapsulating together.

Another reason is that your application code that sees a state and sends an event, may potentially produce indeterministic results. This is because the BLoC instance has a "dirty" state that has an effect on its functionality.

I'd like to hear opinions from developers that have some more experience in this design pattern. If you can post some references to articles on this issue, that'd be great too. I didn't find anything specific about this issue.

Author:Avi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61723394/bloc-pattern-best-practice-is-it-legit-to-store-data-in-the-bloc-class
yy