Trait (computer programming): Difference between revisions

Content deleted Content added
Characteristics: This article was flagged as "too technical", so I provided an opening paragraph with a simplified description of traits.
I've started documenting some known limitations of traits. Sadly, the references to this are largely my communications with the trait researchers and years of personal experience.
Line 37:
* ''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).
 
Note that if you exclude a method from a trait, that method is required to be provided by the class that consumes the trait, or by a parent class that class inherits from. This is because the trait methods themselves might call the excluded method.
 
Traits are composed in the following ways:
Line 42 ⟶ 44:
* Conflicting methods are excluded from the composition.
* Nested traits are equivalent to flattened traits; the composition hierarchy does not affect the traits behaviour. For example, given trait ''S'' = ''A'' + ''X'', where ''X'' = ''B'' + ''C'', then trait ''T'' = ''A'' + ''B'' + ''C'' is the same as ''S''.<ref name="schaerli-ecoop-2003"/>
* A trait may require the consuming class to provide methods for the trait's use. For example, if the trait provides a <code>toJson</code> method, it might require the class to provide a <code>toDict</code> method that the <code>toJson</code> calls to convert to JSON.
 
==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 [[Semantic_equivalence|semantically equivalent]] to the trait's needs. Worse, for some dynamic languages, such as Perl, the required method can only be identified by a method name, not a full [[Type signature|method signature]], making it harder to guarantee that the required method is appropriate.
 
=== Excluding Methods ===
 
If you exclude a method from a trait, that method becomes a 'required' method for the trait because the trait's other methods might call it. If the programming language uses [[Static dispatch|static dispatch]] ("early binding"), method names are bound are [[Compile time|compile time]] and the trait methods might call the trait's implementation of the method and not the corresponding method provided by the class. Conversely, if the programming language uses [[Dynamic dispatch|dynamic dispatch]] ("late binding"), method names are determined at run time and the trait methods might call the class's implementation of the method and not the method provided by the trait. If a method is excluded, the programmer must take this into account.
 
==Supported languages==