पाठ 3 / 25

Side Effects and Why Isolating Them Helps

Effects are necessary; keep them at known places.

Effects are the point, but not everywhere

A program with no side effects cannot show output or save data, so FP does not ban effects: it isolates them. Typical effects are I/O (files, network, database), mutation of shared state, logging, reading the clock and throwing exceptions. When effects are scattered through business logic, every function must be tested with mocks and its behaviour depends on call order. When logic is pure and effects happen at a thin outer layer, the logic can be tested with simple input/output assertions and the effectful layer stays small enough to review and integration-test.

Splitting decision from action

Pure logic decides; a thin shell performs effects.

type Order = { id: string; total: number; customerEmail: string };
type Email = { to: string; subject: string };

// Pure: decides what should happen
function emailsFor(orders: Order[]): Email[] {
  return orders
    .filter(o => o.total >= 100)
    .map(o => ({ to: o.customerEmail, subject: `Thanks for order ${o.id}` }));
}

// Impure shell: fetches data and performs effects
async function run(db: { loadOrders(): Promise<Order[]> },
                   mailer: { send(e: Email): Promise<void> }) {
  const orders = await db.loadOrders();
  for (const email of emailsFor(orders)) {
    await mailer.send(email);
  }
}
// emailsFor can be unit-tested with plain arrays; no mocks needed.

The kitchen and the waiter

The kitchen (pure logic) prepares dishes from ingredients; only the waiter (the shell) talks to customers and handles payment. A mistake in service never changes a recipe.

त्वरित जाँच: Why isolate side effects from business logic?

  • Because effects always slow programs down
  • Because side effects are forbidden in JavaScript
  • To make programs unable to perform I/O
  • The logic becomes testable with plain inputs and outputs, and effects are confined to a small layer
Answer

The logic becomes testable with plain inputs and outputs, and effects are confined to a small layer — FP keeps effects, but moves them to the edges.