Reputation: 3849
I have a class called Result
that I'm using to pass on some error codes and error messages to an error screen.
class Result<T>{
Result._();
factory Result.loading(T msg) = LoadingState<T>;
factory Result.success(T value) = SuccessState<T>;
factory Result.error(T title, T msg, T errorcode) = ErrorState<T>;
}
class ErrorState<T> extends Result<T> {
final T title;
final T msg;
final T errorcode;
ErrorState(this.title, this.msg, this.errorcode) : super._();
//final T msg;
}
This class is called as follows:
return Result.error("Error","Status code not 200", 1);
Functionally it all works great.
The problem is I see myself in the future having to refer back to my class Result code to remember what each field represents which may become even more problematic if I want to add in more fields down the line
I'd rather convert this so that the fields are named
Can this class be converted so that it is called like this (with a name describing the parameter):
return Result.error(title:"Error", msg:"Status code not 200", errorcode:1);
Upvotes: 2
Views: 80
Reputation: 90005
If you want to change Result.error
to accept named parameters without breaking existing call sites, you can't do that. Parameters can be either positional or named, but not both.
If you're okay with breaking existing call sites, then you can just make them required named parameters. Since you're using redirecting constructors, you either will need to:
Change the signature of the redirectee constructor (in your case, ErrorState
) to exactly match that of Result.error
:
factory Result.error(
{required T title, required T msg, required T errorcode}) = ErrorState<T>;
...
ErrorState({required this.title, required this.msg, required this.errorcode})
: super._();
Or change Result.error
to be a non-redirecting constructor:
factory Result.error(
{required T title, required T msg, required T errorcode}) {
return ErrorState<T>(title, msg, errorcode);
}
(If you do want to avoid breaking existing callers, you could add a separate named constructor (or static
method) that uses named parameters, and you could optionally deprecate the old constructor.)
As an aside, it does not make sense that Result
and ErrorState
are generic classes. Do you really expect title
and msg
to not be String
s? Does it really make sense for the type of title
, msg
, and errorcode
to be the same? (With the example you've shown, you'll end up with Result<Object>
, which defeats the point of using a generic class.)
Upvotes: 3