Composition: A class can have references to objects of other classes as members. This is called composition and is sometimes referred to as a has-a relationship.
By Deitel P.J., Deitel H.M. - Java How to Program 9th Edition.
This viewpoint is discussed in this topic:
Prefer composition over inheritance?
Composition: Composite aggregation (composition) is a "strong" form of aggregation with the following characteristics:
*it is binary association,
*it is a whole/part relationship,
*a part could be included in at most one composite (whole) at a time, and
*if a composite (whole) is deleted, all of its composite parts are "normally" deleted with it.
Found on http://www.uml-diagrams.org/composition.html
(actually, Deitel presents UML examples following this idea, in the same book, but did not bother to explain the difference).
This viewpoint is discussed in this topic:
What is the difference between association, aggregation and composition?
Fine, BOTH ARE CORRECT. And this introduces the problem of homonym concepts.
For instance: don't draw a UML model with composition arrows to exemplify the first definition: In UML, any association is a composition by Deitels' the first definition.
Here are some aspects of my question that may help in the correct answer:
How I can say (and know) which composition are we talking about?
Where we draw the line between the two definitions (in contextual terms)?
Can I say that the first is object oriented programming and the second is software engineering/modeling?
Is the UML composition a model-only concept/jargon?
Is the UML composition an UML exclusive thing? or is also applied in the programming field?
How to avoid miscommunication of "what composition are we talking about" in a team?
Please, answer with references, evidences, it is not a philosophical/opinion problem, it is a "scope" problem that I´m trying to address.
And it is not "what is composition" question.
Edit: I´m thinking if the distinction is verb x adjective: "to compose" a class (first def.) and "a composite relation" (second def.).
I found it hard to explain the difference between UML association and implementation references without explaining at least a little bit what UML associations actually are, and what they can do, so here we go.
Association & Link
Lets start by looking at what a UML Association and a link (Association's instance) are.
[11.5.3.1] An Association specifies a semantic relationship that can occur between typed instances.
[11.8.1.1] A link is a tuple of values that refer to typed objects. An Association classifies a set of links, each of which is an instance of the Association. Each value in the link refers to an instance of the type of the corresponding end of the Association.
So the following is a valid implementation of a limited association.
class Brain { }
class Head { }
a = new Brain;
b = new Head;
link = (new Array).add(a).add(b);
Ownership
[9.5.3] When a Property is owned by a Classifier other than an Association via ownedAttribute, then it represents an attribute of the Classifier.
(Note: Class is a subclass of a Classifier.)
Navigability
[11.5.3.1] An end Property of an Association that is owned by an end Class or that is a navigableOwnedEnd of the Association indicates that the Association is navigable from the opposite ends; otherwise, the Association is not navigable from the opposite ends. Navigability means that instances participating in links at runtime (instances of an Association) can be accessed efficiently from instances at the other ends of the Association. The precise mechanism by which such efficient 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.
Why are those concepts relevant? Imagine the following example.
We see that brain is an attribute of Head class (the black dot signifies ownership by the opposite Class), and that it is navigable (the arrow).
We also see that head is NOT an attribute of Brain (no black dot ⇒ not owned by the Brain class ⇒ not an attribute of Brain), however it is still navigable. This means that in UML the head Property is held by the association itself.
The implementation could, for example, look like this (the association itself is represented by a tuple of two references (see link description earlier)).
class Head {
public Brain brain;
}
class Brain {
}
h = new Head;
b = new Brain;
h.brain = b;
link = (new Array).add(h).add(b);
So as you hopefully start to see, UML association is not such a simple concept as a has-a relationship.
Composition
Lets add another piece, composition.
[11.5.3.1] A binary Association may represent a composite aggregation (i.e., a whole/part relationship). Composition is represented by the isComposite attribute
[9.9.17] The value of isComposite is true only if aggregation is composite.
With the aggregation being
none - Indicates that the Property has no aggregation semantics.
shared - Indicates that the Property has shared aggregation semantics. Precise semantics of shared aggregation varies by application area and modeler.
composite -- Indicates that the Property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects
Again we see, that a UML association is explicitly specifying concepts that are hard to perceive from implementation (e.g. who is responsible for object management/destruction).
Model Composition vs Object Implementation Composition
So from the description above we can construct a more precise description of what an implementation composition (has-a relationship) would be.
[Deteils] Composition: A class can have references to objects of other classes as members. This is called composition and is sometimes referred to as a has-a relationship.
McConnell [Code Complete 2, 6.3] also refers to has-a relationship as a Containment.
Neither of them however talk about HOW the objects (container-contained, composer-composite) are related to one another, who is responsible for lifecycles, or whether the contained element knows about the container.
So just by saying that objects have a has-a relationship (and call it composition), you could actually mean any of these (and several more)
So if you call something composition in programming, you can mean pretty much any relationship/reference (or rather not an inheritance), so the word by itself is not very useful.
In UML on the other hand you are trying to capture all such information about how the objects are related to one another. Therefore there's a focus on giving terms a more precise meaning. So when you call something composition in UML you have in mind a very specific has-a relationship, where the container is responsible for the lifecycle of the contained items.
Implementation of UML associations
All those extra concepts information mean that there is really no precise way how to even implement associations. This makes sense as the implementation would depend on the target programming language or environment (e.g. executable models, where the UML concepts are used as the final product).
As an example I can recommend a paper describing UML association implementation in Java with enforced concepts such as multiplicity, navigability, and visibility Implementing UML Associations in Java.
More subquestions
How I can say (and know) which composition are we talking about?
By context, or you can just ask (which is always a good thing to do when unsure). Personally I've heard the use of composition as "has-a relationship" only when differentiating from inheritance; and in the rest in terms of UML. But then again I am in academia, so my view is biased.
Where we draw the line between the two definitions (in contextual terms)?
As the "programming" term composition doesn't actually mean anything (only that it is has-a), I'd recommend drawing the line yourself and pushing others to use more precise terminology.
Can I say that the first is object oriented programming and the second is software engineering/modeling?
More or less, with all the nuances mentioned in this answer.
Is the UML composition a model-only concept/jargon?
Is the UML composition an UML exclusive thing? or is also applied in the programming field?
No, you can use it in programming to mean the same thing as it means in UML, but you might need to state it more obviously. E.g. "This class is a composite for those classes, because it manages their lifecycle.".
The point is to teach people to differentiate between regular-old has-a relationships, and relationships that have more precise semantics.
How to avoid miscommunication of "what composition are we talking about" in a team?
This is a very broad question that you could apply to any term to which you want attach special meaning (what even is software engineering?), and there is no best way. Have a team-shared vocabulary (you are probably already having a lots of specific terms in your domain), and guide people to use more precise terminology.
numbered quotes refers to sections in UML 2.5 Specifications.
To cite the UML 2.5 specification on page 110:
Sometimes a Property is used to model circumstances in which one instance is used to group together a set of instances; this is called aggregation. To represent such circumstances, a Property has an aggregation property, of type AggregationKind; the instance representing the whole group is classified by the owner of the Property, and the instances representing the grouped individuals are classified by the type of the Property. AggregationKind is an enumeration with the following literal values:
none: Indicates that the Property has no aggregation semantics.
shared: Indicates that the Property has shared aggregation semantics. Precise semantics of shared aggregation varies by application area and modeler.
composite: Indicates that the Property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (see the definition of parts in 11.2.3).
Personally I see it the way that notion of a composite aggregation is about object lifetime, not about static relation. A composite aggregation kills aggregate members when their parent dies. None leaves this open. And shared aggregation is a bastard that OMG should not have introduced at all since it's semantics is domain dependent.
Related
The above statement is taken from www.uml-diagrams.org section Assocation ends from the rather beginning.
Is there a real-world example for this?
What exactly means owned by association itself?
What is association class or how is it implement in code?
Here's my attempt. I also was unsure about the nature of an association in the past and until not so long ago where I sort of grasped it. For the full pain you have to go through pp. 197 of UML 2.5 (11.5 Associations)
What is an association?
When you have a number of classes (we may call them A, B, etc. here for brevity. They are designed to be somewhat self-consistent. So you have properties and operations which work with the latter. If our A is some mathematical class you may have a well working black box. Fine.
Now, when any class is in need of another (e.g. the B class needs objects of type A to have that math toolbox handy) you create some reference. In a programming language that will be some variable holding a reference to an instance of the needed class. That's the moment where you have an association.
In UML you can denote such an association as a property typed with the other class. Or (!) you draw a line for an association between both class boxes and place the role name towards the referenced class (telling the name of the variable the programmer shall use). This being quite simple got me some headaches since I saw notations with both property and role notation. I have not fosteres the UML spec as tho what this would mean, but I established a rule I was also teaching that this is not allowed. Tools like EA do not support roles in a correct way which forces you to manually maintain your diagrams. That is, if you have an association role from B to A and the diagram does not contain A then you should show the role as property (see my note about dot notation below). But once you place A on that diagram you should see the assocation line with the role name, but not the property (pretty confusing I admit).
Note: Dot notation
Since UML 2.5 (or was it 2.1?; but see p. 200 of UML 2.5) the OMG guys introduced the so called dot notation. That is, you have a little dot at the association line end along where the role name is. This dot indicates that the role name is actually the property of the referencing class. Pretty much what I was talking about above. And what I thought was the intention. So, I have no idea what a not-owned property would be in any case. May be a good question to be asked.
Associaton class
Assume you have class C which reflects some kind of relation between A and B (and eventually D, E, etc.). Doing that makes it an association class. It's doing that by exactly the same technique as above, just for multiple classes. (If a class has multiple relations to other classes it's not necessarily an association class, but only if it's main purpose is to set these into some relation. YMMV)
So here you have the case where an association owns the role since you have a real object. The association explained above exists only as a reference in the programming world, not a complex storage structure like an association class.
First of all, you should understand that, as opposed to the explanation of #qwerty_so, in data/information modeling, relations between two objects (called "links" in UML) are a first-class citizen. Logically/conceptually, they exist next to objects. In terms of OO implementation, they may exist either within one or both of the two participating objects in the form of object references, or outside of the two participating objects in the form of another object representing the "link".
Likewise, in data/information modeling, an Assocation, which classifies "links", is a first-class citizen that logically/conceptually exists next to the involved Classes. A binary Assocation is implementated either within one or both of the two (Java/C#/JS/etc.) classes involved in the form of a reference property (or possibly two mutually inverse reference properties), or outside of the two classes in the form of another class representing the Assocation.
In the case where a binary association has one ownership dot at one of its ends, it is unidirectional and implemented as a reference property in the corresponding class, while in the case where it has ownership dots at both of its ends, it is bidirectional and implemented as two mutually inverse reference properties, one in each of the involved classes.
What exactly means owned by association itself?
An Assocation End of a binary Assocation can be owned either by the Class on the opposite side or by the Assocation itself. In the former (more common) case, the Assocation End corresponds to a reference property of the (Java/C#/JS/etc.) class on the opposite side. In the former (less common) case, the Assocation End corresponds to a reference property of the (Java/C#/JS/etc.) class that represents the Assocation.
In principle, there could be an OOP language that supports Assocations as first-class citizens, having a keyword "assocation", in addition to "class".
What is association class or how is it implement in code?
The need for an Association Class arises when the "links" of an Association have to be characterized with the help of attributes, or when they have to be processed with the help of special operations. In such a case, an Association Class allows defining these attributes or operations. An Association Class is implemented in the form of a (Java/C#/JS/etc.) class that has corresponding reference properties for each of the Association's ends.
This question already has answers here:
What is Navigability in UML diagrams?
(2 answers)
Closed 2 years ago.
Let's consider Book class and Chapter class.
Class Book {
private Chapter chapter;
}
Class Chapter {
}
Statement 1: If Book contains Chapter, this is a composition, since destroying Book would also destroy Chapter
Statement 2: Since Book is associated with and aware of Chapter, it can also be navigability.
So, are both statements correct, I know statement 1 is correct, but I am not sure if statement 2 is precise.
There is composition and composition
The same term "composition" is used to refer to very different things:
object composition, which is an OOP technique, making one object to be made (composed) out of several other objects and values.
UML composition, which is a kind of association where one object can be part of maximum one composite object at a time, and the composite has the responsibility for the existence and storage of the component. So it's an exclusive ownership.
By the way, the Wikipedia article is misleadingly incomplete about UML notation for object composition, at the date of this answer: it completely misses the point that object composition could implement a simple association
Your case is object composition
In your example, you use object composition, with a composite Book and a component object Chapter (hint: make it a container to get your example more realistic)
There is no guarantee that it's UML composition: For example, if this code would be implemented in Java, a Book book could have a private Chapter chapter. But some method of the book, say getChapter(), could leak the private chapter to another object. Since java classes are reference objects, the chapter would therefore not be guaranteed to exist in at most one composite, which is an UML requirement for UML composition. Moreover, in such case, a chapter may survive a book.
Advice: unless you are sure of an exclusive ownership, avoid UML composition. In case of doubt, model a simple association.
Navigability
Navigability is orthogonal to the kind of association. Navigability exist for composition, aggregation, and simple association. It means that you can easily move from the instance of one class to an associated instance of the other class.
In your case:
You can clearly navigate from composite book to a component chapter (as easy as book.chapter).
However, there is no evidence of a backward navigation: so when you have a specific chapter, without knowing the book in which it is included, it's not possible to find back the associated book.
It's pretty strange to see all those answers about composition/aggregation/association.
Who/What is the source of those notions?
geeksforgeeks
wikipedia?!?!
stackexchange
and finally my lovely stackoverflow (at least I glad that answers were not marked as verified)
What is the difference between association, aggregation and composition?
What is the difference between aggregation, composition and dependency?
There is a great book "Design Patterns"
GoF
It describes two most common techniques for reusing functionality in object-oriented systems:
1) class inheritance (is-a)
2) object composition (has-a)
"Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality."
"Composition" is a very descriptive term to express relationship between objects unlike "Association".
Why all those sources above use term "Composition" in the wrong way?!
Let's go further.
Objects could be composed in two ways:
1) Aggregation
2) Acquaintance
"Consider the distinction between object aggregation and acquaintance and how differently they manifest themselves at compile- and run-times. Aggregation implies that one object owns or is responsible for another object. Generally we speak of an object having or being part of another object. Aggregation implies that an aggregate object and its owner have identical lifetimes."
aggregate object and its owner have identical lifetimes!!!
"Acquaintance implies that an object merely knows of another object. Sometimes acquaintance is called "association" or the "using" relationship. Acquainted objects may request operations of each other, but they aren't responsible for each other. Acquaintance is a weaker relationship than aggregation and suggests much looser coupling between objects."
"It's easy to confuse aggregation and acquaintance, because they are often implemented in the same way. In Smalltalk, all variables are references to other objects. There's no distinction in the programming language between aggregation and acquaintance. In C++, aggregation can be implemented by defining member variables that are real instances, but it's more common to define them as pointers or references to instances. Acquaintance is implemented with pointers and references as well."
Guys, please, help me to figure out what's going on here...
Yes, there is lot of confusion around for these two terms Composition and Aggregation [There is More to add Shared and non-shared Aggregation]. After going through a lot of confusion and getting biased towards UML resources, I have formed my view as follows [need not be taken as final or accurate].
A simplest and loosely coupled relationship I take is Association [it can be unidirectional or bidirectional] where an Object has a reference of other object but both live independently. Association can be Qualified Association if its connected by specific Identity [In OO, identity is an important part of every entity object] e.g. accountNumber for Account of Customer.
Aggregation is collection (of other object types and can be assembled for restricted purpose) maintained by an Object. Still both the objects live independently. e.g. Athletics team. Same student can be part of many such teams like Cycling team [aggregates] and so on. Deleting Athletics team makes no harm to each student entry in college records [they still exist]. Such a relationship can be maintained as Collection of students on Team side or reference of Athletics team for each student being part of team. It depends on more frequently required navigability for application.
Composition is more tight relationship where container object completely holds the contained object and contained object does not have any meaning outside relationship with container object. I can see an example as relationship between Person and Address where for each person we keep separate/ fresh entry of address. For family members Address may have same logical equality, but never physical equality. Change of address for one member does not affect other members [simple test is - DB columns for Person record has extended columns for address as a part of person table.] another example is Single entry (row) of item purchase and Complete bill of items. where deleting bill makes each entry context-less.
If an object instantiates and contains another object completely [never allows outside world to obtain its ref by any means] I would take that as Composition. Techniques like Cloning objects at interaction points instead of passing same ref can be helpful here. In case of association or aggregation, we exchange same reference.
Containment being black-box reuse, is preferred over white-box kind of reuse (implemented using inheritance). Most of the GOF patterns suggest best combinations of Containment for reuse and inheritance for polymorphism. e.g. In case of Adapter pattern, Object Adapter is preferred over Class Adapter.
Implementing all these flavors in Java (Implementations will be language specific) has its own challenge and NOT very straight forward, especially composition. There is a point on learning curve, where one feels (at least I felt) Composition is same as inner class, inner class can help us implement it, but simply having inner class does not give any guarantee of composition.
Can composition be bidirectional in a way that both classes are aware of each other?
And if not, what is the default direction of composition?
You should distinguish navigability and aggregation. Arrow and diamond.
Arrow A->B means only that B is reachable from A in some simple way. If A contains a composition of B, it means that
the composite object has responsibility for the existence and storage
of the composed objects (parts).
(citation from OMG Unified Modeling Language TM (OMG UML) - p.109)
So, can composition have bi-directional navigability?
Yes. It is quite normal.
If, for example, you have decided to destroy B in some of its functions, you MUST reach A and destroy it from there. So, composition has bi-directional navigability often enough. Notice, that bi-directional navigability, according to both current and coming UML standards, is shown as line without arrows on both sides. Both-sided arrow is deprecated. THAT is the reason you won't see it often.
Can the composition itself be bi-directional? Can we see black diamonds on both sides of an association?
No, of course this sort of association cannot be mutual, for it is impossible for B to be created in A only and, simultaneously, for A to be created in B only.
What is interesting, the shared aggregation (empty diamond) cannot be mutual, too, but here the limitation is not inherent, it is simply forbidden by UML standard.
Yes, Composition does not add constraints with regards to the navigability of the association.
More info on the difference between Accociation, Composition and Aggregations can be found here: UML Composition vs Aggregation vs Association
From https://www.lucidchart.com/pages/uml/class-diagram:
Bidirectional associations are the default associations between two classes and are represented by a straight line between two classes. Both classes are aware of each other and of their relationship with each other. In the example above, the Car class and RoadTrip class are interrelated. At one end of the line the Car takes on the association of "assignedCar" with the multiplicity value of 0..1 which means that when the instance of RoadTrip exists, it can either have one instance of Car associated with it or no Cars associated with it. In this case, a separate Caravan class with a multiplicity value of 0..* is needed to demonstrate that a RoadTrip could have multiple instances of Cars associated with it. Since one Car instance could have multiple "getRoadTrip" associations-- in other words, one car could go on multiple road trips--the multiplicity value is set to 0..*
In the past I had the same opinion as Gangnus with
So, can composition have bi-directional navigability?
But following some recent discussion I had a more detailed look into the UML specs. And simply, that statement is not true (only partially). Let's look into the UML 2.5 specs. On p. 110 it is stated
Sometimes a Property is used to model circumstances in which one instance is used to group together a set of instances; this is called aggregation. To represent such circumstances, a Property has an aggregation property, of type AggregationKind; the instance representing the whole group is classified by the owner of the Property, and the instances representing the grouped individuals are classified by the type of the Property. AggregationKind is an enumeration with the following literal values:
[omitting shared aggregation]
composite: Indicates that the Property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (see the definition of parts in 11.2.3).
Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it.
Note my emphasis on the object/instance in the above text. So UML just talks of responsibility. If A composes B it will be responsible to delete B when it is destroyed itself. Vice versa B would be responsible for A's destruction. So, if you have references in both directions (i.e. diamonds on both sides) then you will be reponsible to delete the object on the other side. This of course works only if just one of both holds a reference to the other. If both would have a reference, it would not be possible to have a directed responsibility (because it's circular).
I still think that having composite aggregation on both sides is not really a good idea. But according to the specification it is possible.
I am reviewing my knowledge in object-oriented programming. Under the relationship between classes topic, I have encountered some relationships which are a bit ambiguous to me.
I know dependency "uses-a" and inheritance "is-a" but I'm a bit unfamiliar with Aggregation, Composition, Association and Direct Association; also, which of them is "has-a" relationship. Some use Aggregation interchangeably with Association.
What is Direct Association? Also, what is Composition? In UML diagrams, the arrows that represents them are different. I would be really thankful if you could clear these things out for me.
Please note that there are different interpretations of the "association" definitions. My views below are heavily based on what you would read in Oracle Certification books and study guides.
Temporary association
A usage inside a method, its signature or as a return value. It's not really a reference to a specific object.
Example: I park my Car in a Garage.
Composition association
A so-called "STRONG relationship": The instantiation of the linked object is often hard
coded inside the constructor of the object. It cannot be set from
outside the object. (Composition cannot be a many-to-many
relationship.)
Example: A House is composed of Stones.
Direct association
This is a "WEAK relationships". The objects can live independent and there are usually setters or other ways to inject the dependent objects.
Example: A Car can have Passengers.
Aggregation association
Very similar to a Direct association. It's also a "WEAK relationship" with independent objects. However here the associated objects are a crucial part of the containing object.
Example: A Car should have Tires.
Note: Both Direct associations and Aggregation associations are often generalized as "Associations". The difference is rather subtle.
The whole point of OOP is that your code replicates real world objects, making your code readable and maintainable.
1. Association
Association is: Class A uses Class B.
Example:
Employee uses Bus/train Services for transportation.
Computer uses keyboard as input device
And in In UML diagram Association is denoted by a normal arrow head.
2. Aggregation
Class A contains Class B, or Class A has an instance of Class B.
An aggregation is used when life of object is independent of container object. But still container object owns the aggregated object.
So if we delete class A that doesn't mean that class B will also be deleted. E.g. none, or many, teachers can belong to one or many departments.
The relationship between Teachers and Departments is aggregation.
3. Composition
Class A owns Class B.
E.g. Body consists of Arm, Head, Legs. BankAccount consists of Balance and TransactionHistory.
So if class A gets deleted then also class B will get deleted.
Direct association has nothing in common with the other three. It does not belong to UML at all, it is the IBM requirements modelling term.
As for others,
Association A->B is a child of Dependency. Association means, that A (or its instance) has some easy way to get to instance of B. For example, a.x.y.b. Or by function, or by some local variable. Or by a direct reference or pointer, or something else (there are many languages in the world). As you see, there is no strict border between dependency and association.
One of attributes of Association is Aggregation, it can have values: None, shared (often incorrectly called aggregation), and composition.
If A (or instance) has some (or one) instances of B so, that destroying of association means the destroying of B instances, it is the composition.
If you or a tool author had decided, that some has-a relationship, that is weaker that composition, needs to be specially shown, you can use shared aggregation. Usually it is some collections of references to B in A.
There are some more interesting attributes of associations. Look here if you are interested.
An association between object types classifies relationships between objects of those types. For instance, the association Person-isEmployedBy-Enterprise may classify the relationships PeterMiller-isEmployedBy-IBM, SusanSmith-isEmployedBy-IBM and SarahAnderson-isEmployedBy-Google between the objects PeterMiller, SusanSmith and SarahAnderson of type Person as well as Google and IBM of type Enterprise. In other words, associations are relationship types with two or more object types participating in them. An association between two object types is called binary. While binary associations are more common, we may also have to deal with n-ary associations, where n is a natural number greater than 2. For instance, Person-isTreatedIn-Hospital-for-Disease is a 3-ary ("ternary") association between the object types Person, Hospital and Disease.
I guess that with "direct association" you mean a directional (or directed) association, which is an association (with a domain class and a range class) that represents a reference property in its domain class. Such a directional association has an "ownership dot" at its target end.
Please see this book chapter for more about associations.
And see my answer to this SO question for an explanation of aggregations and compositions.