LOW-LEVEL DESIGN · MODELING AND UML · UML · 18 OF 48

UML Use Case Diagrams: Actors, Include and Extend Explained

How to read and draw UML use case diagrams: primary and secondary actors, the system boundary, use cases as goals, include, extend and actor generalization, all on a clinic appointment system, plus how to use one in the first minutes of a design interview to fix the scope, with Java that turns each use case into a method.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 202 lines, with a small main() demo. Save it as ClinicUseCaseDemo.java, then run javac ClinicUseCaseDemo.java && java ClinicUseCaseDemo.

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * The clinic use case diagram as code: one service method per use case,
 * actors as roles whose permissions come from the association lines.
 */
public class ClinicUseCaseDemo {

    // ---- The problem: methods named after screen steps, not goals. ----
    // Who may call them? What goal do they finish? Nothing here says.
    static final class StepByStepClinicScreen {
        void openForm() { }
        void typePatientId(String id) { }
        void pickSlot(String slot) { }
        void clickSave() { }
    }

    // ---- The clean version: goals, roles and permissions. ----
    enum UseCase { BOOK, CANCEL, CHECK_IN, RECORD_CONSULT, PAY_BILL, VIEW_SCHEDULE }

    /** Actor generalization: a role inherits every use case of its parent. */
    enum Role {
        PATIENT(null, UseCase.BOOK, UseCase.CANCEL, UseCase.PAY_BILL),
        CLINIC_STAFF(null, UseCase.VIEW_SCHEDULE),
        RECEPTIONIST(CLINIC_STAFF, UseCase.BOOK, UseCase.CANCEL, UseCase.CHECK_IN),
        DOCTOR(CLINIC_STAFF, UseCase.RECORD_CONSULT);

        private final Role parent;
        private final Set<UseCase> own;

        Role(Role parent, UseCase first, UseCase... rest) {
            this.parent = parent;
            this.own = EnumSet.of(first, rest);
        }

        boolean can(UseCase u) {
            return own.contains(u) || (parent != null && parent.can(u));
        }
    }

    record Actor(String id, Role role) { }

    /** Secondary actors: outside systems the clinic calls. */
    interface SmsService {
        void send(String to, String text);
    }

    interface PaymentGateway {
        boolean charge(String reference, int amount);
    }

    /** One method per use case that an actor touches. */
    interface ClinicAppointments {
        String bookAppointment(Actor by, String patientId, String wantedSlot);
        String cancelAppointment(Actor by, String appointmentId);
        String checkIn(Actor by, String appointmentId);
        String recordConsultation(Actor by, String appointmentId, String notes);
        String payBill(Actor by, String appointmentId, int amount);
        List<String> viewSchedule(Actor by);
    }

    static final class Appointment {
        final String id;
        final String patientId;
        final String slot;
        String status = "BOOKED";

        Appointment(String id, String patientId, String slot) {
            this.id = id;
            this.patientId = patientId;
            this.slot = slot;
        }
    }

    static final class ClinicService implements ClinicAppointments {
        private final List<String> freeSlots = new ArrayList<>(List.of("10:00", "10:30"));
        private final Map<String, Appointment> appointments = new LinkedHashMap<>();
        private final List<String> waitlist = new ArrayList<>();
        private final SmsService sms;
        private final PaymentGateway gateway;

        ClinicService(SmsService sms, PaymentGateway gateway) {
            this.sms = sms;
            this.gateway = gateway;
        }

        /** Every association line becomes this check. */
        private void require(Actor by, UseCase u) {
            if (!by.role().can(u)) {
                throw new SecurityException(by.role() + " may not " + u);
            }
        }

        @Override
        public String bookAppointment(Actor by, String patientId, String wantedSlot) {
            require(by, UseCase.BOOK);
            if (by.role() == Role.PATIENT && !by.id().equals(patientId)) {
                throw new SecurityException("patients book only for themselves");
            }
            Optional<String> slot = findFreeSlot(wantedSlot);          // include: always runs
            if (slot.isEmpty()) {
                return joinWaitlist(patientId);                         // extend: only when full
            }
            freeSlots.remove(slot.get());
            Appointment a = new Appointment("A-" + (appointments.size() + 1), patientId, slot.get());
            appointments.put(a.id, a);
            sms.send(patientId, "booked " + a.id + " at " + a.slot);
            return "booked " + a.id + " at " + a.slot;
        }

