Created
August 8, 2024 15:51
-
-
Save eseidel/06f35154903c5a2628f2ba97dc72be94 to your computer and use it in GitHub Desktop.
Testing behavior of switch and async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Stubs for package:http. | |
enum HttpMethod { | |
GET, | |
POST, | |
PATCH, | |
} | |
class HttpStatus { | |
static const int ok = 200; | |
static const int methodNotAllowed = 405; | |
} | |
Future<Response> doGetAsync() async { | |
return Response(statusCode: HttpStatus.ok); | |
} | |
Future<Response> doPostAsync() async { | |
return Response(statusCode: HttpStatus.ok); | |
} | |
class Response { | |
final int statusCode; | |
Response({required this.statusCode}); | |
} | |
// Original code before refacotoring to switch. | |
// Note how some paths return a future, some return a value | |
// (which dart implicitly wraps as a future). | |
Future<Response> respondIf(HttpMethod method) async { | |
if (method == HttpMethod.GET) { | |
return doGetAsync(); | |
} | |
if (method == HttpMethod.POST) { | |
return doPostAsync(); | |
} | |
return Response(statusCode: HttpStatus.methodNotAllowed); | |
} | |
// Refactor to use switch. | |
// This broke in our larger codebase... | |
Future<Response> respondSwitch(HttpMethod method) async { | |
return switch (method) { | |
HttpMethod.GET => doGetAsync(), | |
HttpMethod.POST => doPostAsync(), | |
// Don't I have to wrap it in a Future.value?!? | |
_ => Response(statusCode: HttpStatus.methodNotAllowed) | |
}; | |
} | |
// How we had to do this in our larger codebase otherwise | |
// analyzer complained: | |
// "A value of type 'Object' cannot be returned from the | |
// function 'onRequest' because it has a return type of of | |
// Future<Response>. | |
Future<Response> respondSwitchFuture(HttpMethod method) async { | |
return switch (method) { | |
HttpMethod.GET => doGetAsync(), | |
HttpMethod.POST => doPostAsync(), | |
_ => Future.value(Response(statusCode: HttpStatus.methodNotAllowed)) | |
}; | |
} | |
// Another way we could have done it. | |
Future<Response> respondSwitchAwait(HttpMethod method) async { | |
return switch (method) { | |
HttpMethod.GET => await doGetAsync(), | |
HttpMethod.POST => await doPostAsync(), | |
_ => Response(statusCode: HttpStatus.methodNotAllowed) | |
}; | |
} | |
void main() async { | |
await respondIf(HttpMethod.GET); | |
await respondSwitch(HttpMethod.GET); | |
await respondSwitchFuture(HttpMethod.GET); | |
await respondSwitchAwait(HttpMethod.GET); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment