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 toserialize objects toJSON. Historically, there have been several approaches to solve this without duplicating the code in every class needing the behavior. Other approaches includemultiple inheritance andmixins, 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.
Traits combine aspects ofprotocols (interfaces) andmixins. Like an interface, a trait defines one or moremethod signatures, of which implementing classes must provide implementations. Like a mixin, a trait provides additional behavior for the implementing class.
In case of anaming collision 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 thediamond problem ofmultiple inheritance. This is different from other composition methods in object-oriented programming, where conflicting names are automatically resolved byscoping rules.
Operations which can be performed with traits include:[3][4]
symmetric sum: an operation that merges two disjoint traits to create a new trait
override (orasymmetric sum): an operation that forms a new trait by adding methods to an existing trait, possiblyoverriding 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 ashallow 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 iscommutative (i.e. given traitsA andB,A +B is equivalent toB +A) andassociative (i.e. given traitsA,B, andC, (A +B) +C is equivalent toA + (B +C)).[1]
If a trait requires the consuming class to provide certain methods, the trait cannot know if those methods aresemantically equivalent 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 fullmethod signature, making it harder to guarantee that the required method is appropriate.
Traits come originally from the programming languageSelf[5] and are supported by the following programming languages:
AmbientTalk: Combines the properties of Self traits (object-based multiple inheritance) andSmalltalk'sSqueak traits (requiring explicit composition of traits by the programmer). It builds on the research onstateful andfreezable traits to enable state within traits, which was not allowed in the first definitions.[6]
C#: Since version 8.0, C# has support fordefault interface methods,[7] which have some properties of traits.[8]
OCaml: 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: Calledroles, they are implemented in Perl libraries such asMoose, Role::Tiny and Role::Basic. Roles are part of the sister languageRaku.[30] With the acceptance of theCorinna OOP Proposal[31] Perl will have roles native to the language as part of a modern OOP system.
PHP: Since version 5.4,[32][33] PHP allows users to specify templates that provide the ability to "inherit" from more than one (trait-)class, as a pseudomultiple inheritance.
Python: Via a third-party library,[34][35] or via higher-order mixin classes[36]
Racket: Supports traits as a library and uses macros, structures, and first-class classes to implement them.[37]
Ruby:Module mixins can be used to implement traits.[38]
This example uses a trait to enhance other classes:
// The templatetraitTSingleton{privatestatic$_instance=null;privatefunction__construct(){}// Must have private default constructor and be aware not to open it in the classpublicstaticfunctiongetInstance(){if(null===self::$_instance){self::$_instance=newself();}returnself::$_instance;}}classFrontController{useTSingleton;}// Can also be used in already extended classesclassWebSiteextendsSomeClass{useTSingleton;}
This allows simulating aspects of multiple inheritance:
A trait in Rust declares a set of methods that a type must implement.[44] Rust compilers require traits to be explicated, which ensures the safety ofgenerics in Rust.
// type T must have the "Ord" trait// so that ">" and "<" operations can be donefnmax<T:Ord>(a:&[T])->Option<&T>{letmutresult=a.first()?;fornina{if*n>*result{result=&n;}}Some(result)}
To simplify tedious and repeated implementation of traits likeDebug andOrd, thederive macro can be used to request compilers to generate certain implementations automatically.[45] Derivable traits include:Clone,Copy,Debug,Default,PartialEq,Eq,PartialOrd,Ord andHash.
^Ducasse, Stéphane; Nierstrasz, Oscar; Schärli, Nathanael; Wuyts, Roel; Black, Andrew P. (March 2006). "Traits: A mechanism for fine-grained reuse".ACM Transactions on Programming Languages and Systems.28 (2):331–388.CiteSeerX10.1.1.64.2480.doi:10.1145/1119479.1119483.S2CID16434119.
^Curry, Gael; Baer, Larry; Lipkie, Daniel; Lee, Bruce (1982).Traits: An approach to multiple-inheritance subclassing. SIGOA Conference on Office Information Systems. Philadelphia, Pennsylvania, USA: ACM Press. pp. 1–9.doi:10.1145/966873.806468.