        private Optional<String> findFreeSlot(String wanted) {
            if (freeSlots.contains(wanted)) {
                return Optional.of(wanted);
            }
            return freeSlots.stream().findFirst();
        }

        private String joinWaitlist(String patientId) {
            waitlist.add(patientId);
            return "day is full, " + patientId + " is number " + waitlist.size() + " on the waitlist";
        }

        @Override
        public String cancelAppointment(Actor by, String appointmentId) {
            require(by, UseCase.CANCEL);
            Appointment a = find(appointmentId);
            a.status = "CANCELLED";
            freeSlots.add(a.slot);
            return "cancelled " + a.id;
        }

        @Override
        public String checkIn(Actor by, String appointmentId) {
            require(by, UseCase.CHECK_IN);
            find(appointmentId).status = "CHECKED_IN";
            return "checked in " + appointmentId;
        }

        @Override
        public String recordConsultation(Actor by, String appointmentId, String notes) {
            require(by, UseCase.RECORD_CONSULT);
            find(appointmentId).status = "SEEN";
            return "notes saved for " + appointmentId + ": " + notes;
        }

        @Override
        public String payBill(Actor by, String appointmentId, int amount) {
            require(by, UseCase.PAY_BILL);
            boolean paid = gateway.charge(appointmentId, amount);
            return paid ? "paid " + amount + " for " + appointmentId : "payment failed";
        }

        @Override
        public List<String> viewSchedule(Actor by) {
            require(by, UseCase.VIEW_SCHEDULE);
            List<String> rows = new ArrayList<>();
            appointments.values().forEach(a -> rows.add(a.slot + " " + a.id + " " + a.status));
            return rows;
        }

        private Appointment find(String id) {
            Appointment a = appointments.get(id);
            if (a == null) {
                throw new IllegalArgumentException("no appointment " + id);
            }
            return a;
        }
    }

    public static void main(String[] args) {
        SmsService sms = (to, text) -> System.out.println("  [sms to " + to + "] " + text);
        PaymentGateway gateway = (ref, amount) -> {
            System.out.println("  [gateway] charged " + amount + " for " + ref);
            return true;
        };
        ClinicAppointments clinic = new ClinicService(sms, gateway);

        Actor patient = new Actor("P-17", Role.PATIENT);
        Actor desk = new Actor("R-2", Role.RECEPTIONIST);
        Actor doctor = new Actor("D-4", Role.DOCTOR);

        System.out.println("Patient: " + clinic.bookAppointment(patient, "P-17", "10:00"));
        System.out.println("Receptionist: " + clinic.bookAppointment(desk, "P-21", "10:00"));
        System.out.println("Receptionist: " + clinic.bookAppointment(desk, "P-33", "11:00"));
        System.out.println("Receptionist: " + clinic.checkIn(desk, "A-1"));
        System.out.println("Doctor: " + clinic.recordConsultation(doctor, "A-1", "mild fever, rest"));
        System.out.println("Patient: " + clinic.payBill(patient, "A-1", 500));
        System.out.println("Doctor (inherited from staff): " + clinic.viewSchedule(doctor));

        try {
            clinic.recordConsultation(patient, "A-1", "I feel fine");
        } catch (SecurityException e) {
            System.out.println("Refused: " + e.getMessage());
        }
    }
}

Notes

The problem

Here is the problem. The interviewer says: design a clinic appointment system. Most people start drawing classes at once. Twenty minutes later they learn that receptionists also book for walk in patients, that a full day needs a waitlist, and that payment was never in scope. The classes were fine, but for the wrong system. A use case diagram makes you ask these questions first, while changing your mind is still free.

Design a clinic booking app
  • questions nobody asked:
  • can a patient book alone,
  • or only the front desk?
  • what if every slot is full?
  • who checks the patient in?
  • does the doctor write notes
  • here, or somewhere else?
  • is payment in scope?
  • skip them, and you design
  • the wrong system, very well

The idea

The idea in one sentence: a use case diagram shows who interacts with the system and which goals they can reach with it. It has only a few pieces. Actors are stick figures outside the system. The system boundary is a box with the system name at the top. Use cases are ovals inside the box, each one a goal. Lines connect actors to the use cases they take part in. Three special relations, include, extend and generalization, add detail.

