从Dart中的工厂构造函数返回null是否可以接受? [英] Is it acceptable to return null from a factory constructor in Dart?

查看:397
本文介绍了从Dart中的工厂构造函数返回null是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用Dart编写一些代码。我真的很喜欢工厂构造函数,但恐怕我滥用它的用处。特别是,当我编写一个值对象类时,如果验证失败,我有时会返回null。

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");
  ...
}

为什么这样不好的论点是来自其他静态类型的语言(例如Java或C ++)的开发人员希望 emailAddress 始终被初始化为非null值。为什么这是完全可以接受的参数是构造函数是工厂,因此可以返回 null 值。

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?

推荐答案

返回 null 来自工厂的结果是可以接受的,因为Dart 工厂功能wiki / Factory_%28software_concept%29 rel = nofollow>工厂软件概念没有任何空值限制。

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.

另一方面,我可以改写您的问题是否可以从相等运算符返回null

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";
}

PS

我个人认为从Dart的工厂返回 null 坏习惯是因为Dart的工厂很难与构造函数区分开。

My personal opinion that returning null from factory in Dart is a bad practice because factories in Dart are very difficult to distinguish from contructors.

从外部看,它们看起来像构造函数,不同之处在于它们更强大,因为可以构造不同的类型

From the outside they looks like contructors 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...

这篇关于从Dart中的工厂构造函数返回null是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