【发布时间】:2021-04-25 13:20:17
【问题描述】:
当我看到别人的代码时,我主要看到两种方法样式。
一个看起来像这样,有许多嵌套的 if:
void doSomething(Thing thing) {
if (thing.hasOwner()) {
Entity owner = thing.getOwner();
if (owner instanceof Human) {
Human humanOwner = (Human) owner;
if (humanOwner.getAge() > 20) {
//...
}
}
}
}
而另一种风格,看起来像这样:
void doSomething(Thing thing) {
if (!thing.hasOwner()) {
return;
}
Entity owner = thing.getOwner();
if (!(owner instanceof Human)) {
return;
}
Human humanOwner = (Human) owner;
if (humanOwner.getAge() <= 20) {
return;
}
//...
}
我的问题是,这两种代码样式有名称吗?如果,它们叫什么。
【问题讨论】:
-
我不知道名字,但之前已经注意到了区别。有(是?)一种经典的反感,反对在一个方法中使用多个返回语句(并且某些语言不允许这样做)。我个人认为这两种风格都没有问题,所以我同意你的描述,这完全是——风格的问题。
标签: java