AlgoViz

Single responsibility (SRP)

medium 50 min

A class should have one reason to change: it answers to one group of people.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:20

See it run

Objects at run time: who asks for a change, who is hit by it, and what a split makes better or worse.

Operations

One change in a god class

Marketing changes a text, and the cache is empty.

Step 1 of 6

One actor

marketingwants a new textusersUserServicerulesokrows2mail textv1cachewarmlogtexttestsgreenlast editweek 1

At first only marketing asks for things. One class, one owner: no problem.

Step 1: One actor

def send_welcome(self, email):    body = "Welcome, " + self.find(email)    self.sent.append((email, body))    self.cache.clear()      # nobody remembers whydef find(self, email):    if email not in self.cache:        self.cache[email] = self.rows[email]    return self.cache[email]
Good for
The first weeks
Costs
Every wish is everybody's risk
Reasons to change
6

Ask for the last three bugs. Often they sit where two groups meet.

In the real world

The same single responsibility doing real jobs. Pick one and step through it.

One person for everything becomes a team with somebody who knows the order.

Step 1 of 8

One person

one personRestaurantManagercooksyesservesyestakes moneyyescleansyesbusy withpastaguests4 tablesmoodfinewaiting0

Cooking, serving, taking money, cleaning, counting the store, writing the report. With two guests it works.

Step 1: One person

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Splitting by size

    major

    Three files that always change together are one responsibility, only harder to read.

    Wrong
    class NameRule: ...class EmailRule: ...class AgeRule: ...      # always edited together
    Right
    class RegistrationRules:    def check(self, name, email, age): ...
  • A coordinator with rules

    critical

    The next god class starts with one small if.

    Wrong
    def run(self, name, email):    if email.endswith(".test"): return None    ...
    Right
    clean = self._rules.check(name, email)
  • A base class that brings it back

    major

    Everybody inherits the logger, the database and the mailer. The harness is back.

    Wrong
    class RegistrationRules(BaseService):   # has self.db, self.mail    ...
    Right
    class RegistrationRules:                # needs nothing    ...
  • A flag for the second actor

    critical

    Both rules stay in one method, and every caller must know the history.

    Wrong
    shift.hours(rounded=True)
    Right
    PaidTime().minutes(shift)RealTime().minutes(shift)
  • Data class and helper

    major

    Nobody guards the data, and the order of calls decides whether it is right.

    Wrong
    OrderDeliverySetter().set(order)OrderLineAdder().add(order, 6000)
    Right
    order.add(6000)order.total()
  • Joints without care

    critical

    Between two classes a process can die. Then one half has happened.

    Wrong
    users.add(name, email)mail.send(user)          # and if we stop here?
    Right
    uow.add_user(email, name)uow.remember(key, message)uow.commit()

Interview tips

  • Name the people

    • Who asked for the last changes?
    • One name per class
    • Roles, not technologies
  • Show evidence

    • Methods against fields
    • Commits that go together
    • Stand-ins per test
  • Keep the order thin

    • No rule, no SQL, no text
    • One coordinator per use case
    • Collaborators handed in
  • Know the other side

    • Merge what moves together
    • Methods stay with their data
    • Say which cut you did not make