Backend Complexity - shibotsu/obs-clone GitHub Wiki

🧮 Cyclomatic Complexity in Backend Development

Cyclomatic complexity is a software metric used to measure the complexity of a program by quantifying the number of linearly independent paths through its source code. It is an important indicator of code maintainability, readability, and testability.

What is Cyclomatic Complexity?

  • Definition: Cyclomatic complexity counts the number of decision points (such as if, else, while, for, case, etc.) in a program.
  • Formula:
    M = E - N + 2P
    
    Where:
    • M = cyclomatic complexity
    • E = number of edges in the control flow graph
    • N = number of nodes in the control flow graph
    • P = number of connected components (usually 1 for a single program)

Why is it Important?

  • Maintainability: Lower complexity means code is easier to understand and modify.
  • Testability: Higher complexity requires more test cases to achieve full coverage.
  • Quality: Helps identify potentially problematic or error-prone code.

Interpreting Cyclomatic Complexity

Complexity Value Interpretation
1-10 Simple, low risk
11-20 Moderate complexity, moderate risk
21-50 Complex, high risk
51+ Very complex, very high risk

How to Measure Cyclomatic Complexity

Best Practices

  • Refactor methods/functions with high complexity.
  • Aim for small, single-responsibility functions.
  • Use early returns to reduce nesting.
  • Regularly review complexity metrics as part of code reviews.

Example

public function follow($id)
    {
        $user = User::find($id); //(1)
        if (!$user) { //(2)
            return response()->json(['error' => 'User not found.'], 404); //(3)
        }

        if (auth()->id() === $user->id) { //(4)
            return response()->json(['error' => 'You cannot follow yourself.'], 400); //(5)
        }

        if (auth()->user()->following()->where('following_id', $user->id)->exists()) { //6)
            return response()->json(['error' => 'You are already following this user.'], 409); //(7)
        }

        auth()->user()->following()->attach($user->id);
        $user->number_of_followers++;
        $user->save(); //(8)

        return response()->json(['message' => 'Followed successfully']);
    }

Graph

ccgraph

Cyclomatic comple xity of this graph is 4.

Possible execution paths:

  • P → 1 → 2 → 3 → K
  • P → 1 → 2 → 4 → 5 → K
  • P → 1 → 2 → 4 → 6 → K
  • P → 1 → 2 → 4 → 6 → 8 → K

Note: In the diagram, the far-right node should be labeled K (end), not 8.

References: