Trait (computer programming)

From HandWiki - Reading time: 8 min

Short description: Concept used in object-oriented programming


In computer programming, a trait is a concept used in programming languages which represents a set of methods that can be used to extend the functionality of a class.[1][2]

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. Historically, there have been several approaches to solve this without duplicating the code in every class needing the behavior. Other approaches include multiple inheritance and mixins, 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. 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 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 of multiple inheritance. 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:[3][4]

  • 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 (i.e. given traits A and B, A + B is equivalent to B + A) and associative (i.e. given traits A, B, and C, (A + B) + C is equivalent to A + (B + C)).[1]

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 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, 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[5] and are supported by the following programming languages:

  • AmbientTalk: Combines the properties of Self traits (object-based multiple inheritance) and Smalltalk's Squeak 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.[6]
  • C#: Since version 8.0, C# has support for default interface methods,[7] which have some properties of traits.[8]
  • C++: Used in Standard Template Library and the C++ standard library to support generic container classes[9][10] and in the Boost TypeTraits library.[11]
  • Curl: Abstract classes as mixins permit method implementations and thus constitute traits by another name.[citation needed]
  • Fortress[12]
  • Groovy: Since version 2.3[13]
  • Haskell: In Haskell, Traits are known as Type classes.
  • Haxe: Since version 2.4.0.[14] Called Static Extension[15] in the manual, it uses using keyword
  • Java: Since version 8, Java has support for default methods,[16] which have some properties of traits.[17][18][19][20]
  • JavaScript: Traits can be implemented via functions and delegations[21] or through libraries that provide traits.[22][23][24]
  • Julia: Several packages implement traits, e.g.,[25]
  • Kotlin: Traits have been called interfaces[26] since M12.[27]
  • Lasso[28]
  • Mojo: Since version 0.6.0[29]
  • 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: Called roles, they are implemented in Perl libraries such as Moose, Role::Tiny and Role::Basic. Roles are part of the sister language Raku. [30] With the acceptance of the Corinna 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 pseudo multiple 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]
  • Rust[39]
  • Scala[40][41] trait is builtin supported with the key word trait.
  • Smalltalk: Traits are implemented in two dialects of Smalltalk, Squeak[1] and Pharo.[42]
  • Swift: Traits can be implemented with protocol extensions.[43]

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
{
    // Traditional interface methods
    void Log(string message);
    void LogError(Exception exception);

    // Default interface method
    void LogWarning(string message)
    {
        Console.WriteLine(message);
    }        
}

class Logger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine(message);
    }

    public void LogError(Exception exception)
    {
        Console.WriteLine(exception.ToString());
    }
}

class Program
{
    static void Main(string[] args)
    {
        ILogger logger = new Logger();

        logger.LogWarning("Some warning message");
    }
}

PHP

This example uses a trait to enhance other classes:

// The template
trait TSingleton
{
    private static $_instance = null;

    private function __construct() {} // Must have private default constructor and be aware not to open it in the class

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}

class FrontController
{
    use TSingleton;
}

// Can also be used in already extended classes
class WebSite extends SomeClass
{
    use TSingleton;
}

This allows simulating aspects of multiple inheritance:

trait TBounding
{
    public $x, $y, $width, $height;
}

trait TMoveable
{
    public function moveTo($x, $y)
    {
        // …
    }
}

trait TResizeable
{
    public function resize($newWidth, $newHeight)
    {
        // …
    }
}

class Rectangle
{
    use TBounding, TMoveable, TResizeable;

    public function fillColor($color)
    {
        // …
    }
}

Rust

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 of generics in Rust.

// type T must have the "Ord" trait
// so that ">" and "<" operations can be done
fn max<T: Ord>(a: &[T]) -> Option<&T> {
    let mut result = a.first()?;
    for n in a {
        if *n > *result {
            result = &n;
        }
    }
    Some(result)
}

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.[45] Derivable traits include: Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord and Hash.

See also

References

  1. 1.0 1.1 1.2 Schärli, Nathanael; Ducasse, Stéphane; Nierstrasz, Oscar; Black, Andrew P. (2003). "Traits: Composable Units of Behaviour". Proceedings of the European Conference on Object-Oriented Programming (ECOOP).. Lecture Notes in Computer Science (Springer) 2743: 248–274. doi:10.1007/978-3-540-45070-2_12. ISBN 978-3-540-45070-2. http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. 
  2. 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. doi:10.1145/1119479.1119483. 
  3. Statically typed traits. University of Chicago. 2003. Archived from the original on May 17, 2004. https://web.archive.org/web/20040517161301/http://www.cs.uchicago.edu/files/tr_authentic/TR-2003-13.pdf. 
  4. Fisher, Kathleen; Reppy, John (2004). "A typed calculus of traits". 11th Workshop on Foundations of Object-oriented Programming. University of Chicago. http://people.cs.uchicago.edu/~jhr/papers/2004/fool-traits.pdf. 
  5. 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. 
  6. Van Cutsem, Tom; Bergel, Alexandre; Ducasse, Stéphane; De Meuter, Wolfgang (2009). "Adding State and Visibility Control to Traits Using Lexical Nesting". European Conference on Object-Oriented Programming (ECOOP 2009). 5653. Springer-Verlag. pp. 220–243. doi:10.1007/978-3-642-03013-0_11. ISBN 978-3-642-03012-3. http://soft.vub.ac.be/Publications/2009/vub-prog-tr-09-04.pdf. 
  7. "Default interface methods". Microsoft. https://docs.microsoft.com/en-gb/dotnet/csharp/whats-new/csharp-8#default-interface-methods. 
  8. "Interfaces in C# 8.0 gets a makeover". Talking Dotnet. 9 September 2019. https://www.talkingdotnet.com/default-implementations-in-interfaces-in-c-sharp-8/. 
  9. "iterator_traits<Iterator>". SGI. http://www.sgi.com/tech/stl/iterator_traits.html. 
  10. Myers, Nathan C. (June 1995). "Traits: a new and useful template technique". C++ Report. http://www.cantrip.org/traits.html. Retrieved January 23, 2016. 
  11. Abrahams, David. "Generic Programming Techniques: Traits". http://www.boost.org/more/generic_programming.html#traits. 
  12. Steele, Guy; Maessen, Jan-Willem (June 11, 2006). "Fortress Programming Language Tutorial". Sun Microsystems. http://stephane.ducasse.free.fr/Teaching/CoursAnnecy/0506-Master/ForPresentations/Fortress-PLDITutorialSlides9Jun2006.pdf. 
  13. "Object Orientation: Traits". http://www.groovy-lang.org/objectorientation.html#_traits. 
  14. "Haxe 2.4.0 - Haxe - The Cross-platform Toolkit". Haxe - The Cross-platform Toolkit. https://haxe.org/download/version/2.4.0/. 
  15. "Manual - Haxe - The Cross-platform Toolkit". Haxe - The Cross-platform Toolkit. https://haxe.org/manual/lf-static-extension.html. 
  16. "Default Methods". Oracle. https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html. 
  17. Liquori, Luigi; Spiwack, Arnaud (2008). "FeatherTrait: A Modest Extension of Featherweight Java". ACM Transactions on Programming Languages and Systems 30 (2): 11:1. doi:10.1145/1330017.1330022. https://hal.inria.fr/inria-00432538/. 
  18. Liquori, Luigi; Spiwack, Arnaud (2008). "Extending FeatherTrait Java with Interfaces". Theoretical Computer Science 398 (1–3): 243–260. doi:10.1016/j.tcs.2008.01.051. https://hal.inria.fr/inria-00432540/. 
  19. Bono, Viviana; Mensa, Enrico; Naddeo, Marco (September 2014). "Trait-oriented Programming in Java 8". International Conference on Principles and Practices of Programming on the Java Platform: virtual machines, languages, and tools (PPPJ ’14). pp. 181–6. doi:10.1145/2647508.2647520. https://hal.inria.fr/hal-01026531/en. 
  20. Forslund, Emil (February 3, 2016). "Definition of the Trait Pattern in Java". http://ageofjava.com/2016/02/definition-of-trait-pattern-in-java.html. 
  21. Seliger, Peter (April 11, 2014). "The Many Talents of JavaScript". http://peterseliger.blogspot.com/2014/04/the-many-talents-of-javascript.html. 
  22. "Traits.js: Traits for JavaScript". https://traitsjs.github.io/traits.js-website/. 
  23. Van Cutsem, Tom; Miller, Mark S. (2012). "Robust Trait Composition for Javascript". Science of Computer Programming. http://soft.vub.ac.be/Publications/2012/vub-soft-tr-12-19.pdf. Retrieved January 23, 2016. 
  24. "CocktailJS". https://cocktailjs.github.io/. 
  25. mauro3. "SimpleTraits.jl". https://github.com/mauro3/SimpleTraits.jl. 
  26. "Interfaces". JetBrains. http://kotlinlang.org/docs/reference/interfaces.html. 
  27. Breslav, Andrey (May 29, 2015). "Kotlin M12 is out!". JetBrains. http://blog.jetbrains.com/kotlin/2015/05/kotlin-m12-is-out/. 
  28. "Traits". LassoSoft. January 6, 2014. http://lassoguide.com/language/traits.html. 
  29. "Modular Docs - Mojo🔥 changelog" (in en). https://docs.modular.com/mojo/changelog.html#v0.6.0-2023-12-04. 
  30. chromatic (April 30, 2009). "The Why of Perl Roles". http://www.modernperlbooks.com/mt/2009/04/the-why-of-perl-roles.html. 
  31. Curtis "Ovid" Poe. "Corinna OOP Proposal". https://github.com/Ovid/Cor/blob/master/rfc/mvp.md. 
  32. "Traits". The PHP Group. http://www.php.net/manual/en/language.oop5.traits.php. 
  33. Marr, Stefan (January 9, 2011). "Request for Comments: Horizontal Reuse for PHP". The PHP Group. https://wiki.php.net/rfc/horizontalreuse. 
  34. Perä, Teppo. "py3traits Documentation". http://py3traits.readthedocs.org/. 
  35. Perä, Teppo (2015-03-25). "py2traits". https://github.com/Debith/py2traits. 
  36. "Higher Order Mixin Classes". http://stupid-python-tricks.blogspot.com/2015/04/computed-properties-and-higher-order.html. 
  37. "Traits". http://docs.racket-lang.org/reference/trait.html. 
  38. David Naseby (February 14, 2004). "Traits in Ruby". http://ruby-naseby.blogspot.com/2008/11/traits-in-ruby.html. 
  39. "Traits". https://doc.rust-lang.org/book/ch10-02-traits.html. 
  40. "Traits". École polytechnique fédérale de Lausanne. http://www.scala-lang.org/node/126. 
  41. Neward, Ted (April 29, 2008). "The busy Java developer's guide to Scala: Of traits and behaviors". IBM. http://www.ibm.com/developerworks/java/library/j-scala04298/. 
  42. "Traits in 10 minutes". http://pharo.gemtalksystems.com/book/LanguageAndLibraries/Traits/. 
  43. Hollemans, Matthijs (July 22, 2015). "Mixins and Traits in Swift 2.0". https://machinethink.net/blog/mixins-and-traits-in-swift-2.0/. 
  44. "Traits - Introduction to Programming Using Rust". http://gradebot.org/doc/ipur/trait.html. 
  45. "Traits - the Rust Programming Language". https://doc.rust-lang.org/book/first-edition/traits.html. 

External links




Licensed under CC BY-SA 3.0 | Source: https://handwiki.org/wiki/Trait_(computer_programming)
7 views | Status: cached on October 01 2024 21:14:35
↧ Download this article as ZWI file
Encyclosphere.org EncycloReader is supported by the EncyclosphereKSF