<分区>
我个人反对在 if-else-statements 中省略花括号,我完全明白为什么应该避免它。
但是现在我遇到了一个有趣的用例,示例代码在这里:
public <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (result) return;
throw exceptionSupplier.get();
}
我个人认为这段代码是:
- 尽可能简洁,将在下面显示其他变体。
- 不容易受到添加一行会更改代码逻辑的问题的影响。
我会将其设置为我自己的个人规则,仅在控制流语句中使用它。
所以实际上这意味着,return
、break
和continue
。
此代码的两个替代版本如下所示。
备选方案 1
public <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (result) {
return;
}
throw exceptionSupplier.get();
}
备选方案 2
public <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (!result) {
throw exceptionSupplier.get();
}
}
我会说它们都无缘无故地使代码看起来更复杂。