2.5.12 Representing readonly Fields in Class Diagrams

Representing readonly Fields in Class Diagrams

A Wildcats Player has an identifier that should not be reassigned after initialization. The diagram needs to distinguish that restriction from private visibility.

Read the Code Before Drawing

This complete class uses a field initializer so no constructor knowledge is needed. Each instance stores this teaching value; it is not a unique-ID generator.

Source to translate
public class Player
{
    public readonly int TrainingGroup = 1;
    public int NumberOfTurns;
}
Rewrite the Meaning in Ordinary Words
The same design in ordinary words
Define a Player with a public TrainingGroup integer
Initialize TrainingGroup to 1 and restrict later reassignment
Also define a mutable public NumberOfTurns integer
Describe the two field contracts independently

These words describe the class contract, not a sequence of runtime actions. Identify the types, stored members, operation inputs and results, and relationships before choosing compartments and connectors.

Map the Source to Class Boxes and Connectors
Build the Diagram in Violet
  1. Create a class diagram in Violet and add Player.
  2. Enter the exact attribute +TrainingGroup : int {readOnly}. Keep the braces as annotation text in the diagram.
  3. On another line enter +NumberOfTurns : int. Do not apply the readOnly marker to this mutable field.
  4. Leave the operations compartment empty and do not underline either entry. The example introduces no constructor and no static member.
  5. Save and compare the two entries: one restricts reassignment after initialization; the other permits its value to change during training.
Compare the Completed Soccer Diagram

Compare this reference with the diagram you built in Violet. Layout may differ; the source meaning, labels, and relevant connections should agree.

Player has public TrainingGroup marked readOnly and a separately mutable NumberOfTurns field.
A field-level read-only restriction
  • New
  • Changed
  • Removed
Read the Contract One Part at a Time

NumberOfTurns can change during training. TrainingGroup cannot be reassigned by ordinary code after initialization. Later constructor lessons show another permitted initialization point.

Verify the Drawing Against the Source
Predict and Check a Small Change