代码之家  ›  专栏  ›  技术社区  ›  Pablo Matias Gomez

在单行中调用可选的#isPresent()会报告为未调用

  •  9
  • Pablo Matias Gomez  · 技术社区  · 8 年前

    private static final int BASE_ID = 100_000_000;
    private boolean isValidId(Id id) {
        return id.asInteger().isPresent() && id.asInteger().get() >= BASE_ID;
    }
    

    方法 asInteger 退货 Optional<Integer>

    Call "Optional#isPresent()" before accessing the value. 在回油管中。

    if 如果第一个是假的就不会被处决。我知道这个问题可以通过 .filter(..).isPresent() 但我更喜欢这样。

    你知道为什么会这样吗?

    3 回复  |  直到 7 年前
        1
  •  19
  •   Andreas dfa    8 年前

    Sonarqube不能保证 id.asInteger() id

    将代码更改为首先分配给局部变量,以确保 isPresent() 和 get()

    private boolean isValidId(Id id) {
        Optional<Integer> idAsInteger = id.asInteger();
        return idAsInteger.isPresent() && idAsInteger.get() >= BASE_ID;
    }
    
        2
  •  5
  •   Eugene    8 年前

    你可以把它写成一句话顺便说一句:

    return id.asInteger()
             .map(x -> x >= BASE_ID)
             .orElse(false)
    

        3
  •  0
  •   Donat    8 年前

    在使用可选产品时,应避免 .isPresent 和 .get

    SonarQube的分析能力有限。它通常不能排除各种假阳性。这种情况并不是一个真正的问题,因为不建议以这种方式使用Optionals。

        4
  •  0
  •   Leandro Maro    7 年前

    为了避免这个问题,我使用iterator().next()它的功能与.get相同,但是它没有isPresent()问题!