Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Created May 13, 2023 08:31
Show Gist options
  • Save MelbourneDeveloper/3cea24edc6cbf5904b90e66c7e2ace97 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/3cea24edc6cbf5904b90e66c7e2ace97 to your computer and use it in GitHub Desktop.
Bloc Style Functions
//Programming is too easy. What if we wrote functions like this?
//Instead of just calling the function, we create types to bundle
//up the arguments and then pass the type to the function that accepts
//a generic type.
//
//This is the essence of the Bloc pattern.
class AdditionArguments {
final num a;
final num b;
AdditionArguments(this.a, this.b);
}
num calculateBlocStyle<T>(T event) {
if (event is AdditionArguments) {
return event.a + event.b;
}
throw Exception('I dont know anything about this event');
}
/// Or, we could just do this...
num calculate(num a, num b) => a + b;
//And this doesn't even take into account attaching
//and detaching streams...
//Obviously Bloc style is way more verbose, makes the code harder to read,
//introduces extra code paths that you need to handle, which makes it
//more error prone, is generally clunky, and basically defies the whole
//point of functions. But hey, it unifies our code right?
void main() {
print('Hello world: ${calculateBlocStyle(AdditionArguments(1, 1))}!');
print('Hello world: ${calculate(1, 1)}!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment