Description
Trying to refactor a simple function that validates a Uri
:
bool _validateUri(Uri uri) {
return uri.path == '/path' &&
uri.queryParameters['param1'] == 'param1' &&
uri.queryParameters['param2'] == 'param2' &&
uri.queryParameters['param3'] != null &&
uri.queryParameters['param4'] != null;
}
I have followed my instincts and wrote this code using patters:
bool _validateUri(Uri uri) {
return uri.path == '/path' && uri.queryParameters case {
'param1': 'param1',
'param2': 'param2',
'param3': String _,
'param4': String _,
};
}
and found out that I can't use case
conditions anywhere outside an if
. Furthermore, when I changed the code to use an if
condition I found out that I can only use a single case
condition in the if
.
I got this to work with a switch
and a single pattern:
bool _validateUrl(Uri uri) {
return switch (uri) {
Uri(
path: '/path',
queryParameters: {
'param1': 'param1',
'param2': 'param2',
'param3': String _,
'param4': String _,
},
) => true,
_ => false,
};
}
But this approach requires me to explicitly return true and have a default false case, when all I want is to just return a bool result of "this variable did(n't) match this pattern".
In my opinion it would be useful and intuitive to be able to use case
conditions outside of if
and to chain multiple conditions with case
. This might be two separate issues, but this was my thought process when trying to refactor this function.