Card 07/ 08

ExerciseDifficulty: Intermediate2 min

Practice: Drawing the Class Diagram for a Short Listing

A Python listing of four classes: draw the boxes and the arrows.

Drawing a class diagram from code is the reverse of reading one, and doing it checks that each mark and arrow means something precise to you. Below is a short Python listing of four classes. Draw a box for each with its visible members and their visibility, then draw every relationship with the right line and arrowhead.

Decide each relationship by looking at how one class gets hold of the other: by inheriting from it, by keeping it in a field, or by receiving it for one call. For a field, check where the object stored in it was created.

py
from abc import ABC, abstractmethod


class Shape(ABC):
    @abstractmethod
    def area(self) -> float: ...


class Square(Shape):
    def __init__(self, side: float) -> None:
        self.side = side

    def area(self) -> float:
        return self.side * self.side


class Drawing:
    def __init__(self) -> None:
        self._shapes: list[Shape] = []

    def add(self, shape: Shape) -> None:
        self._shapes.append(shape)

    def total_area(self) -> float:
        return sum(shape.area() for shape in self._shapes)


class Printer:
    def print_summary(self, drawing: Drawing) -> None:
        print(f"total area: {drawing.total_area()}")


small = Square(2.0)
drawing = Drawing()
drawing.add(small)
drawing.add(Square(3.0))
Printer().print_summary(drawing)
OutputRan with python:3.12-slim (Python 3.12.13)
total area: 13.0
Four classes and the lines that use them.
Show the diagram
The listing as a class diagram

Shape is abstract, because it inherits from ABC and marks area with @abstractmethod, so area is drawn in italics. Square inherits from it: a solid line with a hollow triangle, not a dashed one, because Shape is an abstract class rather than an interface.

Drawing holds its shapes in _shapes, so the field is private. The shapes arrive through add from outside, and small still exists after it is added, so the relationship is aggregation with a hollow diamond beside Drawing. Printer receives a drawing for one call and keeps nothing, so it has a dependency: a dashed line with an open arrow.

The diamond beside Shape instead of Drawing, or a filled one, are the two answers most often drawn.