重构此方法以将其认知复杂度从 21 降低到允许的 15。如何重构和降低复杂性

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. How to refactor and reduce the complexity

如何降低给定代码段的复杂度?我在 Sonarqube 中收到此错误---> 重构此方法以将其认知复杂度从 21 降低到允许的 15。

this.deviceDetails = this.data && {...this.data.deviceInfo} || {};
    if (this.data && this.data.deviceInfo) {
      this.getSessionInfo();
      // tslint:disable-next-line: no-shadowed-variable
      const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
      this.deviceDetails = {
        name: device.name || '',
        manufacturer: device.manufacturer || '',
        deviceType: device.deviceType || '',
        model: device.model || '',
        description: device.description || '',
        managerId: device.deviceManager && device.deviceManager.managerId || null,
        locationId: device.location && device.location.locationId || null,
        active: device.active,
        connectionType: connectionType || null,
        driver_id: driver && driver.driverId || null,
        ipAddress: ipAddress || '',
        port: String(port) || '',
        connectionStatus: active,
      };
      this.oldDeviceDetails = {...this.deviceDetails};
      this.deviceLocation = device.location && device.location.locationId || null;
    } else {

全部||只是加起来,它看起来像一个不好的做法。您可以将 this.deviceDetails = {... 转移到它自己的映射函数以获得快速解决方案。

如果您使用的是 typescript 3.7 或更高版本,您可以使用可选链接来简化您的某些条件。

  • device.deviceManager && device.deviceManager.managerId ||空

会变成

  • device.deviceManager?.managerId ||空

有关认知复杂性如何运作以及为何应保持低水平的一些信息

首先,重要的是要了解“认知复杂性”与“圈复杂性”相比如何工作。认知复杂性考虑了人脑感知的复杂性。这就是为什么它不简单地表示条件路径的数量(简化条件的数量加1为return语句)。

认知复杂性 指标还考虑嵌套条件(例如 if 内的 if,if 语句内的 if),这使得它甚至从人类的角度更难阅读和理解代码。

SonarQube 文档 (https://www.sonarsource.com/docs/CognitiveComplexity.pdf) 中的以下示例概述了我要解释的内容:

if (someVariableX > 3) { // +1
    if (someVariableY < 3) { // +2, nesting = 1
        if (someVariableZ === 8) { // +3, nesting = 2
            someResult = someVariableX + someVariableY - someVariableZ;
        }
    }
}

因此请注意,二元运算会增加复杂性,但嵌套条件甚至会为每个嵌套条件增加 1 分。这里的认知复杂度为 6,而圈复杂度仅为 4(每个条件一个,return 路径一个);

如果您使您的代码对人类更具可读性,例如通过从包含条件的行中提取方法,您可以同时获得更好的可读性和更低的复杂性。

尽管您提供的代码没有嵌套条件,但我认为首先了解圈复杂度和认知复杂度计算的工作原理以及为什么将其保持在较低水平是个好主意很重要。

[TL;DR] 一种将代码重构为不那么复杂且可读性更好的版本的可能方法

让我们首先看看评论中概述的代码的复杂度计算是如何完成的:

this.deviceDetails = this.data && {  ...this.data.deviceInfo } || {}; // +2
if (this.data && this.data.deviceInfo) { // +1 for the if condition, +1 for the binary operator
    this.getSessionInfo();

    const { device, driver, ipAddress, port, active, connectionType } =             
    this.data.deviceInfo;
    this.deviceDetails = {
        name: device.name || '', // +1 for the binary operator
        manufacturer: device.manufacturer || '', // +1 for the binary operator
        deviceType: device.deviceType || '', // +1 for the binary operator
        model: device.model || '', // +1 for the binary operator
        description: device.description || '', // +1 for the binary operator
        managerId: device.deviceManager && device.deviceManager.managerId || null, // +2 for the varying binary operators
        locationId: device.location && device.location.locationId || null, // +2 for the varying binary operator
        active: device.active,
        connectionType: connectionType || null, // +1 for the binary operator
        driver_id: driver && driver.driverId || null, // +2 for the varying binary operator
        ipAddress: ipAddress || '', // +1 for the binary operator
        port: String(port) || '', // +1 for the binary operator
        connectionStatus: active,
    };
    this.oldDeviceDetails = { ...this.deviceDetails };
    this.deviceLocation = device.location && device.location.locationId || null; // +2 for the varying binary operator
} else { // +1 for the else path 
    // some statement
}

所以假设我的数学是正确的,这总结了 SonarQube 报告的认知复杂度 21。

以下代码示例展示了如何将您的代码重构为一个版本,该版本应该将认知复杂度降低到 12。 (请注意,这只是人工计算。)

可以通过应用简单的重构来完成,例如提取方法 and/or 移动方法(另见 Martin Fowler,https://refactoring.com/catalog/extractFunction.html)。

this.deviceDetails = getDeviceInfo();
if (deviceInfoAvailable()) { // +1 for the if statement
    this.getSessionInfo();
    // tslint:disable-next-line: no-shadowed-variable
    const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
    this.deviceDetails = {
        name: getInfoItem(device.name), 
        manufacturer: getInfoItem(device.manufacturer),
        deviceType: getInfoItem(device.deviceType),
        model: getInfoItem(device.model),
        description: getInfoItem(device.description), 
        managerId: getManagerId(device),
        locationId: getDeviceLocation(device),
        active: device.active,
        connectionType: getInfoItem(connectionType, null), 
        driver_id: getDriverId(driver), 
        ipAddress: getInfoItem(ipAddress), 
        port: getInfoItem(port), 
        connectionStatus: active,
    };
    this.oldDeviceDetails = { ...this.deviceDetails };
    this.deviceLocation = getDeviceLocation(device);
} else { // +1 for the else
    // some statement
}

function getDeviceInfo()
{
    return this.data && { ...this.data.deviceInfo } || {}; // +2
}

function getDriverId(driver) {
    return driver && driver.driverId || null; // +2 for the binary operators
}

function getDeviceLocation(device) {
    return device.location && device.location.locationId || null; // +2 for the binary operators
}

function getManagerId(device) {
    return device.deviceManager && device.deviceManager.managerId || null; // +2 for the binary operators
}

function deviceInfoAvailable() {
    return this.data && this.data.deviceInfo; // +1 for the binary operator
}

function getInfoItem(infoItem, defaultValue = '') {
    return infoItem || defaultValue; // +1 for the binary operator
}

使用简单的提取方法重构大量重复(参见getInfoItem() 函数)被淘汰以及使得降低复杂度和增加可读性变得容易.

老实说,我什至会更进一步并进一步重组您的代码,以便在提供设备详细信息时检查空项目和设置默认值(此处为空字符串)的逻辑由设备 class 或设备详细信息 class 本身具有更好的数据和操作该数据的逻辑的凝聚力。但由于我不知道代码的其余部分,这个初始重构应该让您更进一步,以提高可读性和降低复杂性。

注意:我们甚至可以更进一步,执行所谓的Replace Nested Conditional with Guard Clauses 重构(有时也称为“early return”或“invert if statement)。

由于消除了 else 语句,这可能会导致如下所示的代码并进一步降低认知复杂度。导致最终的认知复杂度为 11。提取出来的函数是一样的,所以这里不再列出...

this.deviceDetails = getDeviceInfo();
if (deviceInfoAvailable()) { // +1 for the if statement
    // some statement
    return; // return the same way as in the eliminated else clause
}

this.getSessionInfo();
const { device, driver, ipAddress, port, active, connectionType } = this.data.deviceInfo;
this.deviceDetails = {
  name: getInfoItem(device.name), 
  manufacturer: getInfoItem(device.manufacturer),
  deviceType: getInfoItem(device.deviceType),
  model: getInfoItem(device.model),
  description: getInfoItem(device.description), 
  managerId: getManagerId(device),
  locationId: getDeviceLocation(device),
  active: device.active,
  connectionType: getInfoItem(connectionType, null), 
  driver_id: getDriverId(driver), 
  ipAddress: getInfoItem(ipAddress), 
  port: getInfoItem(port), 
  connectionStatus: active,
};
this.oldDeviceDetails = { ...this.deviceDetails };
this.deviceLocation = getDeviceLocation(device);