ArticleslgStudy

computer science

Trait (computer programming)

Trait (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Trait (computer programming) rather than just read about it. In short: In computer programming, a trait is a language concept that represents a set of methods that can be used to extend the functionality of a class. Rationale In object-oriented programming, behavior is sometimes shared between classes which are not related to each other.

Key takeaways

  • Trait (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Trait (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Trait (computer programming) from memory before moving on to harder problems.

Reference excerpt

In computer programming, a trait is a language concept that represents a set of methods that can be used to extend the functionality of a class.

Rationale 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 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 problem of multiple 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:

symmetric sum: an operation that merges two disjoint traits to create a new trait override (or asymmetric sum): an operation that forms a new trait by adding methods to an existing trait, possibly overriding some of its methods alias: an operation that creates a new trait by adding a new name for an existing method exclusion: an operation that forms a new trait by removing a method from an existing trait. (Combining this with the alias operation yields a shallow rename operation). 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)).

Limitations While traits offer significant advantages over many alternatives, they do have their own limitations.

Required methods 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 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 Traits originate in the programming language Self and are supported by these programming languages:

AmbientTalk: Combines the properties of Self traits (object-based multiple inheritance) and Smalltalk's Squeak traits (requiring explicit composition of traits by the programmer). It builds on the research on stateful and freezable traits to enable state within traits, which was not allowed in the first definitions. C#: Since version 8.0, C# supports default interface methods, which have some properties of traits. C++: Used in Standard Template Library and the C++ Standard Library to support generic container classes and in the Boost TypeTraits library. Curl: Abstract classes as mixins permit method implementations and thus constitute traits by another name. Fortress Groovy: Since version 2.3 Haskell: Traits are named Type classes. Haxe: Since version 2.4.0. Called Static Extension in the manual, it uses using keyword Java: Since version 8, Java supports default methods, which have some properties of traits. JavaScript: Traits can be implemented via functions and delegations or through libraries that provide traits. Julia: Several packages implement traits, e.g., Kotlin: Traits have been called interfaces since M12. Lasso Mojo: Since version 0.6.0 OCaml: Traits can be implemented using a variety of language features: module and module type inclusion, functors and functor types, class and class type inheritance, et cetera. Perl: Named roles, they are implemented in Perl libraries such as Moose, Role::Tiny and Role::Basic. Roles are part of the sister language Raku. With the acceptance of the Corinna OOP Proposal Perl will have roles native to the language as part of a modern OOP system. PHP: Since version 5.4, PHP allows users to specify templates that provide the ability to "inherit" from more than one (trait-)class, as a pseudo multiple inheritance. Python: Via a third-party library, or via higher-order mixin classes Racket: Supports traits as a library and uses macros, structures, and first-class classes to implement them. Ruby: Module mixins can be used to implement traits. Rust Scala trait is builtin supported with the key word trait. Smalltalk: Traits are implemented in two dialects of Smalltalk, Squeak and Pharo. Swift: Traits can be implemented with protocol extensions.

Examples

C# On C# 8.0, it is possible to define an implementation as a member of an interface.

PHP This example uses a trait to enhance other classes:

This allows simulating aspects of multiple inheritance:

Rust A trait in Rust declares a set of methods that a type must implement. Rust compilers require traits to be explicated, which ensures the safety of generics in Rust.

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. Derivable traits include: Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord and Hash.

See also Extension method Interface (object-oriented programming) Parametric polymorphism UFCS

References

External links "Traits: Composable Units of Behavior". Software Composition Group. University of Bern.

Worked examples

Example 1 — a first encounter with Trait (computer programming)

Start with the simplest possible case. Write down what Trait (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Trait (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Trait (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Trait (computer programming)

In research
Trait (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Trait (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Trait (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Programming language topics, Type theory, so understanding it makes those chapters shorter.
In everyday life
Look for Trait (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Trait (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Trait (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Trait (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Trait (computer programming) in simple terms?

In computer programming, a trait is a language concept that represents a set of methods that can be used to extend the functionality of a class. Rationale In object-oriented programming, behavior is sometimes shared between classes which are not related to each other.

Why does Trait (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Trait (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Trait (computer programming).

Tags

  • C++
  • Programming language topics
  • Type theory

Keep exploring