1.3.8 Translating Sequence Diagrams Into C#

Video: Writing Code from Sequence Diagrams (33:07)
A Sequence Diagram Gives You an Ordered Call Plan

A UML sequence diagram shows:

  • the objects involved;
  • which object receives each message;
  • the method name;
  • the order of the interactions.

That makes it a useful guide for C# method-call structure.

Consider this conceptual interaction:

controller1 asks team1 to DisplayName. The message identifies the receiver and method; the method bar shows execution.
controller1 calls DisplayName on team1.
  • New
  • Changed
  • Removed

The message says:

The receiving object needs a class that defines the requested method. For this example, Team has one method:

class Team
{
    public void DisplayName()
    {
        System.Console.WriteLine("Wildcats");
    }
}

The message identifies team1 as the receiving object and DisplayName() as the method to run.

Translate the Receiver First

Now consider a nested interaction:

controller1 calls ShowTeamName on player1. Inside that method, player1 follows this.team to call DisplayName on team1.
controller1 calls ShowTeamName on player1, which calls DisplayName on team1.
  • New
  • Changed
  • Removed

Read the messages from top to bottom. First, controller1 calls ShowTeamName() on player1. While that method is running, player1 calls DisplayName() on team1.

The calling code creates the objects, connects the Player to the Team, and starts the first call:

Calling Code in controller1
Team team1 = new Team();
Player player1 = new Player();
player1.team = team1;

player1.ShowTeamName();

That call enters the Player method below. Its team field refers to the same team1 object:

Player Class
class Player
{
    public Team team;

    public void ShowTeamName()
    {
        this.team.DisplayName();
    }
}

Inside ShowTeamName(), this.team.DisplayName(); starts the second call in the diagram. It runs the Team method shown earlier, which displays Wildcats.

The controller starts the interaction; the Player method contains the nested call to the Team.

Match Calls to Methods that Already Exist in the Design

A message names a method that belongs to the receiving object's class:

The DisplayName message maps to team1.DisplayName() in C# and the existing void DisplayName method in Team.
DisplayName belongs to the receiving object's Team class.
  • New
  • Changed
  • Removed

Here, team1 is a Team object, and the Team class defines DisplayName(). The Player reaches that same object through its team field.

The diagram and code describe the same interaction: the receiver determines which object acts, and the message names its method.

Translation Means Preserving the Interaction

The goal is not line-for-line conversion of drawing geometry.

The goal is to preserve:

That is the common meaning shared by the UML sequence diagram and the C# source.