Wize Software Engineering Textbook > System Implementation

Implementing Classes Based on Interaction and State Diagrams

Implementing State and Interaction Models

A class diagram tells you which classes, fields and methods exist. It does not tell you what happens inside the methods, or when they may be called. Two other UML models fill that gap. A sequence diagram fixes the order of calls between objects, and that order becomes the body of each method. A state machine diagram fixes how an object's response to a call depends on its history, and that becomes a state field and the checks around it. This lesson translates both into Java so that every line of code traces back to the model.

From messages to method bodies

Each lifeline in a sequence diagram is one object taking part in the interaction. It is drawn as a box with a dashed line running down the page. A solid arrow from one lifeline to another is a message, and in code a message is a method call. The method belongs to the class at the arrowhead. The call is written inside whichever method the sender is executing at that moment, which the sender's activation bar shows. Reading down one activation bar gives the statements of one method in order.


Diagram element

Java construct

Synchronous message to another lifeline

Call to a method declared in the receiver's class

Dashed return arrow

Return value, stored in a local variable or used directly

Self-message

Call to a method on this, usually a private helper

Create message

Constructor call with new

opt or alt fragment

if or if/else around the enclosed calls

loop fragment

for or while loop around the enclosed calls


Example: A Checkout lifeline sends pay(amount) to an Order. Inside that activation, the order sends charge(amount) to a PaymentGateway and receives a Receipt on the return arrow. It then sends itself recordReceipt(receipt). The model produces this method:


Java
public void pay(double amount) {
    Receipt receipt = gateway.charge(amount);
    recordReceipt(receipt);
}


The call gateway.charge compiles only if the order can reach a gateway. That reference can be a field, a parameter, or an object returned by an earlier message. If none of these exists, the interaction depends on a link the design never provided, and the fix belongs in the model as well as in the code.



From states and transitions to fields and guards

A state machine diagram lists the states an object can occupy, the events it receives, and the transitions between states. Each transition is labelled event [guard] / action. A guard condition is a Boolean test that must be true when the event arrives for the transition to fire. The action runs as the transition fires. Together, the transitions define a function from state-event pairs to next states:


δ:S×E→S,state-event cells=∣S∣×∣E∣\delta : S \times E \to S, \qquad \text{state-event cells} = |S| \times |E|


The code needs a decision for every cell, but a diagram draws only the meaningful ones. The order lifecycle below has 4 states and 3 events, so it has 12 cells. Only 4 cells are drawn, which leaves 8 that the code must handle by policy.


State machine diagram of an Order moving from Pending to Paid to Shipped, with cancel transitions from Pending and Paid to Cancelled.


To implement the diagram:

  1. Store the current state in a private enum field, initialised to the state that the initial arrow points to.
  2. Write one public method per event, and switch on the current state inside it.
  3. In each drawn case, test the guard, run the action, then assign the target state. If the guard is false, the transition does not fire and the state stays as it was.
  4. Send every undrawn cell to one consistent policy, such as throwing IllegalStateException.


Java
public class Order {
    private enum State { PENDING, PAID, SHIPPED, CANCELLED }

    private State state = State.PENDING;

    public void cancel() {
        switch (state) {
            case PENDING:
                state = State.CANCELLED;
                break;
            case PAID:
                refund();                   // transition action
                state = State.CANCELLED;
                break;
            default:
                throw new IllegalStateException("cannot cancel when " + state);
        }
    }
}


The pay method from the sequence example uses the same frame. Its case PENDING first tests amount >= total; only if that holds does it run the charge interaction from the sequence diagram and set state = State.PAID.


A state can also have its own actions. Its entry action runs on every transition into the state, and its exit action runs on every transition out of it. Put each one in a private helper and call that helper from every matching case. When a transition fires, UML runs the source state's exit action first, then the transition action, then the target state's entry action.



Choosing a structure for the state logic


Approach

Structure

Fits best when

Enum field with switch

One state field and one switch per event method

There are few states and little behaviour per state

State pattern

One class per state, with the object delegating each event to its current state object

There are many states, or states with substantial behaviour


The switch keeps the whole machine in one file, so you can check it against the diagram cell by cell. The State pattern moves each state's behaviour into its own class, so adding a state means writing one new class rather than editing every event method.

What to remember

  • Each message becomes a call to a method in the receiver's class, placed in the sender's current method in diagram order.
  • Fragments map to control flow: opt and alt become if statements, and loop becomes a loop.
  • A state becomes an enum constant or a State class, and an event becomes a public method.
  • Check the guard before running the action or changing state. Run the exit, transition and entry actions in that order.
  • Decide all ∣S∣×∣E∣|S| \times |E| cells, including the undrawn ones.

Example: Implementing a library copy's loan states

A library system models each physical book as a BookCopy object. Its state machine diagram has four states, AVAILABLE, ON_LOAN, ON_HOLD and LOST. It also has four events: checkOut, returnCopy, placeHold and reportLost. A new copy starts in AVAILABLE, and the diagram draws six transitions:

  • AVAILABLE to ON_LOAN on checkOut
  • AVAILABLE to ON_HOLD on placeHold
  • ON_HOLD to ON_LOAN on checkOut when the patron is the holder
  • ON_LOAN to AVAILABLE on returnCopy when the hold queue is empty
  • ON_LOAN to ON_HOLD on returnCopy when the hold queue is not empty, with the action notify next patron
  • ON_LOAN to LOST on reportLost, with the action charge replacement fee

