logo

Database

Inappropriate coding practices - Cyclomatic complexity

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

1. 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'
            IO.puts 'abc'...

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.

2. Steps

• Decompose the function into smaller, simpler functions

• Replace nested if-else statements with cleaner control structures, like pattern matching

3. 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'
    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.