Traits vs. Interfaces vs. Mixins? Traits vs. Interfaces vs. Mixins? ruby ruby

Traits vs. Interfaces vs. Mixins?


Every reference type in Java, except Object, derives from one single superclass.

By the way, Java classes may implement zero or more interfaces.

Generally speaking, an interface is a contract that describes the methods an implementing class is forced to have, though without directly providing an implementation.

In other words, a Java class is obliged to abide its contract and thus to give implementation to method signatures provided by the interfaces it declares to implement.

An interface constitutes a type. So you can pass parameters and have return values from methods declared as interface types, requiring that way that parameters and return types implement particular methods without necessarily providing a concrete implementation for them.

This sets the basis for several abstraction patterns, like, for example, dependency injection.

Scala, on its own, has traits. Traits give you all the features of Java interfaces, with the significant difference that they can contain method implementations and variables. Traits are a smart way of implementing methods just once and - by means of that - distribute those methods into all the classes that extend the trait.Like interfaces for Java classes, you can mix more than one trait into a Scala class.

Since I have no Ruby background, though, I'll point you to an excerpt from David Pollak's "Beginning Scala" (amazon link):

Ruby has mixins, which are collections of methods that can be mixed into any class. Because Ruby does not have static typing and there is no way to declare the types of method parameters, there’s no reasonable way to use mixins to define a contract like interfaces. Ruby mixins provide a mechanism for composing code into classes but not a mechanism for defining or enforcing parameter types.

Interfaces can do even more than is described in this post; as the topic can be vast, I suggest you to investigate more in each one of the three directions, while if you even have Java background, Scala and therefore traits are affordable to learn.