The team's policy is that an event with no transition from the current state throws IllegalStateException. A sequence diagram details the notify next patron action:

  1. Desk sends returnCopy() to BookCopy.
  2. BookCopy sends isEmpty() to HoldQueue, which returns false.
  3. BookCopy sends next() to HoldQueue, which returns a Patron.
  4. BookCopy sends notifyReady(patron, this) to Notifier.

a) How many state-event cells must the class decide, and how many of them fall under the reject policy?


Count the states and events first. There are 4 states and 4 events, so the class must decide 4 × 4 = 16 state-event cells.


Next, place the six arrows in cells. The two returnCopy arrows both leave ON_LOAN on the same event with complementary guards, so they share ________ cell. The six arrows therefore occupy ________ cells.


That leaves 16 − 5 = 11 cells under the reject policy. Examples include returnCopy in AVAILABLE and placeHold in LOST. Each of these cells throws IllegalStateException.


A guarded cell needs the same decision when its guard is false. The cell for checkOut in ON_HOLD is occupied, but a checkOut by a patron who is not the holder fires no transition, so the team's policy rejects it with IllegalStateException as well rather than silently ignoring it.


b) Write the returnCopy() method, including the fields it needs.


The sequence diagram sends messages from BookCopy to two other lifelines. BookCopy therefore needs fields of type ________ and Notifier, while isEmpty, next and notifyReady are declared in those receiving classes. The fields are final, so a constructor must assign them; whoever creates the copy injects the two links it will message.


Java
public class BookCopy {
    private enum State { AVAILABLE, ON_LOAN, ON_HOLD, LOST }

    private State state = State.AVAILABLE;
    private final HoldQueue holds;
    private final Notifier notifier;

    public BookCopy(HoldQueue holds, Notifier notifier) {
        this.holds = holds;
        this.notifier = notifier;
    }

    public void returnCopy() {
        if (state != State.ON_LOAN) {
            throw new IllegalStateException("cannot return when " + state);
        }
        if (holds.isEmpty()) {
            state = State.AVAILABLE;
        } else {
            Patron next = holds.next();
            notifier.notifyReady(next, this);
            state = State.ON_HOLD;
        }
    }
}


The first test sends every state except ON_LOAN to the reject policy. The two transitions share one cell, so a single ________ on holds.isEmpty() chooses between them, and the guards cannot both be true. In the else branch, the statements follow the sequence diagram from top to bottom: next(), then notifyReady. The state is assigned last, because the transition action runs before the copy enters ON_HOLD.


c) A new copy receives these events in order: placeHold, checkOut by the holder, returnCopy with an empty hold queue, and reportLost. Give the state after each event, and identify any event that is rejected.


The copy starts in AVAILABLE. placeHold has a transition from AVAILABLE, so the state becomes ON_HOLD.


checkOut arrives in ON_HOLD, and the guard ________ is true, so the ON_HOLD transition fires and the state becomes ON_LOAN.


returnCopy arrives in ON_LOAN, where the guard ________ is true. The if branch fires and the state returns to AVAILABLE, with no notification sent.


reportLost has a transition only from ON_LOAN, and AVAILABLE has no reportLost transition. The fourth event is therefore rejected with IllegalStateException, and the copy stays in AVAILABLE. A unit test for this sequence checks one drawn path and one undrawn cell at the same time.

When you implement a design from its sequence and state machine diagrams, each diagram element maps to a particular code construct. Match each element to the construct that implements it.

Match each term
A.

Boolean test that must hold before a transition fires

B.

Call to a method declared in the receiving object's class

C.

Helper run by every transition that arrives in a particular state

D.

Call to a private helper method on this

E.

For or while statement wrapping the enclosed calls

F.

Value handed back to the caller and stored or used next

Return arrow

Guard condition

Entry action

Loop fragment

Synchronous message

Self-message

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A sequence diagram for a point-of-sale system shows three messages in order. First, Cashier sends scan(code) to Register. While that activation is open, Register sends lookUp(code) to Catalog, which returns a price. Finally, Register sends addLine(price) to itself. Where is lookUp declared, and where is it called?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A MediaPlayer class implements a state machine with states STOPPED, PLAYING and PAUSED, and it starts in STOPPED. The drawn transitions are STOPPED to PLAYING on play, PLAYING to PAUSED on pause, PAUSED to PLAYING on play, PLAYING to STOPPED on stop, and PAUSED to STOPPED on stop. Any event with no transition from the current state is ignored and leaves the state unchanged. The player receives the events in the table, in order. For each step, enter the state after the event, using the state names exactly as given, and whether a transition fired (yes or no).

StepEventState after eventTransition fired (yes or no)
1pause
2play
3play
4pause
5stop
6pause
7play

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors