Search code examples
javaclassenumsumldiagram

How do I model enums in UML so they express a key-value relation?


I want to represent some key-value pairs in an UML enum type. For instance, lets say we have some elements and their symbol:

ROAD => 'R'
CAR => 'C'
NOTHING => ' '

In Java, it would be something similar to the following:

public enum AsciiCodes { 
    ROAD  ('R'),
    CAR ('C'),
    NOTHING (' ');

    private final char code;

    private AsciiCodes(char code) {
        this.code = code;
    }
}

How can I represent that in UML?

What I have so far:

enter image description here


Solution

  • In UML ROAD, CAR and NOTHING are EnumerationLiteral and in a class diagram they are shown in the compartment literals showing their name, and nothing more of them.

    An enumeration being a Datatype may have property, however the attribute code from your Java cannot be supported by a property as your did because it does not concern the enumeration but the EnumerationLiteral.

    Of course an EnumerationLiteral is not a property of the enumeration nor an instance of the enumeration, but an InstanceSpecification.

    So there is nothing the standard allowing to model code and its value for each enumeration literal until you extend the enumeration through a stereotype to add code as a StructuralFeature, in that case the values of code will be specified through a Slot

    In formal/2017-12-05 see :

    • § 10.5.3 Enumeration page 175
    • § 10.5.4 EnumerationLiteral page 175 and 176
    • § 9.9.9 InstanceSpecification page 140

    [edit]

    Alternative representation in UML inspired by the reading of Christophe's answer.

    An other way is to completely forget the UML EnumerationLiteral and to model each Java enumeration literal through a dedicated instance itself available through a static read-only attribute.

    AsciiCodes can be still an UML enumeration.

    enter image description here

    Note in your Java definition and above the value of code is unavailable from outside, then finally useless until an operation is added to return it as proposed in Christophe's answer.

    By the way this is how I still implement the enumerations in the API of the plug-out of BoUML for Java, using the stereotype enum_pattern specially managed by the Java code generator. I started to distribute BoUML in 2005 when the enumeration did not yet exist in Java.