Trait (computer programming)

From Wikipedia, the free encyclopedia

In computer programming, a trait is a collection of methods, used as a "simple conceptual model for structuring object-oriented programs"[1][2] similar to mixins. Traits provide a simple way to create classes that reuse behavior from software components.

An object defined as a trait is created as the composition of methods, which can be used by other classes without requiring multiple inheritance. In case of a naming collision, when more than one traits to be used by one class have methods with the same name, the programmer must explicitly disambiguate which one of those methods will be used in the class; thus manually solving the "diamond problem" of repeated inheritance. This is different from other composition methods in object-oriented programming, where conflicting names are automatically resolved by scoping rules.

Whereas mixins can be composed only using the inheritance operation, traits offer a much wider selection of operations, including symmetric sum[clarify], method exclusion[clarify], and aliasing[clarify]. A trait differs from an interface in that it provides implementations of its methods, not just type signatures.

Supported languages

Traits come from the Self programming language[3] and are supported by the following programming languages:

  • Fortress programming language: Where they also play the role of types.
  • JavaScript: With the Joose framework or by using just this languages functional core features - a function object that implements behavior in a stateless way is delegated via call or apply to objects that are in need of it.[4]
  • Perl 5: With the Moose module.
  • Perl 6: It calls them "roles".
  • Squeak Smalltalk
  • D: using __traits language extension [5] and std.traits module[6] helper templates, for compile time traits. Available in D 2 since version 2.003, with later extended functionality. Together with other language features (notably templets and mixins) they allow flexible automatic generation of methods based on interfaces and types. D also allows explicit aliasing of member methods and variables, including forwarding to multiple member classes.[7]
  • Pharo
  • PHP 5.4[8]
  • Ruby[9] Modules can be used to implement traits.
  • Rust
  • Lasso[10]
  • Scala[11]The busy Java developer's guide to Scala: Of traits and behaviors
  • Python (programming language), using the Trait package[12]

Traits for the Smalltalk programming language were initially developed at the Software Composition Group, University of Bern.[13] AmbientTalk combines the properties of Self traits (object-based multiple inheritance) and Smalltalk's Squeak traits (requiring explicit composition of traits by the programmer); AmbientTalk builds upon the research on stateful and freezable traits to enable state within traits, which was not allowed in the first definitions.[14]

The concept has been applied as libraries to mainstream languages like C++, PHP, and Javascript.[15]

Traits have the following properties
  • Provides a set of methods that implement behaviour.
  • Requires a set of methods that parameterize the provided behaviour.
Can be composed
  • Trait composition is symmetric[clarify] and conflicting methods are excluded from the composition.
  • Can be nested, but the nesting has no semantics for classes.

Nested traits are equivalent to flattened traits[clarify].[16] Abstract classes as mixins in the multiple-inheritance Curl programming language permit method implementations and thus constituted traits by another name. Module mixins in Ruby are similar to traits to some degree. Racket supports traits as a library and uses macros, structures, and first-class classes to implement them.

Implementation

In computer programming, a traits class is a class template used to associate state and/or behaviour to a compile-time entity, typically a data type or a constant, without modifying the existing entity. In the C++ programming language and PHP programming language, this is normally achieved by defining a primary class template, and creating explicit or partial specializations for the relevant types.

It is used in Standard Template Library and the C++ standard library to support generic container classes. The technique is used extensively in the Boost TypeTraits library.

Traits function differently in PHP. Since version 5.4.0,[8] PHP allows users to specify templates that provide the ability to "inherit" from more than one (trait-)class, as a pseudo multiple inheritance. Traits in PHP are not as dynamic as C++ in using different data types.

Examples

PHP

Since version 5.4.0 PHP allows traits. This example uses one template class (trait) to enhance another class:

// the template
trait TSingleton {
  private static $_instance = null;
 
  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 gives the user power to simulate 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;
 
  function fillColor($color) {
    // ...
  }
}

References

  1. Nathanael Schärli, Stéphane Ducasse, 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, Volume 2743, Springer-Verlag, 2003, pp. 248-274
  2. Stéphane Ducasse, Oscar Nierstrasz, Nathanael Schärli, Roel Wuyts, Andrew P. Black: Traits: A mechanism for fine-grained reuse. ACM Trans. Program. Lang. Syst. 28(2): 331-388 (2006)
  3. G. Curry, L. Baer, D. Lipkie, and B. Lee. Traits: An approach to multiple-inheritance subclassing. In SIGOA conference on Office Information Systems, pages 1–9, Philadelphia, Pennsylvania, USA, 1982. ACM Press
  4. JavaScript Code Reuse Patterns, April 19, 2013.
  5. http://dlang.org/traits.html
  6. http://dlang.org/phobos/std_traits.html
  7. http://dlang.org/class.html#AliasThis
  8. 8.0 8.1 Marr, Stefan. "Request for Comments: Horizontal Reuse for PHP". The PHP.net wiki. The PHP Group. Retrieved 31 January 2011. 
  9. http://ruby-naseby.blogspot.co.at/2008/11/traits-in-ruby.html
  10. http://lassoguide.com/language/traits.html
  11. http://www.scala-lang.org/node/126 A Tour of Scala: Traits
  12. http://code.enthought.com/projects/traits
  13. http://scg.unibe.ch/cgi-bin/scgbib.cgi?query=nathanael+traits+composable+units+ecoop
  14. Adding State and Visibility Control to Traits Using Lexical Nesting. Genoa Proceedings of the 23rd European Conference on ECOOP 2009 --- Object-Oriented Programming table of contents. Editor: Sophia Drossopoulou Department of Computing, Imperial College London, London, UK SW7 2AZ. Pages 220 - 243. Publisher Springer-Verlag Berlin, Heidelberg ©2009 ISBN 978-3-642-03012-3 doi>10.1007/978-3-642-03013-0_11. Appears in LNCS: Lecture Notes In Computer Science.
  15. Robust Trait Composition for Javascript. Tom Van Cutsem, Mark S. Miller
  16. http://web.cecs.pdx.edu/~black/publications/TR_CSE_02-012.pdf

External links

This article is issued from Wikipedia. The text is available under the Creative Commons Attribution/Share Alike; additional terms may apply for the media files.