Trait (computer programming)

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

The use of traits allows the horizontal reusing a collection of methods. The principle of multiple inheritance, which offer some object-oriented programming languages, the same procedure is possible; However circumvent traits (such as as well as mixins ), Diamond - problem, a specially caused by the multiple inheritance relationship problem under different classes.

Traits as a special variant of mixins

Unlike a mixin traits are much more flexible in the integration into other classes. Way, individual methods exclude a trait or replace it with another. Several traits can be included in a class, and can resolve naming conflicts by using aliases in order to guarantee the use gleichbenannter methods. 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 provides a trait also the possibility to define class attributes.

Examples

PHP

In the PHP programming language traits can be used as of version 5.4:

Hello trait {      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 will output "Hello World! " from.

Programming languages ​​that support traits

  • Curl
  • Fortress
  • Leg ( possible with the additional library Composure )
  • JavaScript (eg with the additional library traits.js possible, or natively by about [call ] or [apply ] delegated functions)
  • Perl 5 ( roles, through the module mosses)
  • Perl 6 (also known there as roles )
  • Pharo Smalltalk
  • PHP version 5.4
  • Python ( for example by the module trait )
  • Self
  • Scala
  • Rust
782141
de