Jump to content

Object composition

From Wikipedia, the free encyclopedia

Incomputer science,object compositionandobject aggregationare closely related ways to combineobjectsordata typesinto more complex ones. In conversation, the distinction between composition and aggregation is often ignored.[1]Common kinds of compositions areobjectsused inobject-oriented programming,tagged unions,sets,sequences,and variousgraphstructures. Object compositions relate to, but are not the same as, data structures.

Object composition refers to the logical or conceptual structure of the information, not the implementation or physicaldata structureused to represent it[citation needed].For example, asequencediffers from asetbecause (among other things) the order of the composed items matters for the former but not the latter. Data structures such asarrays,linked lists,hash tables,and many others can be used to implement either of them. Perhaps confusingly, some of the same terms are used for both data structures and composites. For example, "binary tree"can refer to either: as a data structure it is a means of accessing a linear sequence of items, and the actual positions of items in the tree are irrelevant (the tree can be internally rearranged however one likes, without changing its meaning). However, as an object composition, the positions are relevant, and changing them would change the meaning (as for example incladograms)[citation needed].

Programming technique

[edit]

Object-oriented programmingis based on usingobjectstoencapsulatedata and behavior. It uses two main techniques for assembling and composing functionality into more complex ones, sub-typing and object composition.[2]Object composition is about combining objects within compound objects, and at the same time, ensuring the encapsulation of each object by using their well-definedinterfacewithout visibility of their internals. In this regard, object composition differs from data structures, which do not enforce encapsulation.

Object composition may also be about a group of multiple related objects, such as a set or a sequence of objects.Delegationmay enrich composition by forwarding requests or calls made to the enclosing composite object to one of its internal components.[3]

Inclass-based andtypedprogramming languages, types can be divided into composite and non-composite types, and composition can be regarded as a relationship between types: an object of a composite type (e.g.car) "has"objects of other types (e.g.wheel). When a composite object contains several sub-objects of the same type, they may be assigned to particularroles,often distinguished by names or numbers. For example, aPointobject might contain 3 numbers, each representing distance along a different axis, such as 'x', 'y', and 'z'. The study of part-whole relationships in general, ismereology.

Composition must be distinguished fromsubtyping,which is the process of adding detail to a general data type to create a more specific data type. For instance, cars may be a specific type of vehicle:caris avehicle.Subtyping doesn't describe a relationship between different objects, but instead, says that objects of a type are simultaneously objects of another type. The study of such relationships isontology.

Inprototype-based programming languages such asJavaScript,objects can dynamically inherit the behaviors from a prototype object at the moment of their instantiation. Composition must be distinguished from prototyping: the newly instantiated object inherits the composition of its prototype, but it may itself be composed on its own.

Composite objects may be represented in storage by co-locating the composed objects, by co-locating references, or in many other ways. The items within a composite object may be referred to asattributes,fields,members,properties,or other names, and the resulting composition ascomposite type,storage record,structure,tuple,or auser-defined type (UDT).For details, see theaggregationsection below.

UML modeling technique

[edit]
A bycicle class represented in UML, with three properties: saddle, wheels and parts, the two last having a multiplicity indicating several objects
Object composition using UML properties to compose objects

InUMLmodeling, objects can be conceptually composed, independently of the implementation with a programming language. There are four ways of composing objects in UML: property, association, aggregation and composition:[4]

  • A property represents an attribute of the class.
  • An association represents asemantic relationshipbetween instances of the associated classes. The member-end of an association corresponds to a property of the associated class.
  • An aggregation is a kind of association that models a part/whole relationship between an aggregate (whole) and a group of related components (parts).
  • A composition, also called a composite aggregation, is a kind of aggregation that models a part/whole relationship between a composite (whole) and a group of exclusively owned parts.

The relationship between the aggregate and its components is a weak "has-a" relationship: The components may be part of several aggregates, may be accessed through other objects without going through the aggregate, and may outlive the aggregate object.[4]The state of the component object still forms part of the aggregate object.[citation needed]

The relationship between the composite and its parts is a strong “has-a” relationship: The composite object has sole "responsibility for the existence and storage of the composed objects",the composed object can be part of at most one composite, and"If a composite object is deleted, all of its part instances that are objects are deleted with it".Thus in UML, composition has a more narrow meaning than the usual object composition.

