Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Trait (computer programming)

From Wikipedia, the free encyclopedia
Set of methods that extend the functionality of a class
This articlemay be too technical for most readers to understand. Pleasehelp improve it tomake it understandable to non-experts, without removing the technical details.(March 2012) (Learn how and when to remove this message)
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Trait" computer programming – news ·newspapers ·books ·scholar ·JSTOR
(November 2022) (Learn how and when to remove this message)

Incomputer programming, atrait is alanguage concept that represents a set ofmethods that can be used to extend the functionality of aclass.[1][2]

Rationale

[edit]

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.

Characteristics

[edit]

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]

Limitations

[edit]

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

Required methods

[edit]

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.

Excluding methods

[edit]

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

[edit]

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]
  • C++: Used inStandard Template Library and theC++ Standard Library to support genericcontainer classes[9][10] and in theBoost 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 asType classes.
  • Haxe: Since version 2.4.0.[14] CalledStatic Extension[15] in the manual, it usesusing keyword
  • Java: Since version 8, Java has support fordefault 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 calledinterfaces[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: 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]
  • Rust[39]
  • Scala[40][41] trait is builtin supported with the key wordtrait.
  • Smalltalk: Traits are implemented in two dialects of Smalltalk,Squeak[1] andPharo.[42]
  • Swift: Traits can be implemented withprotocol extensions.[43]

Examples

[edit]

C#

[edit]

On C# 8.0, it is possible to define an implementation as a member of an interface.

