Inappropriate coding practices - Cyclomatic complexity - Elixir

Inappropriate coding practices - Cyclomatic complexity - Elixir

Need

Enhance maintainability and security of the code

Context

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

Description

Non compliant code

        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

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

Compliant code

        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