logo

Inappropriate coding practices - Cyclomatic complexity - Elixir


Need

Enhance maintainability and security of the code


Context

  1. Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications
  2. Usage of Phoenix Framework for building web applications with Elixir

Description

Insecure Code Example

defmodule Unsafe do
  def complex_function(a, b, c, d) do
    if a do
      if b do
        if c do
          if d do
            IO.puts 'abcd'
          else
            IO.puts 'abc'
          end
        else
          IO.puts 'ab'
        end
      else
        IO.puts 'a'
      end
    else
      IO.puts 'none'
    end
  end
end

In this code, the function `complex_function` has a high cyclomatic complexity due to multiple nested if-else statements. High cyclomatic complexity makes the code difficult to read, maintain, and test. It could also increase the probability of bugs or vulnerabilities, as it's harder to understand all possible execution paths.

Steps

  1. Decompose the function into smaller, simpler functions
  2. Replace nested if-else statements with cleaner control structures, like pattern matching

Secure Code Example

defmodule Safe do
  def simple_function(a, b, c, d) do
    cond do
      a && b && c && d -> IO.puts 'abcd'
      a && b && c -> IO.puts 'abc'
      a && b -> IO.puts 'ab'
      a -> IO.puts 'a'
      true -> IO.puts 'none'
    end
  end
end

In this revised code, the function `simple_function` is much easier to read and understand. It uses the `cond` statement to clearly show the different conditions and their outcomes. This reduces the cyclomatic complexity and makes the function easier to test and maintain.


References

  • 145 - Inappropriate coding practices - Cyclomatic complexity

  • Last updated

    2023/09/18