Object Composition
   HOME

TheInfoList



OR:

In
computer science Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to Applied science, practical discipli ...
, object composition and object aggregation are closely related ways to combine
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
or
data type In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
s into more complex ones. In conversation the distinction between composition and aggregation is often ignored. Common kinds of compositions are
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
used in
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, tagged unions, sets,
sequences In mathematics, a sequence is an enumerated collection of objects in which repetitions are allowed and order matters. Like a set, it contains members (also called ''elements'', or ''terms''). The number of elements (possibly infinite) is called t ...
, and various
graph Graph may refer to: Mathematics *Graph (discrete mathematics), a structure made of vertices and edges **Graph theory, the study of such graphs and their properties *Graph (topology), a topological space resembling a graph in the sense of discre ...
structures. 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 physical
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, a ...
used to represent it. For example, a sequence differs from a set because (among other things) the order of the composed items matters for the former but not the latter. Data structures such as
arrays An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
,
linked lists In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which ...
,
hash tables In computing, a hash table, also known as hash map, is a data structure that implements an associative array or dictionary. It is an abstract data type that maps keys to values. A hash table uses a hash function to compute an ''index'', als ...
, 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 In computer science, a binary tree is a k-ary k = 2 tree data structure in which each node has at most two children, which are referred to as the ' and the '. A recursive definition using just set theory notions is that a (non-empty) binary t ...
" 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 in
cladogram A cladogram (from Greek ''clados'' "branch" and ''gramma'' "character") is a diagram used in cladistics to show relations among organisms. A cladogram is not, however, an evolutionary tree because it does not show how ancestors are related to d ...
s).


Programming technique

