Use Associations for Classes and Attributes for DataTypes
Make an informed choice between Attributes and Associations when modeling a relation between two Classifiers.
When modeling the structure of your system there are basically two ways to express a structural relationship between two Classifiers. You could use an Association between the two Classifiers, or you could create an Attribute owned by one Classifier with it’s type set to the other Classifier.
Both ways, Association or Attribute are pretty much equivalent. There’s not really a big difference between the two except for personal preferences.
To explore the details of the two approaches it is best to have a look at the UML meta model.
In this meta diagram we see that both the Attribute as the Association use the same Property object to link to a type.
The association has two or more Properties as MemberEnd. Each of these Properties has a Type, so that is the way the association links two or more Classes. The derived link from Association to EndType is derived from the type of the Properties in the memberEnds.
The Attribute of a class is in fact a Property in the ownedAttributes of a class. Again through the fact that a Property is a TypedElement an thus has a Type as “type” we get the relation to another Classifier.
In the years I’ve been working with different modelling teams I’ve found that the rule that works best is to use Associations for Classes and Attributes for DataTypes.
Now whats the difference between a Datatype and a Class? Well, they are actually pretty similar. The UML specification states:
A data type is a special kind of classifier, similar to a class. It differs from a class in that instances of a data type are identified only by their value.
So that means that DataTypes are much like the primitive types and enumerations we know in the programming world. This concept is generally referred to as being immutable. So you can think of things like Integer, Date, MoneyAmount, but also enumerations such as Color, DayOfTheWeek etc..
If we add Datatype and Enumeration to the meta diagram we get following
You can see that DataType is a subtype of Classifier, and that Enumeration is a subtype of Datatype.
Following example shows how to use Classes and Datatypes when following this best practice.
In this diagram we see two Enumerations: Currency and ProductCategory. ProductCategory is being used as the type of the attribute Product.Category while Currency is being used by the Datatype MoneyAmount.
I’ve added dependencies to visually express which Datatype is being used by which Classifier, but those dependencies are usually not there in a production model.