Read Code Fast

Lesson 10 Structure words

5 min read · Python · Quiz

modules, classes, factories, and what "service", "handler" and "util" usually mean

What you'll learn

  • Say what a handler, service, repository, factory and util should do
  • Spot a name that promises more or less than the code does
  • Check what a class depends on and who owns its data

Before you read a single line of a new file, its name tells you what it is allowed to do. "Service", "handler" and "util" are promises about the code inside.

The idea

Structure words say where code lives and what it should touch. A handler takes a request and sends a reply, and should stay thin. A service holds the business steps. A repository talks to the database. A factory builds an object and wires its parts together. A util is a small, plain helper with no side effects.

Use the words as a map. If the SQL is in a handler, or a util sends emails, the name is making a promise the code doesn't keep. Then check who owns the data: each instance of a class, or one shared copy.

order_service.py
1class OrderService:2    def __init__(self, repo, mailer):3        self.repo = repo4        self.mailer = mailer56    def place(self, order):7        saved = self.repo.save(order)8        self.mailer.send_receipt(saved)9        return saved101112def create_order_service():13    return OrderService(OrderRepo(db), Mailer())141516def place_order_handler(service, request):17    return service.place(request.json)
  1. Line 2 Read __init__ first. It lists what this class depends on: a repository and a mailer.
  2. Line 6 The service: the business steps (save, then send a receipt). No HTTP in here, no SQL either.
  3. Line 12 A factory: it builds the service and plugs in the real parts. Tests can build one with fakes instead.
  4. Line 16 The handler: take the request, call the service, send the reply. If it grows, logic is hiding in the wrong place.

Take away

  • Handler takes the request, service does the steps, repository talks to the database.
  • A factory builds things, and a util should be small and plain.
  • Check what each object depends on, and who owns the data it holds.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.