UML - association or aggregation (simple code snippets)
Asked Answered
D

4

5

I drives me crazy how many books contradicts themselves.

Class A {} class B {void UseA(A a)} //some say this is an association,
no reference is held but communication is possible
Class A {} class B {A a;} //some say this is
    aggregration, a reference is held

But many say that holding a reference is still just an association and for aggregation they use a list - IMHO this is the same, it it still a reference.

I am very confused, I would like to understand the problem.

E.g. here: http://aviadezra.blogspot.cz/2009/05/uml-association-aggregation-composition.html - what is the difference between Strong Association and Aggregation, in both cases the author uses a field to store the reference..

Another example: This is said to be Association:

enter image description here

And this is said to be Aggregration:

enter image description here

public class Professor {
  // ...
}

public class Department {
  private List<Professor> professorList;
  // ..

}

Again, what is the difference? It is a reference in both cases

Decompound answered 28/2, 2015 at 0:51 Comment(5)
Your "reference" is about UML navigability while UML aggregation is about "whole/part relationship"Sanctimony
It mentiones specifically that one case is the association while the other the aggregation.Decompound
Aggregation is a binary association. The association's property aggregation: AggregationKind determines the type. See "Figure 7.12 - Classes diagram of the Kernel package" in www.omg.org/spec/UML/2.4.1/Superstructure. If you need to use a "list" to hold the "reference" is determined by UML multiplicity. If the association is not UML navigable then there will be no "reference" at all. Some of the terms are orthogonal and some are special cases (subclasses). I'd recommend you to pick one good book (e.g. uml-diagrams.org) and use it to do somethingSanctimony
THanks. I tried but as I mentioned in the post, many books disagree on this point. Some say referencing an object in a field is an association, others say it is an aggregration. Like in the example I posted, what is the difference between the Professor and Course? I would be grateful for an answer.Decompound
No difference. Both Department-Course and Department-Professor are UML associations. At the same time both associations can be marked as UML aggregations (maybe even as UML compositions depending on the "business rules" at the particular university)Sanctimony
C
5

This question has been, and will be, asked many times in many different variants, because many people, including many high-profile developers, are confused about the meaning of these terms, which have been defined in the UML. Since the question has been asked many times, it has also been answered many times. See, e.g. this answer. I'll try to summarize the UML definitions.

An association between two classes is not established via a method parameter, but rather via reference properties (class attributes), the range/type of which are the associated classes. If the type of a method parameter is a class, this does not establish an association, but a dependency relationship.

It's essential to understand the logical concept of associations first, before looking at how they are coded. An association between object types classifies relationships between objects of those types. For instance, the association Committee-has-ClubMember-as-chair, which is visualized as a connection line in the class diagram shown below, may classify the relationships FinanceCommittee-has-PeterMiller-as-chair, RecruitmentCommittee-has-SusanSmith-as-chair and AdvisoryCommittee-has-SarahAnderson-as-chair, where the objects PeterMiller, SusanSmith and SarahAnderson are of type ClubMember, and the objects FinanceCommittee, RecruitmentCommittee and AdvisoryCommittee are of type Committee.

The association Committee-has-ClubMember-as-chair

An association is always encoded by means of reference properties, the range/type of which is the associated class. For instance, like so

class Committee { ClubMember chair; String name;}

In the UML, aggregation and composition are defined as special forms of associations with the intended meaning of classifying part-whole-relationships. In the case of aggregation, as opposed to composition, the parts of a whole can be shared with other wholes. This is illustrated in the following example of an aggregation, where a course can belong to many degree programs.

An example of aggregation

The defining characteristic of a composition is to have exclusive (or non-shareable) parts. A composition may come with a life-cycle dependency between the whole and its parts implying that when a whole is destroyed, all of its parts are destroyed with it. However, this only applies to some cases of composition, and not to others, and it is therefore not a defining characteristic. An example of a composition where the parts (components) can be detached from the whole (composite) and therefore survive its destruction, is the following:

enter image description here

