Trait (computer programming) explained

In computer programming, a trait is a language concept that 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]

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:

Since version 8.0, C# has support for default interface methods,[7] which have some properties of traits.[8]

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 templatetrait TSingleton

class FrontController

// Can also be used in already extended classesclass 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.[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 donefn max(a: &[T]) -> 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.[45] Derivable traits include: Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord and Hash.

See also

External links

Notes and References

  1. Nathanael . Schärli . Stéphane . Ducasse . Oscar . Nierstrasz . Oscar Nierstrasz . Andrew P. . Black . Traits: Composable Units of Behaviour . Proceedings of the European Conference on Object-Oriented Programming (ECOOP). . Lecture Notes in Computer Science . 2743 . 2003 . 248–274 . Springer . 10.1007/978-3-540-45070-2_12 . 978-3-540-45070-2 . 10.1.1.1011.8.
  2. Stéphane . Ducasse . Oscar . Nierstrasz . Nathanael . Schärli . Roel . Wuyts . Andrew P. . Black . Traits: A mechanism for fine-grained reuse. . ACM Transactions on Programming Languages and Systems . 28 . 2 . 331–388 . March 2006 . 10.1145/1119479.1119483 . 10.1.1.64.2480. 16434119 .
  3. Kathleen . Fisher . Kathleen Fisher. John . Reppy. Statically typed traits. https://web.archive.org/web/20040517161301/http://www.cs.uchicago.edu/files/tr_authentic/TR-2003-13.pdf. May 17, 2004. live. University of Chicago. 2003.
  4. Kathleen . Fisher. John . Reppy. A typed calculus of traits. 11th Workshop on Foundations of Object-oriented Programming. http://www.cis.upenn.edu/~bcpierce/FOOL//FOOL11.html. University of Chicago. 2004.
  5. Gael . Curry . Larry . Baer . Daniel . Lipkie . Bruce . Lee . Traits: An approach to multiple-inheritance subclassing . SIGOA Conference on Office Information Systems . 1–9 . Philadelphia, Pennsylvania, USA . 1982 . ACM Press . 10.1145/966873.806468 .
  6. Adding State and Visibility Control to Traits Using Lexical Nesting . European Conference on Object-Oriented Programming (ECOOP 2009) . Tom . Van Cutsem . Alexandre . Bergel . Stéphane . Ducasse . Wolfgang . De Meuter . 220–243 . Springer-Verlag . 978-3-642-03012-3 . 2009 . Lecture Notes in Computer Science . 5653 . 10.1007/978-3-642-03013-0_11 . 10.1.1.372.1265.
  7. Web site: Default interface methods . What's new in C# 8.0 . Microsoft . November 29, 2019.
  8. Web site: Interfaces in C# 8.0 gets a makeover . Default Implementation in Interfaces in C# 8.0 . 9 September 2019 . Talking Dotnet . November 29, 2019.
  9. Web site: iterator_traits<Iterator> . Standard Template Library . SGI.
  10. Traits: a new and useful template technique . Nathan C. . Myers . C++ Report . June 1995 . January 23, 2016.
  11. Web site: Generic Programming Techniques: Traits . Boost C++ Libraries . David . Abrahams . January 23, 2016.
  12. Web site: Fortress Programming Language Tutorial . Guy . Steele . Jan-Willem . Maessen . Sun Microsystems . June 11, 2006 . January 23, 2016.
  13. Web site: Object Orientation: Traits . The Groovy Programming Language . January 23, 2016.
  14. News: Haxe 2.4.0 - Haxe - The Cross-platform Toolkit. Haxe - The Cross-platform Toolkit. 2017-09-12.
  15. News: Manual - Haxe - The Cross-platform Toolkit. Haxe - The Cross-platform Toolkit. 2017-09-12.
  16. Web site: Default Methods . The Java Tutorials . Oracle . January 23, 2016.
  17. FeatherTrait: A Modest Extension of Featherweight Java . Luigi . Liquori . Arnaud . Spiwack . ACM Transactions on Programming Languages and Systems . 2008 . 30 . 2 . 11:1 . 10.1145/1330017.1330022. 17231803 . free .
  18. Extending FeatherTrait Java with Interfaces . Luigi . Liquori . Arnaud . Spiwack . Theoretical Computer Science . 2008 . 398 . 1–3 . 243–260 . 10.1016/j.tcs.2008.01.051. 12923128 . free .
  19. Trait-oriented Programming in Java 8 . Viviana . Bono . Enrico . Mensa . Marco . Naddeo . International Conference on Principles and Practices of Programming on the Java Platform: virtual machines, languages, and tools (PPPJ ’14) . September 2014 . http://pppj2014.pk.edu.pl/ . 181–6 . 10.1145/2647508.2647520 . 10.1.1.902.161.
  20. Web site: Definition of the Trait Pattern in Java . https://web.archive.org/web/20160804005218/http://ageofjava.com/2016/02/definition-of-trait-pattern-in-java.html . dead . August 4, 2016 . Age of Java . February 3, 2016 . February 3, 2016 . Emil . Forslund.
  21. Web site: The Many Talents of JavaScript . Peter . Seliger . April 11, 2014 . January 23, 2015.
  22. Web site: Traits.js: Traits for JavaScript . January 23, 2016.
  23. Robust Trait Composition for Javascript . Tom . Van Cutsem . Mark S. . Miller . Science of Computer Programming. 2012 . January 23, 2016.
  24. Web site: CocktailJS . January 23, 2016.
  25. Web site: SimpleTraits.jl . mauro3 . . March 23, 2017.
  26. Web site: Interfaces . Kotlin Reference . JetBrains . January 23, 2016.
  27. Web site: Kotlin M12 is out! . Andrey . Breslav . Kotlin Blog . JetBrains . May 29, 2015 . January 23, 2016.
  28. Web site: Traits . Lasso Language Guide . LassoSoft . January 6, 2014 . January 23, 2016.
  29. Web site: Modular Docs - Mojo changelog . 2023-12-13 . docs.modular.com . en.
  30. Web site: The Why of Perl Roles . chromatic . April 30, 2009 . January 23, 2016.
  31. Web site: Corinna OOP Proposal . Corinna RFC . Curtis "Ovid" Poe . September 30, 2022.
  32. Web site: Traits . PHP Documentation . The PHP Group . January 23, 2016.
  33. Web site: Marr . Stefan . Request for Comments: Horizontal Reuse for PHP . PHP.net wiki . The PHP Group . January 9, 2011 . January 31, 2011.
  34. Web site: py3traits Documentation . Teppo . Perä . January 23, 2016.
  35. Web site: py2traits . Teppo . Perä . . January 23, 2016. 2015-03-25 .
  36. Web site: Higher Order Mixin Classes . 2016-10-09 . https://web.archive.org/web/20161009062141/http://stupid-python-tricks.blogspot.com/2015/04/computed-properties-and-higher-order.html .
  37. Web site: Traits . The Racket Reference . January 23, 2016.
  38. Web site: Traits in Ruby . Ruby Naseby . David Naseby . February 14, 2004 . January 23, 2016.
  39. Web site: Traits . The Rust Programming Language . September 30, 2019.
  40. Web site: Traits . A Tour of Scala . . January 23, 2016.
  41. Web site: The busy Java developer's guide to Scala: Of traits and behaviors . Ted . Neward . IBM developerWorks . IBM . April 29, 2008 . January 23, 2016.
  42. Web site: Traits in 10 minutes . Pharo: The CollaborActive Book . January 23, 2016.
  43. Web site: Mixins and Traits in Swift 2.0 . Matthijs . Hollemans . July 22, 2015 . January 23, 2016.
  44. Web site: Traits - Introduction to Programming Using Rust.
  45. Web site: Traits - the Rust Programming Language.