I've been writing some code in Dart. I really love the factory constructor, but I'm afraid that I'm abusing it's usefulness. In particular, when I write a value object class, I sometimes return null if the validation fails.
class EmailAddress {
static final RegExp _regex = new RegExp(...);
final String _value;
factory EmailAddress(String input) {
return _regex.hasMatch(input) ? new EmailAddress._internal(input) : null;
}
const EmailAddress._internal(this._value);
toString() => _value;
}
At first, this doesn't seem all that bad. However, when you actually use it, this is what you see.
methodThatCreatesAnEmailAddress() {
var emailAddress = new EmailAddress("definitely not an email address");
...
}
The argument why this is bad is that a developer coming from another statically typed language, such as Java or C++, would expect emailAddress
to always be initialized to a non-null value. The argument why this is perfectly acceptable is that the constructor is factory and, as such, is allowed to return a null
value.
So is this bad practice or taking advantage of a useful feature?
If the intent of the factory was indeed to return null, then you can turn it into a static method so it is allowed to return null .
Dart allows returning null in functions with void return type but it also allow using return; without specifying any value. To have a consistent way you should not return null and only use an empty return.
Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.
A factory constructor is a constructor that can be used when you don't necessarily want a constructor to create a new instance of your class. This might be useful if you hold instances of your class in memory and don't want to create a new one each time (or if the operation of creating an instance is costly).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With