Course contentsShow
← JavaScript
Lesson 1750 of 2,72337. Functional Programming PatternsFree lesson

Handling External Dependencies Purely

Use dependency injection to isolate I/O and keep core logic pure.

Handling External Dependencies Purely

You'll learn how to keep your core logic pure even when your program needs side effects like network calls or file I/O.

The Core Problem

Pure functions can't directly perform I/O operations—reading files, making HTTP requests, or accessing databases are all side effects. Yet real programs need these operations. The solution? Dependency injection: pass the impure dependencies as arguments instead of calling them directly inside your function.

How It Works

Instead of hardcoding calls to external resources, your pure function accepts those resources as parameters. The impurity is pushed to the edges of your system—caller code handles the messy I/O, while your core logic stays testable and predictable.

// ❌ Impure: directly calls fetch
function getUserData(userId) {
  return fetch(`/api/users/${userId}`).then(r => r.json());
}

// ✅ Pure: accepts fetcher as dependency
function getUserData(fetcher, userId) {
  return fetcher(`/api/users/${userId}`).then(r => r.json());
}

// Impurity happens at call site
getUserData(fetch, 42);

For synchronous logic, inject already-fetched data:

// ✅ Pure: processes data, doesn't fetch it
function calculateDiscount(user, orderTotal) {
  return user.isPremium ? orderTotal * 0.9 : orderTotal;
}

// Caller handles I/O
const user = await fetchUser(id); // impure
const discount = calculateDiscount(user, 100); // pure

Why This Matters

By injecting dependencies, you isolate side effects, making your core functions:

  • Easier to test (pass mock dependencies)
  • Easier to reason about (no hidden I/O)
  • More reusable (works with any data source)

Key Takeaway: Dependency injection lets you keep business logic pure by accepting side-effect-producing functions or pre-fetched data as parameters, pushing impurity to the program's boundaries.