Home  

Random  

Nearby  



Log in  



Settings  



Donate  



About Wikipedia  

Disclaimers  



Wikipedia





Trait (computer programming)





Article  

Talk  



Language  

Watch  

Edit  


(Redirected from Trait (computer science))
 


Incomputer 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

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

edit

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 problemofmultiple 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

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

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

Examples

edit

C#

edit

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

edit

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

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

edit

References

edit
  1. ^ a b c Schä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. 2743. Springer: 248–274. CiteSeerX 10.1.1.1011.8. doi:10.1007/978-3-540-45070-2_12. ISBN 978-3-540-45070-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.
  • ^ Fisher, Kathleen; Reppy, John (2003). "Statically typed traits" (PDF). University of Chicago. Archived (PDF) from the original on May 17, 2004. {{cite journal}}: Cite journal requires |journal= (help)
  • ^ Fisher, Kathleen; Reppy, John (2004). A typed calculus of traits (PDF). 11th Workshop on Foundations of Object-oriented Programming. University of Chicago.
  • ^ 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.
  • ^ 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.
  • ^ "Default interface methods". What's new in C# 8.0. Microsoft. Retrieved November 29, 2019.
  • ^ "Interfaces in C# 8.0 gets a makeover". Default Implementation in Interfaces in C# 8.0. Talking Dotnet. 9 September 2019. Retrieved November 29, 2019.
  • ^ "iterator_traits<Iterator>". Standard Template Library. SGI.
  • ^ Myers, Nathan C. (June 1995). "Traits: a new and useful template technique". C++ Report. Retrieved January 23, 2016.
  • ^ Abrahams, David. "Generic Programming Techniques: Traits". Boost C++ Libraries. Retrieved January 23, 2016.
  • ^ Steele, Guy; Maessen, Jan-Willem (June 11, 2006). "Fortress Programming Language Tutorial" (PDF). Sun Microsystems. Retrieved January 23, 2016.
  • ^ "Object Orientation: Traits". The Groovy Programming Language. Retrieved January 23, 2016.
  • ^ "Haxe 2.4.0 - Haxe - The Cross-platform Toolkit". Haxe - The Cross-platform Toolkit. Retrieved 2017-09-12.
  • ^ "Manual - Haxe - The Cross-platform Toolkit". Haxe - The Cross-platform Toolkit. Retrieved 2017-09-12.
  • ^ "Default Methods". The Java Tutorials. Oracle. Retrieved January 23, 2016.
  • ^ 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.
  • ^ 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.
  • ^ 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.
  • ^ Forslund, Emil (February 3, 2016). "Definition of the Trait Pattern in Java". Age of Java. Archived from the original on August 4, 2016. Retrieved February 3, 2016.
  • ^ Seliger, Peter (April 11, 2014). "The Many Talents of JavaScript". Retrieved January 23, 2015.
  • ^ "Traits.js: Traits for JavaScript". Retrieved January 23, 2016.
  • ^ Van Cutsem, Tom; Miller, Mark S. (2012). "Robust Trait Composition for Javascript" (PDF). Science of Computer Programming. Retrieved January 23, 2016.
  • ^ "CocktailJS". Retrieved January 23, 2016.
  • ^ mauro3. "SimpleTraits.jl". GitHub. Retrieved March 23, 2017.{{cite web}}: CS1 maint: numeric names: authors list (link)
  • ^ "Interfaces". Kotlin Reference. JetBrains. Retrieved January 23, 2016.
  • ^ Breslav, Andrey (May 29, 2015). "Kotlin M12 is out!". Kotlin Blog. JetBrains. Retrieved January 23, 2016.
  • ^ "Traits". Lasso Language Guide. LassoSoft. January 6, 2014. Retrieved January 23, 2016.
  • ^ "Modular Docs - Mojo🔥 changelog". docs.modular.com. Retrieved 2023-12-13.
  • ^ chromatic (April 30, 2009). "The Why of Perl Roles". Retrieved January 23, 2016.
  • ^ Curtis "Ovid" Poe. "Corinna OOP Proposal". Corinna RFC. Retrieved September 30, 2022.
  • ^ "Traits". PHP Documentation. The PHP Group. Retrieved January 23, 2016.
  • ^ Marr, Stefan (January 9, 2011). "Request for Comments: Horizontal Reuse for PHP". PHP.net wiki. The PHP Group. Retrieved January 31, 2011.
  • ^ Perä, Teppo. "py3traits Documentation". Retrieved January 23, 2016.
  • ^ Perä, Teppo (2015-03-25). "py2traits". GitHub. Retrieved January 23, 2016.
  • ^ "Higher Order Mixin Classes". Archived from the original on 2016-10-09.
  • ^ "Traits". The Racket Reference. Retrieved January 23, 2016.
  • ^ David Naseby (February 14, 2004). "Traits in Ruby". Ruby Naseby. Retrieved January 23, 2016.
  • ^ "Traits". The Rust Programming Language. Retrieved September 30, 2019.
  • ^ "Traits". A Tour of Scala. École polytechnique fédérale de Lausanne. Retrieved January 23, 2016.
  • ^ Neward, Ted (April 29, 2008). "The busy Java developer's guide to Scala: Of traits and behaviors". IBM developerWorks. IBM. Retrieved January 23, 2016.
  • ^ "Traits in 10 minutes". Pharo: The CollaborActive Book. Retrieved January 23, 2016.
  • ^ Hollemans, Matthijs (July 22, 2015). "Mixins and Traits in Swift 2.0". Retrieved January 23, 2016.
  • ^ "Traits - Introduction to Programming Using Rust".
  • ^ "Traits - the Rust Programming Language".
  • edit

    Retrieved from "https://en.wikipedia.org/w/index.php?title=Trait_(computer_programming)&oldid=1230720376"
     



    Last edited on 24 June 2024, at 09:26  





    Languages

     


    Čeština
    Deutsch
    Español
    Français
    Қазақша

    Polski
    Русский
    Simple English

     

    Wikipedia


    This page was last edited on 24 June 2024, at 09:26 (UTC).

    Content is available under CC BY-SA 4.0 unless otherwise noted.



    Privacy policy

    About Wikipedia

    Disclaimers

    Contact Wikipedia

    Code of Conduct

    Developers

    Statistics

    Cookie statement

    Terms of Use

    Desktop