Five pieces
  • actor: a role outside the
  • system (stick figure)
  • system boundary: a box with
  • the system name on top
  • use case: a goal, drawn as
  • an oval inside the box
  • association: a line from
  • actor to use case
  • relations: include, extend,
  • generalization

Primary actors

Start with the primary actors. These are the roles that come to the system to get something done. Our clinic has three: the patient, the receptionist and the doctor. Notice that an actor is a role, not a person and not a job title in the company chart. A doctor who books her own check up is acting as a patient for that moment. Primary actors are usually drawn on the left side.

Secondary actors

Secondary actors are other systems that our system needs, but that do not come to it with a goal of their own. The SMS service sends booking reminders, and the payment gateway charges a card. They are outside our box, so they are actors, usually drawn on the right. Our own database is not an actor. It lives inside the boundary, because we build it and we own it.

Secondary (system) actors
  • SMS Service
  • sends booking reminders
  • Payment Gateway
  • charges the patient card
  • they do not start goals;
  • the system calls them to
  • finish a goal
  • not an actor: our own DB

Use cases are goals

Now the ovals. Each use case is a goal, named with a verb and a noun: book appointment, cancel appointment, check in patient, record consultation, pay bill. Use this test: when the actor finishes it, do they walk away with something of value? Booking passes. Click save, enter name, or open the form do not. Those are steps inside a goal. Even log in is usually a step, not a goal, because nobody visits a clinic app just to log in.

Goal, or just a step?
  • goals (good):
  • Book appointment
  • Cancel appointment
  • Check in patient
  • Record consultation
  • Pay bill
  • steps (not use cases):
  • Click save, Enter name,
  • Open form, Log in

Associations

Associations are plain lines from an actor to a use case. They say this actor takes part in this goal. The patient can book, cancel and pay. The receptionist can book and cancel too, for walk in or phone patients, and is the only one who checks a patient in. The doctor records the consultation. These lines are your first permission table, and later each one becomes an access check in the code.

Include

Include pulls out a piece that a goal always needs. Booking always has to find a free slot, so we draw find free slot as its own oval, and a dashed arrow from book appointment to it, labelled include in double angle brackets. The arrow points at the part being used. Include is useful when the same piece is shared, for example if rescheduling also needs to find a free slot. Think of it as a method call that always happens.

Extend

Extend is the opposite: optional behaviour that only runs under a condition. If the doctor has no free slot that day, the patient can join a waitlist. We draw join waitlist with a dashed arrow labelled extend, pointing from the extension back to book appointment. The base use case is complete without it, and it does not know about it. You can write the condition on a small note, like: day is full.

Include vs extend

The two are easy to mix up, so compare them. Include always runs, and the arrow goes from the base to the part it needs. Extend runs only sometimes, and the arrow goes from the extension back to the base, because the base does not depend on it. A quick check: if you delete the extra oval, is the base goal broken? If yes, it was an include. If no, it was an extend.

Include vs extend
  • include
  • always runs
  • arrow: base to part
  • base needs the part
  • extend
  • runs only if a condition
  • holds
  • arrow: extension to base
  • base works without it

Actor generalization

Actors can inherit, just like classes. Every staff member, receptionist or doctor, can view the day's schedule. Instead of two lines to that use case, we add a parent actor called clinic staff, connect it once, and draw a solid line with a hollow triangle from each child to the parent. The children get everything the parent can do, plus their own goals. Use this only when it removes real repetition.

Clinic Staff (parent actor)
  • use case: View day schedule
  • Receptionist is a Clinic Staff
  • Doctor is a Clinic Staff
  • both can view the schedule,
  • and each adds its own goals
  • one line to the parent
  • instead of two

The whole diagram

Here is the whole diagram. Primary actors on the left, the clinic system box in the middle, and secondary actors on the right. Booking includes finding a free slot, may be extended by the waitlist, and asks the SMS service to send a reminder. Paying a bill uses the payment gateway. Staff inherit the schedule view. Anything not inside the box, like insurance claims or lab reports, is now clearly out of scope.

Diagram to code

The diagram turns into code very directly. Each oval that an actor touches becomes one public method on a service interface, here called ClinicAppointments. The included use case becomes a private helper that is always called. The extend becomes a branch that runs only when the day is full. Each association line becomes a permission: before doing the work, the method checks that the caller's role is allowed this use case.

