Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to return null from a factory constructor in Dart?

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?

like image 880
Andrew Avatar asked Feb 15 '14 02:02

Andrew


People also ask

Can a factory return null?

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 .

How do you return a null in darts?

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.

Is it okay to return null in method?

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.

What is the use of factory constructor in Dart?

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).


1 Answers

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.

like image 178
jamesdlin Avatar answered Oct 15 '22 11:10

jamesdlin