SonarLint 警告,此代码将始终 return 相同的值

SonarLint warning, this code will always return the same value

SonarLint 告诉我:

"Refactor this code to not always return the same value."

但是我好像不太明白为什么

private List<InvoiceRejectionMessage> invoiceList = new ArrayList<>();

public String getMessage() {
    if(!invoiceList.isEmpty()) {
        return invoiceList
                .stream()
                .max(comparing(InvoiceRejectionMessage::getCreatedAt))
                .get()
                .getMessage();
    }
    return null;
}

InvoiceList 已定义并将始终被初始化,因此它不能为 null 只能为空。如果为空,则 return 为空。如果不是,我们确定其中有一个元素可以被 .max() 和 .get()

编辑 return

我不愿意仅仅因为 Sonarlint 告诉我重构这个方法,我想知道为什么我会收到这个警告

与此提示关联的规则是

squid:S3516 - Methods returns should not be invariant

此规则的 SonarQube 实现在 GitHub 上可用。

没有看到您的整个代码,我不能 100% 确定为什么会触发此规则。但是,我怀疑 Sonar 能够弄清楚

  1. invoiceList 无条件为空且;因此
  2. 您的 if-then-else 语句的 if 分支永远不会执行;因此,
  3. the getMessage 方法无条件 returns null.

反正没必要把空表当成特例;您可以通过以下方式简化代码,这可能会安抚声纳:

private List<InvoiceRejectionMessage> invoiceList = new ArrayList<>();

public String getMessage() {
    return invoiceList
            .stream()
            .max(comparing(InvoiceRejectionMessage::getCreatedAt))
            .map(InvoiceRejectionMessage::getMessage)
            .orElse(null);
}

顺便说一句,如果您可以更改 class 的 API,其客户将从将 getMessage 的 return 类型更改为 Optional<String> 中受益(只需删除最后一个 orElse(null) 调用):

public Optional<String> getMessage() {
    return invoiceList
            .stream()
            .max(comparing(InvoiceRejectionMessage::getCreatedAt))
            .map(InvoiceRejectionMessage::getMessage)
}