Association between several bicycles each having one owner; Composition of a bicycle with frame parts which make the bicycle; and aggregation of a bicycle with its wheels, which exist without the bicycle
UML notation for association, composition and aggregation

The graphical notation represents:

  • the property as a typed element in the box of the enclosing class,
  • the association as a plain line between the associated classes,
  • theaggregationas an unfilled diamond on the side of the aggregate and a solid line,
  • the composition as a filled diamond on the side of the composite and a solid line.

Aggregation

[edit]

Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true. For example, auniversityowns various departments (e.g.,chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a university can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a professor could work in more than one department, but a department could not be part of more than one university.

Composition is usually implemented such that an object contains another object. For example, inC++:

classProfessor;// Defined elsewhere

classDepartment{
public:
Department(conststd::string&title):title_(title){}

private:
// Aggregation: |Professors| may outlive the |Department|.
std::vector<std::weak_ptr<Professor>>members_;
conststd::stringtitle_;
};


classUniversity{
public:
University()=default;

private:
// Composition: |Department|s exist only as long as the faculty exists.
std::vector<Department>faculty_={
Department("chemistry"),
Department("physics"),
Department("arts"),
};
};

In aggregation, the object may only contain a reference or pointer to the object (and not havelifetimeresponsibility for it).

Sometimes aggregation is referred to as composition when the distinction between ordinary composition and aggregation is unimportant.

The above code would transform into the following UML Class diagram:

Aggregation in COM

[edit]
Aggregation in COM

In Microsoft'sComponent Object Model,aggregation means that an object exports, as if it were their owner, one or severalinterfacesof another object it owns. Formally, this is more similar tocompositionorencapsulationthan aggregation. However, instead of implementing the exported interfaces by calling the interfaces of the owned object, the interfaces of the owned object themselves are exported. The owned object is responsible for assuring that methods of those interfaces inherited fromIUnknownactually invoke the corresponding methods of the owner. This is to guarantee that the reference count of the owner is correct and all interfaces of the owner are accessible through the exported interface, while no other (private) interfaces of the owned object are accessible.[5]

Special forms

[edit]

Containment

[edit]

Composition that is used to store several instances of the composited data type is referred to as containment. Examples of such containers arearrays,associative arrays,binary trees,andlinked lists.

InUML,containment is depicted with a multiplicity of 0..* or 1..*, indicating that the composite object is composed of an unknown number of instances of the composed class.

Recursive composition

[edit]

Objects can be composed recursively, and their type is then calledrecursive type.Examples includes various kinds oftrees,DAGs,andgraphs.Each node in a tree may be a branch or leaf; in other words, each node is a tree at the same time when it belongs to another tree.

In UML, recursive composition is depicted with an association, aggregation or composition of a class with itself.

Composite pattern

[edit]

Thecomposite design patternis an object-oriented design based on composite types, that combines recursive composition and containment to implement complex part-whole hierarchies.

Composite types in C

[edit]

This is an example of composition inC.

structPerson
{
intage;
charname[20];
enum{job_seeking,professional,non_professional,retired,student}employment;
};

In this example, the primitive (noncomposite) typesint,enum {job_seeking, professional, non_professional, retired, student} and the composite array typechar[]are combined to form the composite structurePerson.EachPersonstructure then "has an" age, name, and an employment type.

Timeline of composition in various languages

[edit]

Ccalls a record astructor structure;object-orientedlanguages such asJava,Smalltalk,andC++often keep their records hidden insideobjects(classinstances); languages in theMLfamily simply call them records.COBOLwas the first widespreadprogramming languageto support records directly;[6]ALGOL 68got it from COBOL andPascalgot it, more or less indirectly, from ALGOL 68.Common Lispprovides structures and classes (the latter via theCommon Lisp Object System).[citation needed]

1959 – COBOL
01customer-record.
03customer-numberpic 9(8)comp.
03customer-name.
05given-namespic x(15).
05initial-2pic x.
05surnamepic x(15).
03customer-address.
05street.
07street-namepic x(15).
09house-numberpic 999comp.
05citypic x(10).
05country-codepic x(3).
05postcodepic x(8).
03amount-owingpic 9(8)comp.
1960 – ALGOL 60

Arrays were the onlycomposite data typeinAlgol 60.

1964 – PL/I
dcl 1 newtypet based (P);
2 (a, b, c) fixed bin(31),
2 (i, j, k) float,
2 r ptr;
allocate newtypet;
1968 – ALGOL 68
int max = 99;
mode newtypet = [0..9] [0..max]struct (
long real a, b, c, short int i, j, k, ref real r
);
newtypet newarrayt = (1, 2, 3, 4, 5, 6, heap real:= 7)

For example, a linked list might be declared as:

mode node = union (real, int, compl, string),
list = struct (node val, ref list next);

For ALGOL 68 only the type name appears to the left of the equality, and most notably the construction is made – and can be read – from left to right without regard to priorities.

1970 – Pascal
type
a=array[1..10]ofinteger;
b=record
a,b,c:real;
i,j,k:integer;
end;
1972 –K&R C
#define max 99
structnewtypet{
doublea,b,c;
floatr;
shorti,j,k;
}newarrayt[10][max+1];
1977 – FORTRAN 77

Fortran 77 has arrays, but lacked any formal record/structure definitions. Typically compound structures were built up usingEQUIVALENCEorCOMMONstatements:

CHARACTERNAME*32,ADDR*32,PHONE*16
REALOWING
COMMON/CUST/NAME,ADDR,PHONE,OWING
1983 – Ada
typeCustis
record
Name:Name_Type;
Addr:Addr_Type;
Phone:Phone_Type;
Owing:Integerrange1..999999;
end record;

Ada 95 brought OOP concepts through tagged types (the equivalent of a C++ class), Ada 2012 added support forsubstitutionverification through class-wide contracts.

1983 – C++
constintmax=99;
class{
public:
doublea,b,c;
float&r;
shorti,j,k;
}newtypet[10][max+1];
1991 – Python
max=99
classNewTypeT:
def__init__(self):
self.a=self.b=self.c=0
self.i=self.j=self.k=0.0
# Initialise an example array of this class.
newarrayt=[[NewTypeT()foriinrange(max+1)]forjinrange(10)]
1992 – FORTRAN 90

Arrays and strings were inherited from FORTRAN 77, and a new reserved word was introduced:type

typenewtypet
double precisiona,b,c
integer*2i,j,k
*Nopointer typeREFREALR
end type

type(newtypet)t(10,100)

FORTRAN 90 updated and includedFORTRAN IV's concept called NAMELIST.

INTEGER::jan=1,feb=2,mar=3,apr=4
NAMELIST/week/jan,feb,mar,apr
1994 – ANSICommon Lisp

Common Lisp provides structures and the ANSI Common Lisp standard added CLOS classes.

(defclasssome-class()
((f:typefloat)
(i:typeinteger)
(a:type(arrayinteger(10)))))

For more details about composition in C/C++, seeComposite type.

See also

[edit]

References

[edit]
  1. ^Yaiser, Michelle."Object-oriented programming concepts: Composition and aggregation".Archived fromthe originalon April 8, 2015.There is a closely related concept to composition called aggregation. In conversation the differences between composition and aggregation are often ignored.
  2. ^Design patterns: elements of reusable object-oriented software.Gamma, Erich., Helm, Richard (Computer scientist), Johnson, Ralph E., 1955-, Vlissides, John. Reading, Mass.: Addison-Wesley. 1995.ISBN0-201-63361-2.OCLC31171684.{{cite book}}:CS1 maint: others (link)
  3. ^Ostermann, Klaus; Mezini, Mira (October 1, 2001)."Object-oriented composition untangled".ACM SIGPLAN Notices.36(11): 283–299.doi:10.1145/504311.504303.ISSN0362-1340.
  4. ^abOMG (2017)."Unified Modeling Language Specification Version 2.5.1".omg.org.p. 109-110,197-201.RetrievedOctober 4,2020.
  5. ^"Aggregation".Platform SDK for Windows XP SP2.Microsoft.RetrievedNovember 4,2007.
  6. ^Sebesta, Robert W.Concepts of Programming Languages(Third ed.). Addison-Wesley Publishing Company, Inc. p.218.ISBN0-8053-7133-8.
[edit]