public Neocortex(Region rootRegion, ConnectionInterface functor) {
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}

嘿,上面我有一个类的构造函数。我的问题是我应该向构造函数添加空指针异常,还是这是不必要的?老实说,我只是不知道何时向代码中添加异常。但是在这种情况下,我应该使用哪个构造函数?
public Neocortex(Region rootRegion, ConnectionInterface functor) {
    if (rootRegion == null) {
    throw new NullPointerException("rootRegion cannot be null");
} else if (functor == null) {
        throw new NullPointerException("functor cannot be null");
    }
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}

最佳答案

好吧...这是一个品味问题。

如果该类的先决条件是必须提供rootRegion,则有必要保护该类的实现,而不必在各处进行空检查。

因此,回答“何时应该在构造函数中引发异常”这个问题:在所有情况下,如果使用方的参数使使用者的实现处于无效状态并委托问题(即引发异常),我将这样做。

如果您尝试一段时间充当消费者角色,并且选择不进行空检查,那么他将具有以下代码:

Neocortex n = new Neocortex(null,null);
n.doSomeething();

如果他到达第二行,并且此处的实现抛出NullPointerException,那么对于他来说,这还不是很清楚,这归因于他提供的参数。

09-25 17:21