April 4, 2007
UML Associations Demystified (Maybe)One of the toughest things in UML to get your head around is associations, roles and multiplicity. I could name some pretty senior UML practitioners (and even one or two UML "experts") - I won't, so don't worry if you think you might be one of them - who haven't really got the hang of it after the best part of a decade. So if you're struggling, don't worry - you're in good company.
Basically, role names are the equivalent of attribute names. The clue comes when we navigate along associations between objects. Navigations along associations read just like navigating to attributes with the same names as the roles at the far end of the association we're navigating along. That's because they mean pretty much the same thing.
If we write our Museum and Artifact classes in C# they might look like this:
When we specify a multiplicity like * (many), or any multiplicity greater than 1, we're just saying "it's a collection of objects of that type". The name of the collection is the role name. So myMuseum.exhibit referes to a collection of objects of type Artifact and the name of the collection is exhibit. In code, we could use an array or a suitable collection class to implement this association end.
When we navigate to collections, we must remember that they are collections. It's very, very easy to write expressions like:
myMuseum.exhibit.owner = myMuseum
Which doesn't make any sense if exhibit is a collection. Strictly speaking, myMuseum.exhibit.owner refers to the collection of all owners of all exhibits in myMuseum. For the same reason, in ASP.NET we wouldn't think to write:
session.Keys = "Jason"
Because session.Keys refers to a collection of objects, not to a specific object in that collection.
If the multiplicity of an association end is 0..1, that just means "optional". In programming terms, the object at this end of the relationship is allowed to be null (as opposed to * or 0..* which means that the collection can be empty).
Default Role Names
What happens when no role name is explicity specified at the end of an association? The default role name is simply the name of the class at that end, but beginning with a lower case letter.
Ambiguous Role Names
One thing to watch out for is situations where navigating in the direction of a role name would have ambiguous results.
What do we mean here, for example, when we write myAnimal.zoo? Which relationship are we talking about - the one between a zoo and all the animals it looks after, or the one between a zoo and its star attraction? Ensure that role names are unique as seen from the perspective of each class.
In a UML association, if there's an arrow, that tells us we can navigate along the relationship in that direction. A uni-directional association allows us to navigate one way only. A bi-directional association allows us to navigate in both directions along the association.
There you go: clear as mud!
Posted 14 years, 3 months ago on April 4, 2007