usingSystem;namespaceCSharp8NewFeatures;interfaceILogger{// Traditional interface methodsvoidLog(stringmessage);voidLogError(Exceptionexception);// Default interface methodvoidLogWarning(stringmessage){Console.WriteLine(message);}}classLogger:ILogger{publicvoidLog(stringmessage){Console.WriteLine(message);}publicvoidLogError(Exceptionexception){Console.WriteLine(exception.ToString());}}publicclassProgram{staticvoidMain(string[]args){ILoggerlogger=newLogger();logger.LogWarning("Some warning message");}}

PHP

[edit]

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:

traitTBounding{public$x,$y,$width,$height;}traitTMoveable{publicfunctionmoveTo($x,$y){// …}}traitTResizeable{publicfunctionresize($newWidth,$newHeight){// …}}classRectangle{useTBounding,TMoveable,TResizeable;publicfunctionfillColor($color){// …}}

Rust

[edit]

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.

See also

[edit]

References

[edit]
  1. ^abcSchärli, Nathanael; Ducasse, Stéphane;Nierstrasz, Oscar; Black, Andrew P. (2003)."Traits: Composable Units of Behaviour"(PDF).Proceedings of the European Conference on Object-Oriented Programming (ECOOP). Lecture Notes in Computer Science. Vol. 2743. Springer. pp. 248–274.CiteSeerX 10.1.1.1011.8.doi:10.1007/978-3-540-45070-2_12.ISBN 978-3-540-45070-2.
  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.CiteSeerX 10.1.1.64.2480.doi:10.1145/1119479.1119483.S2CID 16434119.
  3. ^Fisher, Kathleen; Reppy, John (2003).Statically typed traits(PDF) (Report).University of Chicago.Archived(PDF) from the original on May 17, 2004.
  4. ^Fisher, Kathleen; Reppy, John (2004).A typed calculus of traits(PDF).11th Workshop on Foundations of Object-oriented Programming.University of Chicago.
  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(PDF). European Conference on Object-Oriented Programming (ECOOP 2009). Lecture Notes in Computer Science. Vol. 5653. Springer-Verlag. pp. 220–243.CiteSeerX 10.1.1.372.1265.doi:10.1007/978-3-642-03013-0_11.ISBN 978-3-642-03012-3.
  7. ^"Default interface methods".What's new in C# 8.0. Microsoft. RetrievedNovember 29, 2019.
  8. ^"Interfaces in C# 8.0 gets a makeover".Default Implementation in Interfaces in C# 8.0. Talking Dotnet. 9 September 2019. RetrievedNovember 29, 2019.
  9. ^"iterator_traits<Iterator>".Standard Template Library. SGI.
  10. ^Myers, Nathan C. (June 1995)."Traits: a new and useful template technique".C++ Report. RetrievedJanuary 23, 2016.
  11. ^Abrahams, David."Generic Programming Techniques: Traits".Boost C++ Libraries. RetrievedJanuary 23, 2016.
  12. ^Steele, Guy; Maessen, Jan-Willem (June 11, 2006)."Fortress Programming Language Tutorial"(PDF). Sun Microsystems. RetrievedJanuary 23, 2016.
  13. ^"Object Orientation: Traits".The Groovy Programming Language. RetrievedJanuary 23, 2016.
  14. ^"Haxe 2.4.0 - Haxe - The Cross-platform Toolkit".Haxe - The Cross-platform Toolkit. Retrieved2017-09-12.
  15. ^"Manual - Haxe - The Cross-platform Toolkit".Haxe - The Cross-platform Toolkit. Retrieved2017-09-12.
  16. ^"Default Methods".The Java Tutorials. Oracle. RetrievedJanuary 23, 2016.
  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.S2CID 17231803.
  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.S2CID 12923128.
  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.CiteSeerX 10.1.1.902.161.doi:10.1145/2647508.2647520.
  20. ^Forslund, Emil (February 3, 2016)."Definition of the Trait Pattern in Java".Age of Java. Archived fromthe original on August 4, 2016. RetrievedFebruary 3, 2016.
  21. ^Seliger, Peter (April 11, 2014)."The Many Talents of JavaScript". RetrievedJanuary 23, 2015.
  22. ^"Traits.js: Traits for JavaScript". RetrievedJanuary 23, 2016.
  23. ^Van Cutsem, Tom; Miller, Mark S. (2012)."Robust Trait Composition for Javascript"(PDF).Science of Computer Programming. RetrievedJanuary 23, 2016.
  24. ^"CocktailJS". RetrievedJanuary 23, 2016.
  25. ^Mauro Werder."SimpleTraits.jl".GitHub. RetrievedMarch 23, 2017.
  26. ^"Interfaces".Kotlin Reference. JetBrains. RetrievedJanuary 23, 2016.
  27. ^Breslav, Andrey (May 29, 2015)."Kotlin M12 is out!".Kotlin Blog. JetBrains. RetrievedJanuary 23, 2016.
  28. ^"Traits".Lasso Language Guide. LassoSoft. January 6, 2014. RetrievedJanuary 23, 2016.
  29. ^"Modular Docs - Mojo🔥 changelog".docs.modular.com. Retrieved2023-12-13.
  30. ^chromatic (April 30, 2009)."The Why of Perl Roles". RetrievedJanuary 23, 2016.
  31. ^Curtis "Ovid" Poe."Corinna OOP Proposal".Corinna RFC. RetrievedSeptember 30, 2022.
  32. ^"Traits".PHP Documentation. The PHP Group. RetrievedJanuary 23, 2016.
  33. ^Marr, Stefan (January 9, 2011)."Request for Comments: Horizontal Reuse for PHP".PHP.net wiki. The PHP Group. RetrievedJanuary 31, 2011.
  34. ^Perä, Teppo."py3traits Documentation". RetrievedJanuary 23, 2016.
  35. ^Perä, Teppo (2015-03-25)."py2traits".GitHub. RetrievedJanuary 23, 2016.
  36. ^"Higher Order Mixin Classes". Archived fromthe original on 2016-10-09.
  37. ^"Traits".The Racket Reference. RetrievedJanuary 23, 2016.
  38. ^David Naseby (February 14, 2004)."Traits in Ruby".Ruby Naseby. RetrievedJanuary 23, 2016.
  39. ^"Traits".The Rust Programming Language. RetrievedSeptember 30, 2019.
  40. ^"Traits".A Tour of Scala.École polytechnique fédérale de Lausanne. RetrievedJanuary 23, 2016.
  41. ^Neward, Ted (April 29, 2008)."The busy Java developer's guide to Scala: Of traits and behaviors".IBM developerWorks. IBM. RetrievedJanuary 23, 2016.
  42. ^"Traits in 10 minutes".Pharo: The CollaborActive Book. RetrievedJanuary 23, 2016.
  43. ^Hollemans, Matthijs (July 22, 2015)."Mixins and Traits in Swift 2.0". RetrievedJanuary 23, 2016.
  44. ^"Traits - Introduction to Programming Using Rust". Archived fromthe original on 2023-05-29.
  45. ^"Traits - the Rust Programming Language".

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Trait_(computer_programming)&oldid=1315106137"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp