---
title: Use Dependency Injection
impact: MEDIUM
impactDescription: enables testable business logic and decupling
tags: dependency-injection, decoupling, testability, quality
---

## Use Dependency Injection

Hardcoding dependencies inside classes makes them difficult to test and tightly coupled. Pass dependencies through the constructor (`initialize`).

**Incorrect (tightly coupled):**

```ruby
class OrderService
  def process(order)
    # Hardcoded dependency
    mailer = UserMailer.new
    mailer.send_confirmation(order.user)
  end
end
```

**Correct (dependency injection):**

```ruby
class OrderService
  def initialize(mailer = UserMailer.new)
    @mailer = mailer
  end

  def process(order)
    @mailer.send_confirmation(order.user)
  end
end

# In tests:
# service = OrderService.new(MockMailer.new)
```

**Tools:** PR review
---
