Swift

Swift

Made by DeepSource

Function with cyclomatic complexity higher than threshold SW-R1002

Anti-pattern
Minor

A function with high cyclomatic complexity can be hard to understand and maintain. Cyclomatic complexity is a software metric that measures the number of independent paths through a function. A higher cyclomatic complexity indicates that the function has more decision points and is more complex.

Functions with high cyclomatic complexity are more likely to have bugs and be harder to test. They may lead to reduced code maintainability and increased development time.

To reduce the cyclomatic complexity of a function, you can:

  • Break the function into smaller, more manageable functions.
  • Refactor complex logic into separate functions or classes.
  • Avoid multiple return paths and deeply nested control expressions.

Bad practice

// following code has a complexity of 6
func getColorName(code: Int) -> String {
    if code == 0xFF0000 {
        return "red"
    else if code == 0x00FF00 {
        return "green"
    else if code == 0x0000FF {
        return "blue"
    else if code == 0xFFFF00 {
        return "yellow"
    else if code == 0xFFFFFF {
        return "white"
    } else {
        return "unknown"
    }
}

Recommended

// following code has a complexity of 2
func getColorName(code: Int) -> String {
    let codeMap = [
        0xFF0000: "red",
        0x00FF00: "green",
        0x0000FF: "blue",
        0xFFFF00: "yellow",
        0xFFFFFF: "white"
    ]
    if let name = codeMap[code] {
        return name
    } else {
        return "unknown"
    }
}

Issue configuration

Cyclomatic complexity threshold can be configured using the cyclomatic_complexity_threshold meta field in the .deepsource.toml config file.

Configuring this is optional. If you don't provide a value, the Analyzer will raise issues for functions with complexity higher than the default threshold, which is 25 (category "high", please refer the table below) for the Swift Analyzer.

Here's the mapping of the risk category to the cyclomatic complexity score to help you configure this better:

Risk category Cyclomatic complexity range Recommended action
low 1-5 No action needed.
medium 6-15 Review and monitor.
high 16-25 Review and refactor. Recommended to add comments if the function is absolutely needed to be kept as it is.
very-high 26-50 Refactor to reduce the complexity.
critical >50 Must refactor this. This can make the code untestable and very difficult to understand.