From diagram to code and back
After this: Write the school program from its diagram, and draw the diagram of a program from its code.
On this page · 6 sections · 3 checks
Lesson 3 drew the school as a plan: five boxes and five lines. A plan is only useful if you can build from it, and if you can draw one for code someone else wrote. This lesson goes both ways: from the diagram to code, and from code back to a diagram.
- Student inherits from Person
- Teacher inherits from Person
- School (1) is made of 0..* Classroom (composition)
- Classroom has 0..* Student (aggregation)
- Classroom is linked to 1 Teacher
From the diagram to code
Each part of the drawing becomes one kind of line in the code:
| In the diagram | In the code |
|---|---|
| a box | a class |
| a field line | a field the constructor fills |
| a method line | a method |
| solid line, triangle | class Student(Person):class Student extends Person |
| filled diamond | the whole calls the part's constructor in its own method |
| hollow diamond | the part comes in as an input and is added to a list |
| solid line, open arrowhead | a field holding another object that is not its part |
| dashed arrow | an input or a local variable only, nothing kept |
Here is the school written from the plan, with a few lines at the end that use it.
class Person: def __init__(self, name): self.name = name
def describe(self): return self.name
class Student(Person): def __init__(self, name, year): super().__init__(name) self.year = year
def describe(self): return f"{self.name} (year {self.year})"
class Teacher(Person): def __init__(self, name, subject): super().__init__(name) self.subject = subject
def describe(self): return f"{self.name}, {self.subject}"
class Classroom: def __init__(self, room, teacher): self.room = room self.teacher = teacher self.students = []
def add(self, student): self.students.append(student)
def roll_call(self): print(f"Room {self.room}, teacher {self.teacher.describe()}") for s in self.students: print(" " + s.describe())
class School: def __init__(self, name): self.name = name self.rooms = []
def open_room(self, room, teacher): r = Classroom(room, teacher) self.rooms.append(r) return r
school = School("Hill School")ana = Student("Ana", 2)ben = Student("Ben", 3)room = school.open_room(101, Teacher("Mr Rao", "Maths"))room.add(ana)room.add(ben)room.roll_call()print(len(school.rooms))Room 101, teacher Mr Rao, Maths Ana (year 2) Ben (year 3) 1
import java.util.ArrayList;import java.util.List;
class Person { protected String name;
Person(String name) { this.name = name; }
String describe() { return name; }}
class Student extends Person { private int year;
Student(String name, int year) { super(name); this.year = year; }
@Override String describe() { return name + " (year " + year + ")"; }}
class Teacher extends Person { private String subject;
Teacher(String name, String subject) { super(name); this.subject = subject; }
@Override String describe() { return name + ", " + subject; }}
class Classroom { private int room; private Teacher teacher; private List<Student> students = new ArrayList<>();
Classroom(int room, Teacher teacher) { this.room = room; this.teacher = teacher; }
void add(Student student) { students.add(student); }
void rollCall() { System.out.println("Room " + room + ", teacher " + teacher.describe()); for (Student s : students) { System.out.println(" " + s.describe()); } }}
class School { private String name; List<Classroom> rooms = new ArrayList<>();
School(String name) { this.name = name; }
Classroom openRoom(int room, Teacher teacher) { Classroom r = new Classroom(room, teacher); rooms.add(r); return r; }}
public class Main { public static void main(String[] args) { School school = new School("Hill School"); Student ana = new Student("Ana", 2); Student ben = new Student("Ben", 3); Classroom room = school.openRoom(101, new Teacher("Mr Rao", "Maths")); room.add(ana); room.add(ben); room.rollCall(); System.out.println(school.rooms.size()); }}Room 101, teacher Mr Rao, Maths Ana (year 2) Ben (year 3) 1
Read it class by class, with the diagram beside it:
Personkeeps a name and can describe itself.StudentandTeacherare built on it, which are the two triangles, and each writes its owndescribe.Classroomkeeps a room number, one teacher and a list of students. The teacher comes in through the constructor and stays in a field: the line with an open arrowhead. Students come in one at a time throughadd, made somewhere else: the hollow diamond.Schoolkeeps a list of rooms. Its method open_roomopenRoom callsClassroom(...)itself. That one call is the filled diamond.- The last lines make two students, open room 101 with Mr Rao as its teacher, add both students and call the roll. The school made one room, so the last line prints
1.
Watch who makes what
The trace below runs a short version of the school, with only the lines that matter here. Watch where each constructor frame opens. The task asks you to compare the classroom and the student.
- Run the programRun it and step through. Watch where each constructor frame opens. The Student frame opens from the program's own lines. The Classroom frame opens inside the school's open-room method. Then watch the student arrive in the classroom's list through add.
class Student: def __init__(self, name): self.name = name
class Classroom: def __init__(self, room): self.room = room self.students = []
def add(self, student): self.students.append(student)
class School: def __init__(self): self.rooms = []
def open_room(self, room): r = Classroom(room) self.rooms.append(r) return r
ana = Student("Ana")school = School()room = school.open_room(101)room.add(ana)print(len(school.rooms), len(room.students))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The Classroom frame opens on top of the open-room frame, because the school makes it. The Student frame opens from the program's own lines, and the student reaches the classroom later, as the input of add. The two diamonds are those two places in the code.
Run it
Python runs in the browser when you press Run on the block below. Java does not run here: if you are learning Java, step through the trace above instead, and paste the code into a Java tool on your computer when you want to run it for real.
Add a third student, or open a second room with a new teacher, and run it again. The diagram does not change: it describes the classes, not how many objects a run makes.
From code back to a diagram
To draw code someone else wrote, go through it in this order:
- One box for each class. Fill in the fields from the constructor and the methods from the method lines.
- For each class built on another, draw a solid line with a triangle at the parent.
- For each field that holds another object, ask who made that object. The class itself: a filled diamond. Someone else, and the objects are its parts, such as the students of a classroom: a hollow diamond. Someone else, and the class only knows about the object, such as a classroom's teacher: a solid line with an open arrowhead.
- For each input or local variable of another class that is not kept, draw a dashed arrow.
The lines at the bottom that use the classes get no box. In Python they sit outside every class.In Java they sit inside public class Main, which only starts the program; a diagram of the design leaves Main out.
The last check below asks you to do this for a short program.
Check yourself
The five school classes are the ones above. These lines open two rooms and call the roll in the second. What does this print?
school = School("Hill School")school.open_room(101, Teacher("Mr Rao", "Maths"))art = school.open_room(102, Teacher("Ms Iyer", "Art"))art.add(Student("Chen", 1))art.roll_call()print(len(school.rooms))School school = new School("Hill School");school.openRoom(101, new Teacher("Mr Rao", "Maths"));Classroom art = school.openRoom(102, new Teacher("Ms Iyer", "Art"));art.add(new Student("Chen", 1));art.rollCall();System.out.println(school.rooms.size());The diagram has a filled diamond at School: the school makes each classroom itself. Complete the missing line of open_roomopenRoom, so that it makes the classroom and the next lines can store it and return it.
class School: def __init__(self, name): self.name = name self.rooms = []
def open_room(self, room, teacher): ____________________ # ← make the classroom self.rooms.append(r) return rclass School { private String name; List<Classroom> rooms = new ArrayList<>();
School(String name) { this.name = name; }
Classroom openRoom(int room, Teacher teacher) { ____________________ // ← make the classroom rooms.add(r); return r; }}Draw this program in your head. How many boxes and how many lines does its class diagram have, and which kinds of line?
class Animal: def __init__(self, name): self.name = name
class Dog(Animal): def speak(self): return self.name + " says woof"
class Vet: def check(self, animal): print("checking", animal.name)
class Shelter: def __init__(self): self.dogs = []
def take_in(self, dog): self.dogs.append(dog)
rex = Dog("Rex")shelter = Shelter()shelter.take_in(rex)Vet().check(rex)print(rex.speak())import java.util.ArrayList;import java.util.List;
class Animal { protected String name;
Animal(String name) { this.name = name; }}
class Dog extends Animal { Dog(String name) { super(name); }
String speak() { return name + " says woof"; }}
class Vet { void check(Animal animal) { System.out.println("checking " + animal.name); }}
class Shelter { private List<Dog> dogs = new ArrayList<>();
void takeIn(Dog dog) { dogs.add(dog); }}
public class Main { public static void main(String[] args) { Dog rex = new Dog("Rex"); Shelter shelter = new Shelter(); shelter.takeIn(rex); new Vet().check(rex); System.out.println(rex.speak()); }}Drawing tools
- Write each part of a diagram as code: a box as a class, a triangle in the class line, a filled diamond as a constructor call inside the owner's method.
- Recognise a hollow diamond in code: the part comes in as a method input and is added to a list.
- Watch in a trace where each object is made, and use it to tell composition from aggregation.
- Draw a diagram from code in four passes: boxes, triangles, fields that hold other objects, then inputs that are not kept.