Chopping answered 2/3, 2015 at 11:52 Comment(9)
UML is pretty clear about this - see page 112 of UML 2.5 spec (which I can't copy here as it's too long...).Heng
Very interesting answer. I have a few questions: 1. You suggest that the fundamental difference between a dependency and an association is that the former has method lifetime while the latter has object lifetime. Could you provide a paragraph supporting this in the last U.M.L. specification? 2. In the U.M.L. specification, since an association is not a specialization of a directed relationship, is an association always undirected? 3. What is the kind of the implicit relationship between an attribute and its class: shared aggregation, composite aggregation, or (non-aggregation) association?Carlinecarling
@Maggyero: 1. In UML, the term "Dependency" is used for many different kinds of directed relationships. I did not suggest that UML dependencies generally have "method lifetime". 2. As opposed to the mathematical concept of a relation, a UML association is always undirected in the sense that it supports both the relation expressed by its name (assuming it has one) and the inverse relation. If its has role names at both associatipon ends, you can read it in both directions. The question if it is implemented as a unidirectional or bidirectional association is independent of this reading directionChopping
3. In Philosophy, some people say that a class is a bundle/"aggregate" of properties/attributes, but this is not the same sense as using the term aggregation for a part-whole relationship.Chopping
1. Sorry my question was poorly formulated since as Martin Fowler stated, association implies dependency. I meant: is the difference between association and dependency that the former has object lifetime restriction while the latter does not have such restriction (and therefore can have method lifetime as well)?Carlinecarling
2. Okay so you mean that association is a symmetric relation, but with the symmetry property generalized to n-ary relations (i.e. it is a set of tuples containing any permutations of its tuples, in other words it is a set of sets). 3. Okay. 4. Why isn’t dependency defined as the parent of association and generalization in the element hierarchy of the UML specification since it is implied by them?Carlinecarling
@Maggyero: Associations are types that classify links between objetcs, therefore only links are bound to the lifetime of the participating objects.Chopping
@Maggyero: I guess, since an association is not a directed relationship, it cannot be subsumed under Dependency.Chopping
@GerdWagner Alright for the last comment. "only links are bound to the lifetime of the participating objects." Okay, but can these links have a shorter lifetime, for instance method lifetime, or they must have object lifetime?Carlinecarling
S
1

See Superstructures 2.1.1:

An association may represent a composite aggregation (i.e., a whole/part relationship). Only binary associations can be aggregations. Composite aggregation is a strong form of aggregation that requires a part instance be included in at most one composite at a time. If a composite is deleted, all of its parts are normally deleted with it. Note that a part can (where allowed) be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite. Compositions may be linked in a directed acyclic graph with transitive deletion characteristics; that is, deleting an element in one part of the graph will also result in the deletion of all elements of the subgraph below that element. Composition is represented by the isComposite attribute on the part end of the association being set to true.

Navigability means instances participating in links at runtime (instances of an association) can be accessed efficiently from instances participating in links at the other ends of the association. The precise mechanism by which such access is achieved is implementation specific. If an end is not navigable, access from the other ends may or may not be possible, and if it is, it might not be efficient. Note that tools operating on UML models are not prevented from navigating associations from non-navigable ends.

Your above examples are on different abstraction levels. Department/Course are concrete coding classes while Department/Professor are at some abstract business level. Though there is no good source (I know) explaining this fact, composition and aggregation are concepts you will use only on business level and almost never at coding level (exception below). When you are at code level you live much better with Association having role names on both sides. Roles themselves are a different(/redundant!) rendering of properties of a class that refer to the opposite class.

Aggregation as a strong binding between classes is used e.g. in database modeling. Here you can delete a master only if the aggregates have all been deleted previously (or vice vera: deleting the master will force deletion of the aggregates). The aggregate can not live on its own. The composition as in your example is (from my POV) a silly construct as it pretends to be some week aggregation. But that's simply nonsense. Then use an association. Only on a business level you can try to model (e.g.) machine parts as composite. On a concrete level a composition is a useless concept.

