HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a trait is a concept 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 ...
which represents a set of
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
that can be used to extend the functionality of a
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 ...
.


Rationale

In object-oriented programming, behavior is sometimes shared between classes which are not related to each other. For example, many unrelated classes may have methods to serialize objects to
JSON JSON (JavaScript Object Notation, pronounced ; also ) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other ser ...
. Historically, there have been several approaches to solve this without duplicating the code in every class needing the behavior. Other approaches include
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
and
mixins In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
, but these have drawbacks: the behavior of the code may unexpectedly change if the order in which the mixins are applied is altered, or if new methods are added to the parent classes or mixins. Traits solve these problems by allowing classes to use the trait and get the desired behavior. If a class uses more than one trait, the order in which the traits are used does not matter. The methods provided by the traits have direct access to the data of the class.


Characteristics

Traits combine aspects of protocols (interfaces) and
mixins In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...
. Like an interface, a trait defines one or more method signatures, of which implementing classes must provide implementations. Like a mixin, a trait provides additional behavior for the implementing class. In case of a
naming collision A naming collision is a circumstance where two or more identifiers in a given namespace or a given scope cannot be unambiguously resolved, and such unambiguous resolution is a requirement of the underlying system. Example: XML element names I ...
between methods provided by different traits, the programmer must explicitly disambiguate which one of those methods will be used in the class; thus manually solving the ''
diamond problem Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
'' of
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
. This is different from other composition methods in object-oriented programming, where conflicting names are automatically resolved by scoping rules. Operations which can be performed with traits include: * ''symmetric sum'': an operation that merges two disjoint traits to create a new trait * ''override'' (or ''asymmetric sum''): an operation that forms a new trait by adding methods to an existing trait, possibly overriding some of its methods * ''alias'': an operation that creates a new trait by adding a new name for an existing method * ''exclusion'': an operation that forms a new trait by removing a method from an existing trait. (Combining this with the alias operation yields a ''shallow rename'' operation). If a method is excluded from a trait, that method must be provided by the class that consumes the trait, or by a parent class of that class. This is because the methods provided by the trait might call the excluded method. Trait composition is
commutative In mathematics, a binary operation is commutative if changing the order of the operands does not change the result. It is a fundamental property of many binary operations, and many mathematical proofs depend on it. Most familiar as the name o ...
(i.e. given traits ''A'' and ''B'', ''A'' + ''B'' is equivalent to ''B'' + ''A'') and
associative In mathematics, the associative property is a property of some binary operations, which means that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement f ...
(i.e. given traits ''A'', ''B'', and ''C'', (''A'' + ''B'') + ''C'' is equivalent to ''A'' + (''B'' + ''C'')).


Limitations

While traits offer significant advantages over many alternatives, they do have their own limitations.


Required methods