Object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
is based on
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
to encapsulate data and behavior. It uses two main techniques for assembling and composing functionality into more complex ones, sub-typing and object composition. Object composition is about combining objects within compound objects, and at the same time, ensuring the encapsulation of each object by using their well-defined
interface Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Inte ...
without 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. Delegation may enrich composition by forwarding requests or calls made to the enclosing composite object to one of its internal components. In
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
-based and typed programming 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 HAS or Has may refer to: Organizations * Hawaii Audubon Society, bird conservation organization in Hawaii * Hellenic Actuarial Society, association of actuaries in Greece * Hubbard Association of Scientologists International, corporation founded ...
" objects of other types (e.g. ''wheel''). When a composite object contains several sub-objects of the same type, they may be assigned to particular
role A role (also rôle or social role) is a set of connected behaviors, rights, moral obligation, obligations, beliefs, and social norm, norms as conceptualized by people in a social situation. It is an expected or free or continuously changing behavi ...
s, often distinguished by names or numbers. For example, a Point object 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, is
mereology In logic, philosophy and related fields, mereology ( (root: , ''mere-'', 'part') and the suffix ''-logy'', 'study, discussion, science') is the study of parts and the wholes they form. Whereas set theory is founded on the membership relation bet ...
. Composition must be distinguished from
subtyping In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutabilit ...
, 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: ''car'' is a ''vehicle''. 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 is
ontology In metaphysics, ontology is the philosophical study of being, as well as related concepts such as existence, becoming, and reality. Ontology addresses questions like how entities are grouped into categories and which of these entities exis ...
. In
prototype A prototype is an early sample, model, or release of a product built to test a concept or process. It is a term used in a variety of contexts, including semantics, design, electronics, and Software prototyping, software programming. A prototyp ...
-based programming languages such as
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, 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 as ''attributes'', ''
fields Fields may refer to: Music * Fields (band), an indie rock band formed in 2006 * Fields (progressive rock band), a progressive rock band formed in 1971 * ''Fields'' (album), an LP by Swedish-based indie rock band Junip (2010) * "Fields", a song b ...
'', ''members'', ''properties'', or other names, and the resulting composition as ''
composite type In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggreg ...
'', ''
storage record In computer science{{citation needed, date=July 2016, a storage record is: * A group of related data, words, or fields treated as a meaningful unit; for instance, a Name, Address, and Telephone Number can be a "Personal Record". * A self-contained c ...
'', ''structure'', ''
tuple In mathematics, a tuple is a finite ordered list (sequence) of elements. An -tuple is a sequence (or ordered list) of elements, where is a non-negative integer. There is only one 0-tuple, referred to as ''the empty tuple''. An -tuple is defi ...
'', or a ''user-defined type (UDT)''. For details, see the aggregation section below.


UML modeling technique

In
UML The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system. The creation of UML was originally m ...
modeling, 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: * A property represents an attribute of the class. * An association represents a semantic relationship between 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. The state of the component object still forms part of the aggregate object. 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. 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, * the aggregation as 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

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, a
university A university () is an institution of higher (or tertiary) education and research which awards academic degrees in several academic disciplines. Universities typically offer both undergraduate and postgraduate programs. In the United States, t ...
owns various departments (e.g.,
chemistry Chemistry is the science, scientific study of the properties and behavior of matter. It is a natural science that covers the Chemical element, elements that make up matter to the chemical compound, compounds made of atoms, molecules and ions ...
), 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, in
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
: class Professor; // Defined elsewhere class Department ; class University ; In aggregation, the object may only contain a reference or pointer to the object (and not have lifetime responsibility 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

In Microsoft's Component Object Model, aggregation means that an object exports, as if it were their owner, one or several
interfaces Interface or interfacing may refer to: Academic journals * Interface (journal), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
of another object it owns. Formally, this is more similar to
composition Composition or Compositions may refer to: Arts and literature *Composition (dance), practice and teaching of choreography *Composition (language), in literature and rhetoric, producing a work in spoken tradition and written discourse, to include v ...
or encapsulation than 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 from actually 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.


Special forms


Containment

Composition that is used to store several instances of the composited data type is referred to as containment. Examples of such containers are Array (data structure), arrays,
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an as ...
s,
binary tree In computer science, a binary tree is a k-ary k = 2 tree data structure in which each node has at most two children, which are referred to as the ' and the '. A recursive definition using just set theory notions is that a (non-empty) binary t ...
s, and
linked list In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes whic ...
s. In
UML The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system. The creation of UML was originally m ...
, 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

Objects can be composed recursively, and their type is then called
recursive type In computer programming languages, a recursive data type (also known as a recursively-defined, inductively-defined or inductive data type) is a data type for values that may contain other values of the same type. Data of recursive types are usuall ...
. Examples includes various kinds of
tree In botany, a tree is a perennial plant with an elongated stem, or trunk, usually supporting branches and leaves. In some usages, the definition of a tree may be narrower, including only woody plants with secondary growth, plants that are ...
s, DAGs, and
graph Graph may refer to: Mathematics *Graph (discrete mathematics), a structure made of vertices and edges **Graph theory, the study of such graphs and their properties *Graph (topology), a topological space resembling a graph in the sense of discre ...
s. 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

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


Composite types in C

This is an example of composition in C. struct Person ; In this example, the primitive (noncomposite) types , and the composite array type are combined to form the composite structure . Each structure then "has an" age, name, and an employment type.


Timeline of composition in various languages

C calls a record a
struct In computer science, a record (also called a structure, struct, or compound data) is a basic data structure. Records in a database or spreadsheet are usually called "rows". A record is a collection of '' fields'', possibly of different data typ ...
or structure;
object-oriented Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pro ...
languages such as
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
,
Smalltalk Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
, and
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
often keep their records hidden inside
objects Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
(
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
instances); languages in the ML family simply call them records.
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
was the first widespread
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
to support records directly;
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
got it from COBOL and
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Fren ...
got it, more or less indirectly, from ALGOL 68.
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
provides structures and classes (the latter via the
Common Lisp Object System The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such as ...
). ;1959 – COBOL 01 customer-record. 03 customer-number pic 9(8) comp. 03 customer-name. 05 given-names pic x(15). 05 initial-2 pic x. 05 surname pic x(15). 03 customer-address. 05 street. 07 street-name pic x(15). 09 house-number pic 999 comp. 05 city pic x(10). 05 country-code pic x(3). 05 postcode pic x(8). 03 amount-owing pic 9(8) comp. ;1960 – ALGOL 60 Arrays were the only
composite data type In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggreg ...
in
Algol 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
. ;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 =  ..9 ..maxtruct (
 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 ..10of integer; b = record a, b, c: real; i, j, k: integer; end; ;1972 –
K&R C C (''pronounced like the letter c'') is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities o ...
#define max 99 struct newtypet newarrayt 0 ax + 1 ;1977 – FORTRAN 77 Fortran 77 has arrays, but lacked any formal record/structure definitions. Typically compound structures were built up using or statements: CHARACTER NAME*32, ADDR*32, PHONE*16 REAL OWING COMMON /CUST/NAME, ADDR, PHONE, OWING ;1983 – Ada type Cust is record Name : Name_Type; Addr : Addr_Type; Phone : Phone_Type; Owing : Integer range 1..999999; end record; Ada 95 brought OOP concepts through tagged types (the equivalent of a C++ class), Ada 2012 added support for
substitution Substitution may refer to: Arts and media *Chord substitution, in music, swapping one chord for a related one within a chord progression * Substitution (poetry), a variation in poetic scansion * "Substitution" (song), a 2009 song by Silversun Pi ...
verification through class-wide contracts. ;1983 – C++ const int max = 99; class newtypet 0 ax + 1 ;1991 – Python max = 99 class NewTypeT: 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() for i in range(max + 1)for j in range(10)] ;1992 – FORTRAN 90 Arrays and strings were inherited from FORTRAN 77, and a new reserved word was introduced: type type newtypet double precision a, b, c integer*2 i, j, k * No pointer type REF REAL R end type type (newtypet) t(10, 100) FORTRAN 90 updated and included FORTRAN IV's concept called NAMELIST. INTEGER :: jan = 1, feb = 2, mar = 3, apr = 4 NAMELIST / week / jan, feb, mar, apr ;1994 – ANSI
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
Common Lisp provides structures and the ANSI Common Lisp standard added CLOS classes. (defclass some-class () ((f :type float) (i :type integer) (a :type (array integer (10))))) For more details about composition in C/C++, see
Composite type In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggreg ...
.


See also

* C++ structure *
Composite type In computer science, a composite data type or compound data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. It is sometimes called a structure or aggreg ...
*
Composition over inheritance Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should achieve Polymorphism (computer science), polymorphic behavior and code reuse by their object composition, compo ...
*
Delegation (programming) In computing or computer programming, delegation refers generally to one entity passing something to another entity,Barry Wilkinson, ''Grid Computing: Techniques and Applications'' (2009), p. 164, . and narrowly to various specific forms of relat ...
*
Function composition (computer science) In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next ...
*
Has-a In database design, object-oriented programming and design (see object oriented program architecture), has-a (has_a or has a) is a composition relationship where one object (often called the constituted object, or part/constituent/member object) ...
*
Implementation inheritance In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
*
Inheritance semantics In object-oriented programming, behavioral subtyping is the principle that subclasses should satisfy the expectations of clients accessing subclass objects through references of superclass type, not just as regards syntactic safety (such as the abs ...
*
Law of Demeter The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed by Ian Hol ...
*
Virtual inheritance Virtual inheritance is a C++ technique that ensures only one copy of a base classs member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits fr ...


References


External links


Association, Aggregation and Composition
accessed in February 2009 * Harald Störrle, UML2, Addison-Wesley, 2005 {{DEFAULTSORT:Object Composition Object (computer science) Unified Modeling Language Articles with example Python (programming language) code