tl;dr;

If there is a relation between classes show it as simple association. Adding details like roles will aid when discussing domain details. Use of composition/aggregation is encouraged only when modeling on business level and dis-encouraged on code level.

Simplify answered 28/2, 2015 at 10:45 Comment(9)
Thanks, but it does not asnwer the question in the OP (in the examples I attached), implementation-wise. Association can be binary but why would it have to be aggregation? Can be just two classes knowing about each other.Decompound
Sorry for being so brief, but just 10 hours ago I answered almost the same question and it has subsequently been deleted. I'll edit my answer later.Simplify
For aggregation being binary, that would imply both classes know about each other. But I believe it is not necessary, Class A can have a reference to Class B (with B not knowing about that), would it not still be aggregation if it makes a whole? Having seen an example here (mppmu.mpg.de/english/kluth_oo_uml.pdf), the other class does not have to know...Decompound
Please be a bit patient. I'll try to finish the edit within an hour or so.Simplify
Sure, thank you very much. I am confused with the "binary only" constraint as many examples shows aggregation where the other class does not know about the "parent".Decompound
Well, but speaking about class diagram - composition is clearly implementable as having Class A create and own an isntance of Class B. Or just reference it as in association. In addition, both examples I from the same source and page so I believe the abstraction level is the same. You can see that for the Professor - Department, there is a code and it looks the same as for the first example, i.e. there is a list.Decompound
Yes. You can use aggr/comp. And if there is a real need: go ahead. But in almost all cases there is no real need to use it and you can simply live with association. Also note: UML is a model which says it can differ from reality. It focuses on certain (important) aspects.Simplify
Well, but it does not answer the code snippets question I posted. The latest book I just checked says that "two classes having reference to each other is association" but a class having a collection of other classes instances is aggregation. But this is pretty much the same (e.g. both can hol collections of each other's instances)...Decompound
The collection can simply be expressed as cardinality at the end of the association. A collection does not mean its an aggregation. That is simply nonsense.Simplify
C
1

I've written an article about the differences between UML Association vs Aggregation vs Composition based on the actual UML specification rather then interpretations of book authors.

The primary conclusion being that

In short, the Composition is a type of Association with real constraints and impact on development, whereas the Aggregation is purely a functional indication of the nature of the Association with no technical impact.

Navigability is a completely different property and independent of the AggregationKind.

Camion answered 2/3, 2015 at 7:38 Comment(0)
S
0

For one thing, UML is a rich language, meaning there is more than one way to describe the same thing. That's one reason you find different ways described in different books (and conflicting answers on SO).

But a key issue is the huge disconnect between UML and source code. How a specific source code construct is represented in UML, and vice versa, is not part of the UML specification at all. To my knowledge, only one language (Java) has an official UML profile, and that's out of date.

So the representation of specific source-language constructs are left to the tool vendors, and therefore differ. If you intend to generate code from your model, you must follow the vendor's conventions. If, conversely, you wish to generate a model from existing source code, you get a model based on those same conventions. But if you transfer that model to a different tool (which is difficult at the best of times) and generate code out of that, you won't end up with the same code.

In language-and-tool-agnostic mode, my take on which relationships to use in which situations can be found here. One point there worth repeating is that I don't use undirected associations in source-code models, precisely because they have no obvious counterpart in actual code. If in the code class A has a reference to class B, and B also has one to A, then I draw two relationships instead.

Superload answered 4/3, 2015 at 11:15 Comment(2)
Notice that If class A has a reference property with range B, and B also has one with range A, and they are the inverse of each other, this represents a bidirectional association, which is expressed in JPA e.g. with a @OneToMany(mappedBy="...") annotation.of the reference property.Chopping
Sure, it is possible to find examples of source language constructs that are actually bidirectional. But the overwhelming majority of reference-type constructs in the overwhelming majority of programming languages are unidirectional, and in that overwhelming majority of cases it is better to express two "mirror" references as two separate relationships.Superload

© 2022 - 2024 — McMap. All rights reserved.