If a trait requires the consuming class to provide certain methods, the trait cannot know if those methods are
semantically equivalent {{about, semantic equivalence of metadata, the concept in mathematical logic, Logical equivalence In computer metadata, semantic equivalence is a declaration that two data elements from different vocabularies contain data that has similar meaning. ...
to the trait's needs. For some dynamic languages, such as Perl, the required method can only be identified by a method name, not a full
method signature In computer science, a type signature or type annotation defines the inputs and outputs for a function, subroutine or method. A type signature includes the number, types, and order of the arguments contained by a function. A type signature is typ ...
, making it harder to guarantee that the required method is appropriate.


Excluding methods

If a method is excluded from a trait, that method becomes a 'required' method for the trait because the trait's other methods might call it.


Supported languages

Traits come originally from the programming language
Self The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
and are supported by the following programming languages: *
AmbientTalk AmbientTalk is an experimental Object oriented programming, object-oriented distributed programming language developed at the Programming Technology Laboratory at the Vrije Universiteit Brussel, Belgium. The language is primarily targeted at wri ...
: Combines the properties of Self traits (object-based multiple inheritance) and
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 ...
's
Squeak Squeak is an object-oriented, class-based, and reflective programming language. It was derived from Smalltalk-80 by a group that included some of Smalltalk-80's original developers, initially at Apple Computer, then at Walt Disney Imagineering, ...
traits (requiring explicit composition of traits by the programmer). It builds on the research on ''stateful'' and ''freezable'' traits to enable state within traits, which was not allowed in the first definitions. * C#: Since version 8.0, C# has support for ''default interface methods'', which have some properties of traits. *
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 ...
: Used in
Standard Template Library The Standard Template Library (STL) is a Library (computer science), software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components ...
and the
C++ standard library The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard.ISO/IEC (2018). '' ISO/IEC 9899:2018(E): Programming Languages - C §7'' Starting from the original ANSI C standard, it wa ...
to support generic container classes and in the Boost TypeTraits library. *
Curl cURL (pronounced like "curl", UK: , US: ) is a computer software project providing a library (libcurl) and command-line tool (curl) for transferring data using various network protocols. The name stands for "Client URL". History cURL was fi ...
: Abstract classes as mixins permit method implementations and thus constitute traits by another name. * D: Since version 2.003, the __traits language extension and std.traits module helper templates provide compile-time traits. Together with other language features (notably templates and mixins), they allow flexible automatic generation of methods based on interfaces and types. D also allows explicit aliasing of member methods and variables, including forwarding to multiple member classes. *
Fortress A fortification is a military construction or building designed for the defense of territories in warfare, and is also used to establish rule in a region during peacetime. The term is derived from Latin ''fortis'' ("strong") and ''facere'' ...
*
Groovy ''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context. History The ...
: Since version 2.3 *
Haskell Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
: In Haskell, Traits are known as
Type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...
es. *
Haxe Haxe is an open source high-level cross-platform programming language and compiler that can produce applications and source code, for many different computing platforms from one code-base. It is free and open-source software, released under the ...
: Since version 2.4.0. Called ''Static Extension'' in the manual, it uses using keyword *
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 ...
: Since version 8, Java has support for ''default methods'', which have some properties of traits. *
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 ...
: Traits can be implemented via functions and delegations or through libraries that provide traits. *
Julia Julia is usually a feminine given name. It is a Latinate feminine form of the name Julio and Julius. (For further details on etymology, see the Wiktionary entry "Julius".) The given name ''Julia'' had been in use throughout Late Antiquity (e.g ...
: Several packages implement traits, e.g., * Kotlin: Traits have been called ''interfaces'' since M12. *
Lasso A lasso ( or ), also called lariat, riata, or reata (all from Castilian, la reata 're-tied rope'), is a loop of rope designed as a restraint to be thrown around a target and tightened when pulled. It is a well-known tool of the Spanish an ...
*
OCaml OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
: Traits can be implemented using a variety of language features: module and module type inclusion, functors and functor types, class and class type inheritance, et cetera. *
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
: Called ''roles'', they are implemented in Perl libraries such as
Moose The moose (in North America) or elk (in Eurasia) (''Alces alces'') is a member of the New World deer subfamily and is the only species in the genus ''Alces''. It is the largest and heaviest extant species in the deer family. Most adult mal ...
, Role::Tiny and Role::Basic. Roles are part of the sister language Raku. With the acceptance of the ''Corinna OOP Proposal'' Perl will have roles native to the language as part of a modern OOP system. *
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
: Since version 5.4, PHP allows users to specify templates that provide the ability to "inherit" from more than one (trait-)class, as a pseudo
multiple inheritance Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
. *
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
: Via a third-party library, or via higher-order mixin classes * Racket: Supports traits as a library and uses macros, structures, and first-class classes to implement them. *
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
: ''Module mixins'' can be used to implement traits. *
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH ...
* Scala trait is builtin supported with the key word trait. *
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 ...
: Traits are implemented in two dialects of Smalltalk,
Squeak Squeak is an object-oriented, class-based, and reflective programming language. It was derived from Smalltalk-80 by a group that included some of Smalltalk-80's original developers, initially at Apple Computer, then at Walt Disney Imagineering, ...
and
Pharo Pharo is an open source, cross-platform implementation of the classic Smalltalk-80 programming language and runtime. It's based on the OpenSmalltalk virtual machine called Cog (VM), which evaluates a dynamic, Reflective programming, reflectiv ...
. *
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
: Traits can be implemented with ''protocol extensions''.


Examples


C#

On C# 8.0, it is possible to define an implementation as a member of an interface. using System; namespace CSharp8NewFeatures; interface ILogger class Logger : ILogger class Program


PHP

This example uses a trait to enhance other classes: // The template trait TSingleton class FrontController // Can also be used in already extended classes class WebSite extends SomeClass This allows simulating aspects of multiple inheritance: trait TBounding trait TMoveable trait TResizeable class Rectangle


Rust

A trait in Rust declares a set of methods that a type must implement. Rust compilers require traits to be explicated, which ensures the safety of generics in Rust. // type T must have the "Ord" trait // so that ">" and "<" operations can be done fn max(a: & -> Option<&T> To simplify tedious and repeated implementation of traits like Debug and Ord, the derive macro can be used to request compilers to generate certain implementations automatically. Derivable traits include: Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord and Hash.


See also

*
Extension method In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-orie ...
*
Interface (object-oriented programming) In object-oriented programming, an interface or protocol type is a data type describing a set of method signatures, the implementations of which may be provided by multiple classes that are otherwise not necessarily related to each other. A class ...
*
Parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
*
UFCS Uniform Function Call Syntax (UFCS) or Uniform Calling Syntax (UCS) or sometimes Universal Function Call Syntax is a programming language feature in D and Nim that allows any function to be called using the syntax for method calls (as in object-o ...


References


External links

* {{cite web , url=http://scg.unibe.ch/research/traits , title=Traits: Composable Units of Behavior , website=Software Composition Group , publisher=University of Bern C++ Programming language topics Type theory