Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UML association and dependency

Tags:

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;
    }
}
like image 568
rafal Avatar asked Oct 10 '11 20:10

rafal


1 Answers

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 type B, 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.

enter image description here

As a rule of thumb, it's an aggregation if b gets initialized in A's constructor; it's a composition if it also gets destroyed in B's destructor (shared lifecycle). If neither applies, it's an attribute / directed association.

If b was not a member variable in A, and the local variable b was not operatoed on (no methods were called on it), then I would represent that as a dependency: A needs B, but it doesn't have an attribute of that type.

But f() actually calls a method defined in B. 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.

like image 191
Uffe Avatar answered Oct 09 '22 05:10

Uffe