What is the difference between association and dependency? Can you give code examples?
What is the relationship between class A and B?
class A
{
B *b;
void f ()
{
b = new B ();
b->f();
delete b;
}
}
uml
What is the difference between association and dependency? Can you give code examples?
What is the relationship between class A and B?
class A
{
B *b;
void f ()
{
b = new B ();
b->f();
delete b;
}
}
Best Answer
The short answer is: how any specific source language construct should be represented in UML is not strictly defined. This would be part of a standardized UML profile for the language in question, but these are sadly few and far between. Long answer follows.
In your example, I'm afraid I would have to say "neither", just to be difficult.
A
has a member variable of typeB
, so the relationship is actually an aggregation or a composition... Or a directed association. In UML, a directed association with a named target role is semantically equivalent to an attribute with the corresponding name.As a rule of thumb, it's an aggregation if
b
gets initialized inA
's constructor; it's a composition if it also gets destroyed inB
's destructor (shared lifecycle). If neither applies, it's an attribute / directed association.If
b
was not a member variable inA
, and the local variableb
was not operatoed on (no methods were called on it), then I would represent that as a dependency:A
needsB
, but it doesn't have an attribute of that type.But
f()
actually calls a method defined inB
. This to me makes the correct relationship a<<use>>
, which is a more specialized form of dependency.Finally, an (undirected) association is the weakest form of link between two classes, and for that very reason I tend not to use them when describing source constructs. When I do, I usually use them when there are no direct source code relationships, but the two classes are still somehow related. An example of this might be a situation where the two are responsible for different parts of the same larger algorithm, but a third class uses them both.