【问题标题】:How to avoid "Change this condition so that it does not always evaluate to "false""如何避免“更改此条件,使其不总是评估为“假””
【发布时间】:2021-01-05 03:42:50
【问题描述】:

您好,我正在使用 sonarqube 分析我的代码,并遇到以下方法的错误

    final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element);
        if (active != null) {
            if (active.booleanValue()) {
                final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed(
                        GroupingTypesApiConstants.activationDateParamName, element);
                baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull();
            } else {
                // TODO - KW - not using config for now - just supporting move
                // to pending or active out of box.
                final boolean isPendingApprovalEnabled = true;
                if (!isPendingApprovalEnabled) {
                    baseDataValidator.reset().parameter(GroupingTypesApiConstants.activeParamName)
                            .failWithCode(".pending.status.not.allowed");
                }
            }
        } else {
            baseDataValidator.reset().parameter(ClientApiConstants.activeParamName).value(active).trueOrFalseRequired(false);
        }

sonarqube 说“在语句“if (!isPendingApprovalEnabled)”中更改此条件,使其不会总是评估为“false”

【问题讨论】:

  • 该代码似乎作为占位符存在。您可以忽略该警告,因为它不是最终代码。
  • 所以我改变了规则?并接受?
  • 为什么要在代码库中放置从未被调用的代码?
  • 我不知道具体的 SonarCube 规则,但您可以尝试将标志设为 private static final boolean 字段。我已经多次将其用于条件编译。也许 SonarCube 会毫无征兆地接受这一点。

标签: java if-statement sonarqube


【解决方案1】:

isPendingApprovalEnabled 永远不会为假,因为它在前面的行中使用true 进行了初始化。只要前面的那行是这样实现的,if语句就是死代码。

您可以删除该代码(并在支持配置时重新引入)或用方法替换变量。

  /* ... */
  if (!isPendingApprovalEnabled()) {
  /* ... */
}

private boolean isPendingApprovalEnabled() {
  // TODO - KW - not using config for now
  return true;
}

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2018-08-01
    • 2018-02-10
    • 2017-06-12
    • 2016-05-14
    • 2020-01-11
    • 2016-11-25
    • 2020-06-01
    • 2017-02-02
    相关资源
    最近更新 更多