java - 在单行上严格省略花括号是否被认为是正确的?

标签 java if-statement coding-style

<分区>

我个人反对在 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();
}

我个人认为这段代码是:

  • 尽可能简洁,将在下面显示其他变体。
  • 不容易受到添加一行会更改代码逻辑的问题的影响。

我会将其设置为我自己的个人规则,在控制流语句中使用它。
所以实际上这意味着,returnbreakcontinue

此代码的两个替代版本如下所示。

备选方案 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();
    }
}

我会说它们都无缘无故地使代码看起来更复杂。

最佳答案

Is it considered correct to omit curly braces strictly on one-liners?

嗯,没有任何硬性规定。但考虑到可用性案例,我总是使用大括号。它使代码更具可读性,对于初级开发人员来说也很容易理解。同样,这纯粹是个人/公司(代码标准)的选择。

再次在您的备选方案中,我会选择 Alternative2

public <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
    Objects.requireNonNull(exceptionSupplier);
    if (!result) {
        throw exceptionSupplier.get();
    }
}

为什么?

  1. 更简洁
  2. 行数较少
  3. 逻辑简单

关于java - 在单行上严格省略花括号是否被认为是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23057912/

相关文章:

visual-studio - Visual Studio 2015 - 代码样式设置

java - 用于线程正确性的断言或注释

java - 如何修复 "Call to getEmbeddedPicture failed"异常?

sql - if-then-else 逻辑可以在 Redshift 中完成吗?

python - 我认为没有办法在 Python 中将 if 语句和 else 语句放在一行中是对的吗?

mysql - 如果数据库存在,如何退出 MySQL 脚本

php - PSR-2编码标准: why no closing PHP tag in files containing only PHP?

coding-style - 如何以更优雅的方式解决这个 Python 难题?

java - 我怎样才能让我的 PrimeNumber 生成器工作?

java - Android中无法使用线程