Is it permissible to return null from the factory constructor to Dart?

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?

+3
3

null factory , factory Dart Factory .

, " null "

bool operator ==(other) {
  return null;
}

, , null.

? ?

factory EmailAddress(String input) {
  return _regex.hasMatch(input) ? new EmailAddress._internal(input) :
    throw "something went wrong";
}

P.S.

, null factory bad practice, .

, , .

, ...

+2

. - , .

:

class EmailAddress {
  final String _value;
  static final RegExp _regex = new RegExp(r"...");

  static bool isValid(String email) => _regex.hasMatch(email);

  EmailAddress(this._value) {
    if (!isValid(_value)) throw "Invalid email: $_value";
  }
}

. :

querySelector("#sendButton").disabled = !EmailAddress.isValid(userEmail);
+1

, . , . , Dart, null.

, :

  • throws an exception from invalid inputs. Thus, at least the error is early, and not later, if you saved somewhere null.

  • Use the static method instead of the constructor. Static methods may return nulland not be so confusing.

  • Specify a backup path, for example int.parse. You can accept a callback that will be called on error.

I prefer 1 or 3 myself. I would like to know when something is invalid.

+1
source

All Articles