Trait (programming)

from Wikipedia, the free encyclopedia

A trait is a term from object-oriented programming and describes a reusable collection of methods and attributes , similar to a class . The idea of ​​traits originates from the programming language Self and is now used in many modern object-oriented languages.

The use of traits allows a collection of methods to be reused horizontally. The same approach is possible with the principle of multiple inheritance that some object-oriented programming languages ​​offer; however, traits (as well as mixins ) circumvent the diamond problem , a relationship problem among different classes that is specifically caused by multiple inheritance.

Traits as a special variant of the mixins

In contrast to a mixin , traits are much more flexible when integrated into other classes. In this way, individual methods of a trait can be excluded or replaced by another. Several traits can also be included in one class, whereby name conflicts can be resolved with the help of aliases in order to guarantee the use of methods with the same name. A trait can also use methods that are only part of the including class and were not defined in the trait itself. Compared to a mixin, a trait also offers the option of defining class attributes .

Examples

PHP

In the PHP programming language , traits from version 5.4 can be used:

trait Hello
{
    public function sayHello()
    {
        echo 'Hello ';
    }
}

trait World
{
    public function sayWorld()
    {
        echo 'World';
    }
}

class HelloWorld
{
    use Hello, World;

    public function sayExclamationMark()
    {
        echo '!';
    }
}

$objHelloWorld = new HelloWorld;

$objHelloWorld->sayHello();

$objHelloWorld->sayWorld();

$objHelloWorld->sayExclamationMark();

The above example prints “Hello World!”.

Programming languages ​​that support traits

Web links

Individual evidence

  1. kingcrunch.de: PHP5.4: Traits aka "Horizontal Reuse"
  2. Introduction to Traits on php.net
  3. Traits in Fortress (English, PDF file; 2.5 MB)
  4. Introducing Composure for Haxe (with Dependency Injection)
  5. ^ Moose :: Role Documentation
  6. PyPI: traits 4.4.0
  7. Perl 6: roles and traits ( Memento of the original from September 21, 2011 in the Internet Archive ) Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. @1@ 2Template: Webachiv / IABot / chris.prather.org
  8. ^ Rust Reference Manual: Traits