Content deleted Content added
m →Supported languages: The Corinna OOP project for Perl is making traits native to the language. |
→Characteristics: This article was flagged as "too technical", so I provided an opening paragraph with a simplified description of traits. |
||
Line 5:
==Characteristics==
In object-oriented programming, we frequently encounter behavior shared by classes, even if those classes are not related to each other. For example, we may wish to be able to [[Serialization|serialize]] to [[JSON]] many unrelated classes for use in a [[Representational state transfer|REST API]]. Historically, there have been several approaches to solve this without duplicating the code in every class needing the behavior. Popular approaches have been [[multiple inheritance]] and [[mixin|mixins]], but the behavior of the code may unexpectedly change if you alter the order in which you inherit or "mix in" behavior. Behavior can also unexpectedly change if you add new methods to your parent classes or mixins. [[Delegation (computing)|Delegation]] is another approach, but if the object you're delegating to requires information from the class that contains the delegate, this can mean having to write additional code to handle this. 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 and the methods provided by the traits have direct access to the data of the class.
Traits both provide a set of methods that implement behaviour to a class, and require that the class implement a set of methods that [[Parameter (computer programming)|parameterize]] the provided behaviour.
|