One method per use case
interface ClinicAppointments {
  String bookAppointment(Actor by, ...);
  String cancelAppointment(Actor by, ...);
  String checkIn(Actor by, String apptId);
  String recordConsultation(Actor by, ...);
  String payBill(Actor by, ...);
  List<String> viewSchedule(Actor by);
}
// include: a private helper, always called
// extend: a branch taken only if full

Actors as roles

Actors become roles. Each role lists the use cases it is connected to. The receptionist and the doctor name clinic staff as their parent, so the can method checks the role's own list first, then asks the parent. That is actor generalization in about ten lines. Because the permissions come straight from the association lines, the code and the diagram stay in step: add a line, add one entry.

Roles and permissions
enum Role {
  PATIENT(null, BOOK, CANCEL, PAY_BILL),
  CLINIC_STAFF(null, VIEW_SCHEDULE),
  RECEPTIONIST(CLINIC_STAFF, BOOK,
      CANCEL, CHECK_IN),
  DOCTOR(CLINIC_STAFF, RECORD_CONSULT);
  boolean can(UseCase u) {
    return own.contains(u)
      || (parent != null && parent.can(u));
  }
}

Run it

Watch the demo run one main goal per actor. The patient books the ten o'clock slot, and the SMS service sends a reminder for appointment A one. The receptionist checks the patient in. The doctor records the consultation notes. The patient pays five hundred rupees, and the gateway charges the card. Finally the patient tries to record consultation notes, and the service refuses, because there is no line between patient and that use case.

In the interview

In a design interview, use this diagram in the first few minutes to fix the scope. List the actors, including outside systems. For each, name two or three goals. Draw the box and say out loud what is outside it, like insurance and lab reports. Ask the interviewer to confirm. Then pick the one or two goals that matter most and design those in depth. The diagram becomes your contract for the rest of the round.

First five minutes
  • 1 list the actors, including
  • outside systems
  • 2 for each, two or three goals
  • 3 draw the box; say out loud
  • what is OUT of scope
  • 4 mark include and extend only
  • if they shape the design
  • 5 pick ONE goal to design
  • in depth
  • keep it to about 8 ovals

Common mistakes

Watch for the usual mistakes. The biggest one is drawing steps instead of goals, like click save or validate form. Another is joining ovals with arrows to show order. A use case diagram has no order; that belongs in a sequence or activity diagram. Do not put include on everything, do not make your own database an actor, and do not forget outside systems like payment. Name actors by role, and keep the diagram small.

Watch out for
  • steps as ovals: Click save,
  • Validate form, Open page
  • arrows between ovals to show
  • order (that is a flowchart)
  • include on everything
  • the database as an actor
  • forgetting outside systems
  • actors named after people
  • instead of roles
  • 40 ovals and no scope

Interview questions

What is a use case diagram used for?

It shows who uses a system and which goals they can reach with it, at a high level. It is mainly used to agree on scope and requirements before designing classes, and it shows no order of steps and no internal structure.

What is the difference between include and extend?

An include is behaviour the base use case always needs, drawn as a dashed arrow from the base to the included use case. An extend is optional behaviour that runs only under a condition, drawn as a dashed arrow from the extension back to the base, which is complete without it.

What is the difference between a primary and a secondary actor?

A primary actor starts a use case to reach its own goal, like a patient booking an appointment. A secondary actor is something the system calls to complete a goal, usually an outside system like a payment gateway or an SMS service.

Is the database an actor in a use case diagram?

Not if it is part of the system you are building, because actors are always outside the system boundary. An external system you do not own, such as a third-party records service, can be a secondary actor.

What makes a good use case name?

A verb and a noun that describe a goal the actor cares about, such as Book appointment or Pay bill. If finishing it does not give the actor something of value, like Click save or Enter name, it is a step inside a use case, not a use case.

What is actor generalization?

A child actor inherits all the use cases of a parent actor, drawn as a solid line with a hollow triangle pointing at the parent. For example, Receptionist and Doctor can both inherit View day schedule from a Clinic Staff actor.

How do you use a use case diagram in a low level design interview?

Spend the first few minutes listing actors and their main goals, draw the system boundary, and state what is out of scope. Get the interviewer to agree, then pick the most important goals to design in detail with classes and a sequence diagram.

How does a use case diagram map to code?

Each use case an actor touches usually becomes a public method on a service, and each association becomes a permission check for that role. Included use cases become shared helpers, and extends become conditional branches.