Single Responsibility — Clean Code

SRP means a unit of code has one reason to change, and the easiest way to count reasons is by who asks for changes. An OrderService.placeOrder that checks…

One employee at Raka's T-Shirt Shop handles everything: checks orders, works out prices, writes them in the book, and messages the buyer. Finance wants a new promo, the warehouse wants new shipping, customer service wants new wording for the message, and they all go to the same person. Every request can disturb the other work that person holds.

The Single Responsibility Principle (SRP) keeps code from becoming that employee: a unit of code, whether a function, a class or a file, has one reason to change. The easiest way to picture a "reason to change": who is going to come and ask for that code to change.

One class, four jobs

Raka's T-Shirt Shop now saves orders and sends a confirmation email. So it runs anywhere, the "database" and the "email outbox" here are just arrays:

// VOUCHER_DISCOUNT, FREE_SHIPPING_MIN, SHIPPING_FEE: constants from the earlier lessons
const savedOrders = []; // pretend database
const outbox = [];      // pretend email outbox

class OrderService {
  placeOrder(cart, voucherCode, email) {
    if (cart.length === 0) throw new Error('Cart is empty');
    if (!email.includes('@')) throw new Error('Invalid email');

    let total = 0;
    for (const item of cart) total += item.price * item.qty;
    if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
    if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;

    const order = { id: savedOrders.length + 1, email, total };
    savedOrders.push(order);

    outbox.push(email + ': Order #' + order.id + ', Total: $' + total.toFixed(2));
    return order;
  }
}

Four blocks split by blank lines: check the order, work out the price, save, send the email. Describe it in one sentence and you need three "and"s.

A reason to change = who asks

Count the parties who can come and ask for placeOrder to change:

Who asks The request The part that changes
Raka, the owner "At most 10 items per order" validation
Finance "SAVE10 becomes 15%" voucher
Warehouse "Shipping becomes $20" shipping
IT team "Move from an array to a real database" saving
Customer service "The email opens with 'Hi there'" email

Four jobs, but five parties, because the price has two owners. All of them in one method. Customer service's request about the email greeting makes you open the same method that holds the price formula, and every time you finish a change, all of its jobs have to be checked again.

You count it the same way for other code. saveUserAndSendEmail() gives itself away in its name: two jobs, so two reasons to change. A UserService that handles authentication, input validation, database queries and response formatting has four reasons to change, because each responsibility can change on its own. Changing the response format should never be able to break login.

Checking a price sends an email

The only way to check a price in this class is to call placeOrder. You only want to check the price of the four carts from the first lesson. Before you run them, guess: how many emails go out along the way?

OK   Total: $220.50
OK   Total: $245.00
OK   Total: $90.00
OK   Total: $204.00
Orders saved: 4
Emails sent: 4

The prices are right, but to check four prices, four fake orders went into the "database" and four emails went out. In a real shop, that's four stray emails and four junk rows in the finance report. That's why tests for a class holding many jobs usually need many fakes (mocks): one for the database, one for email, and so on.

Split by who asks

Each party gets its own unit. The price was already split in the Small, Focused Functions lesson: applyVoucher belongs to finance, addShipping to the warehouse. That leaves three new classes:

class OrderValidator {          // order rules: Raka
  validate(cart, email) {
    if (cart.length === 0) throw new Error('Cart is empty');
    if (!email.includes('@')) throw new Error('Invalid email');
  }
}

class OrderRepository {         // saving: IT team
  save(order) {
    const saved = { id: savedOrders.length + 1, ...order };
    savedOrders.push(saved);
    return saved;
  }
}

class OrderMailer {             // email wording: customer service
  sendConfirmation(order) {
    outbox.push(order.email + ': Order #' + order.id + ', Total: ' + formatPrice(order.total));
  }
}

function calculateAmount(cart, voucherCode) {   // price: finance and warehouse
  const discounted = applyVoucher(calculateSubtotal(cart), voucherCode);
  return addShipping(discounted);
}

class OrderService {
  placeOrder(cart, voucherCode, email) {
    new OrderValidator().validate(cart, email);
    const total = calculateAmount(cart, voucherCode);
    const order = new OrderRepository().save({ email, total });
    new OrderMailer().sendConfirmation(order);
    return order;
  }
}

A coordinator isn't a violation

The new placeOrder still calls four things. Does that break SRP? No. It only coordinates the order of the steps, and it has just one reason to change: the checkout flow changes, for example the email only goes out once payment clears. Same as calculateTotal in the Small, Focused Functions lesson.

The opposite is wrong too: splitting until every line is a class. An add(a, b) split into a Validator, a Calculator and a Formatter only adds files without separating anyone, because no different parties ask for changes.

Exercise: UserManager

The exercise's UserManager does three jobs. Split it into three classes:

  1. EmailValidator with isValid(email): true when the email contains @.
  2. UserRepository with save(user): returns { id: 1, ...user }.
  3. UserFormatter with format(user): returns '[' + user.id + '] ' + user.name + ' (' + user.email + ')'.

For { name: 'Budi', email: '[email protected]' }, the output is:

true
{"id":1,"name":"Budi","email":"[email protected]"}
[1] Budi ([email protected])

Format the saved user (saved), because only it has an id. Format the original user and the third line becomes [undefined] Budi ([email protected]).

⚠️ Counting reasons wrong, splitting classes wrong

TL;DR: SRP means a unit of code has one reason to change, and the easiest way to count reasons is by who asks for changes. An OrderService.placeOrder that checks, prices, saves and emails has five parties (Raka, finance, warehouse, IT, customer service), and checking the price of four carts through it saves 4 orders and sends 4 emails. Split into OrderValidator, calculateAmount, OrderRepository and OrderMailer, the price can be checked alone with no side effects, and placeOrder just coordinates, with the same result. saveUserAndSendEmail() breaks SRP because it does two jobs; a UserService with authentication, validation, queries and formatting has 4 reasons to change. In the exercise: EmailValidator, UserRepository, UserFormatter, and format the user save returns so you get [1] Budi ([email protected]).

⚡ A reason to change = who asks

Meaning: SRP means a unit of code has just one reason to change. Count the parties who can ask for placeOrder to change: Raka, finance, the warehouse, the IT team and customer service. Five parties in one method. saveUserAndSendEmail() gives itself away in its name: two jobs, two reasons to change.

⚡ Checking a price sends an email

Guess first: you only want to check the price of four carts through placeOrder. How many emails go out along the way?

Four. The prices are right, but four fake orders went into the "database" and four emails went out: Orders saved: 4, Emails sent: 4.

Meaning: Tests for a class holding many jobs usually need many fakes (mocks): one for the database, one for email, and so on.

⚡ Split by who asks

Write:

class OrderService {
  placeOrder(cart, voucherCode, email) {
    new OrderValidator().validate(cart, email);
    const total = calculateAmount(cart, voucherCode);
    const order = new OrderRepository().save({ email, total });
    new OrderMailer().sendConfirmation(order);
    return order;
  }
}

Meaning: Each party gets its own unit. calculateAmount(cartA, 'SAVE10') can now be checked on its own: 220.5, with no order and no email. placeOrder only coordinates, and it has one reason to change: the order of the checkout steps.

⚡ Format what save returns

Write:

const saved = new UserRepository().save(user);
const formatted = new UserFormatter().format(saved);

Meaning: In the exercise, only the user save returns has an id. Format the original user and the third line becomes [undefined] Budi ([email protected]).

What you will learn