I wrote code in Dart. I really like the factory constructor, but I'm afraid that I am abusing its utility. In particular, when I write a value object class, I sometimes return null if the check 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 is not so 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 like Java or C ++ would expect it to emailAddressalways be initialized to a non-zero value. The argument why this is perfectly acceptable is that the factory constructor, and as such, has the ability to return a value null.
So is this a bad practice or use of a useful feature?