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

新手上路,请多包涵

如何降低给定代码段的复杂性?我在 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 {

原文由 sd_30 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 858
2 个回答

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

首先,重要的是要了解与“ _圈复杂度_”相比“ _认知复杂度_”是如何工作的。认知复杂性考虑了人脑感知的复杂性。这就是为什么它不简单地表示条件路径的数量(简化了条件的数量加 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(每个条件一个,返回路径一个);

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

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

[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
}

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

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

这可以通过应用 简单的重构 来完成,例如 提取方法 和/或移动方法(另请参阅 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() 函数) 也被消除,这 _使得降低复杂性和提高可读性变得容易_。

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

_注意_:我们甚至可以更进一步,执行所谓的 Replace Nested Conditional with Guard Clauses 重构(有时也称为“ _提前返回_”或“ _反转 if 语句_”)。

这可能会导致如下所示的代码,并且由于 _消除了 else 语句_,认知复杂度进一步降低了 1,从而导致最终的认知复杂度为 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);

原文由 afh 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

  • device.deviceManager && device.deviceManager.managerId ||无效的

会成为

  • device.deviceManager?.managerId ||无效的

原文由 Edward 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