Is it acceptable to return null from a factory constructor in Dart?
Returning null
value as result from a factory is acceptable because the builtin factory
feature in Dart Factory software concept does not have any null-restriction.
On the other hand I can rephrase your question "Is it acceptable to return null from a equality operator"
bool operator ==(other) {
return null;
}
This is also acceptable because there is no such restriction that this operator cannot return the null
value.
But there is another question? Why do it and how to avoid it?
factory EmailAddress(String input) {
return _regex.hasMatch(input) ? new EmailAddress._internal(input) :
throw "something went wrong";
}
P.S.
My personal opinion that returning null
from factory
in Dart is a bad practice
because factories in Dart are very difficult to distinguish from constructors.
From the outside they looks like constructors with the difference that they are more powerful because can construct different kinds of objects.
And they also have their restrictions but this is another story.
With null-safe Dart, factory
constructors are no longer permitted to return null
.
Existing factory
constructors that return null
are expected to be replaced with static
methods when migrated.