---
title: Avoid deep nesting (max 3 levels)
impact: MEDIUM
impactDescription: Improve code readability and reduce cyclomatic complexity.
tags: ruby, quality, metrics, nesting
---

## Avoid deep nesting (max 3 levels)

Improve code readability and reduce cyclomatic complexity. Limit nesting (if/else, blocks) to 3 levels maximum. Use guard clauses, early returns, or extract methods to flatten code.

**Incorrect:**

```ruby
def update_user
  if logged_in?
    if admin?
      if params[:id].present?
         # 4th level nesting
      end
    end
  end
end
```

**Correct:**

```ruby
def update_user
  return unless logged_in?
  return unless admin?
  return if params[:id].blank?
  
  # Logic at level 1
end
```

**Tools:** RuboCop (`Metrics/BlockNesting`)
