【问题标题】:How can I reduce cyclomatic complexity for the code to be acceptable by sonar如何降低声纳可接受的代码的圈复杂度
【发布时间】:2020-02-13 19:19:45
【问题描述】:

此功能在声纳中无法正常工作

【问题讨论】:

  • 看起来你没有发布你的整个函数,所以目前有什么语法错误。
  • 编辑了我的代码。其声纳代码气味陈述功能的复杂度为 11,大于授权的 10
  • 函数的复杂性几乎总是可以通过将其分解为更小的函数来降低。将 for 循环的内容移动到自己的函数中可能是很好的第一步。

标签: javascript sonarqube


【解决方案1】:

Sonar 的圈复杂度度量的一种简化思考方式是“我必须推理多少逻辑分支和循环才能理解这个函数?”您可以采取以下几种方法:

  1. 拆分您的功能。如果该函数正在执行多项操作,请尝试将每项内容拆分为自己的函数
  2. 减少代码中的分支。通常情况下,if/else 语句可以改为条件赋值。

圈复杂度甚至没有涵盖您的代码中难以遵循的其他一些内容:

  1. 您经常复制段代码,而不是将内容存储在临时变量中。复制代码不仅使阅读代码的人有更多工作要做,而且还意味着您正在强迫程序做这些额外的工作。
  2. 因为您始终使用var,所以阅读您的代码的人必须查看您的整个函数,以了解是否将在不同点重新分配变量。当某些事情不会改变时使用 const 可以让我们知道我们是否不必再担心这个问题。
  3. 您的某些 if 语句条件很复杂。尝试将它们重构为更易读的临时变量。

这是我降低圈复杂度和代码可读性的尝试:

function validateSignInForm(signinErrorMessage) {
  let bFinalSubmit = true;

  if (!validateFields()) {
    bFinalSubmit = false;
  }

  const errMainError = (typeof signinErrorMessage === 'undefined')
    ? configuration.messages.signinIncomplete;
    : signinErrorMessage;
  if (errMainError === configuration.messages.notFound) {
    trp.fai.common.log(errMainError);
    bFinalSubmit = false;
  }

  const errMsg = $('#signin-mainerr-message');
  const errContainer = $('#signin-ui-notification-container-mainerr');
  if (!bFinalSubmit) {
    errMsg.html(errMainError);
    errContainer.show();
  } else {
    errMsg.html('');
    errContainer.hide();
  }

  return bFinalSubmit;
}

function validateFields() {
  let canSubmit = true;

  configuration.required.signin.forEach(field => {
    const fieldName = field.name;
    const fieldValue = $.trim(field.value);
    const fieldElement = $('#' + fieldName);
    const fieldLabel = fieldElement
      .closest('li')
      .find('label')

    if (
      (fieldValue === '' || (fieldName === 'username' && fieldValue === 'Your email address')) 
      && $('#' + field.id).is(':visible')
    ) {
      fieldElement.addClass('ui-red-border');
      fieldLabel.addClass('ui-red-text');
      canSubmit = false;
    } else {
      fieldElement.removeClass('ui-red-border');
      fieldLabel.removeClass('ui-red-text');
      $('#' + fieldName + 'Field').removeClass('registerFieldError');

      if (configuration.required.signin[i].onchange) {
        configuration.required.signin[i].onchange();
      }
    }
  });

  return canSubmit;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-13
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多