(Read this article in french on my website)
In object-oriented programming, a Mixin is a way to add one or more predefined and autonomous functionalities to a class. Some languages provide this capability directly, while others require more effort and compromise to code Mixins. In this article, I explain an implementation of Mixins in Kotlin using delegation.
The mixin pattern is not as precisely defined as other design patterns such as Singleton or Proxy. Depending on the context, there may be slight differences in what the term means.
This pattern can also be close to the "Traits" present in other languages (e.g., Rust), but similarly, the term "Trait" does not necessarily mean the same thing depending on the language used1.
That said, here is a definition from Wikipedia:
In object-oriented programming, a mixin (or mix-in) is a class that contains methods used by other classes without needing to be the parent class of those other classes. The way these other classes access the mixin’s methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited."
You can also find definitions in various articles on the subject of mixin-based programming (2, 3, 4). These definitions also bring this notion of class extension without the parent-child relationship (or is-a) provided by classical inheritance. They further link with multiple inheritance, which is not possible in Kotlin (nor in Java) but is presented as one of the interests of using mixins.
An implementation of the pattern that closely matches these definitions must meet the following constraints:
The most trivial way to add functionalities to a class is to use another class as an attribute. The mixin’s functionalities are then accessible by calling methods of this attribute.
class MyClass { private val mixin = Counter() fun myFunction() { mixin.increment() // ... } }
This method doesn’t provide any information to Kotlin’s type system. For example, it’s impossible to have a list of objects using Counter. Taking an object of type Counter as a parameter has no interest as this type represents only the mixin and thus an object probably useless to the rest of the application.
Another problem with this implementation is that the mixin’s functionalities aren’t accessible from outside the class without modifying this class or making the mixin public.
For mixins to also define a type usable in the application, we will need to inherit from an abstract class or implement an interface.
Using an abstract class to define a mixin is out of the question, as it would not allow us to use multiple mixins on a single class (it is impossible to inherit from multiple classes in Kotlin).
A mixin will thus be created with an interface.
interface Counter { var count: Int fun increment() { println("Mixin does its job") } fun get(): Int = count } class MyClass: Counter { override var count: Int = 0 // We are forced to add the mixin's state to the class using it fun hello() { println("Class does something") } }
This approach is more satisfactory than the previous one for several reasons:
However, there remains a significant limitation to this implementation: mixins can’t contain state. Indeed, while interfaces in Kotlin can define properties, they can’t initialize them directly. Every class using the mixin must thus define all properties necessary for the mixin’s operation. This doesn’t respect the constraint that we don’t want the use of a mixin to force us to add properties or methods to the class using it.
We will thus need to find a solution for mixins to have state while keeping the interface as the only way to have both a type and the ability to use multiple mixins.
This solution is slightly more complex to define a mixin; however, it has no impact on the class using it. The trick is to associate each mixin with an object to contain the state the mixin might need. We will use this object by associating it with Kotlin’s delegation feature to create this object for each use of the mixin.
Here’s the basic solution that nevertheless meets all the constraints:
interface Counter { fun increment() fun get(): Int } class CounterHolder: Counter { var count: Int = 0 override fun increment() { count } override fun get(): Int = count } class MyClass: Counter by CounterHolder() { fun hello() { increment() // The rest of the method... } }
We can further improve the implementation: the CounterHolder class is an implementation detail, and it would be interesting not to need to know its name.
To achieve this, we’ll use a companion object on the mixin interface and the "Factory Method" pattern to create the object containing the mixin’s state. We’ll also use a bit of Kotlin black magic so we don’t need to know this method’s name:
interface Counter { // The functions and properties defined here constitute the mixin's "interface contract." This can be used by the class using the mixin or from outside of it. fun increment() fun get(): Int companion object { private class MixinStateHolder : Counter { // The mixin's state can be defined here, and it is private if not also defined in the interface var count: Int = 0 override fun increment() { count } override fun get(): Int = count } // Using the invoke operator in a companion object makes it appear as if the interface had a constructor. Normally I discourage this kind of black magic, but here it seems one of the rare justified cases. If you don't like it, rename this function using a standard name common to all mixins like `init` or `create`. operator fun invoke(): Counter { return MixinStateHolder() } } } class MyClass: Counter by Counter() { fun myFunction() { this.increment() // The rest of the method... } }
This implementation of mixins is not perfect (none could be perfect without being supported at the language level, in my opinion). In particular, it presents the following drawbacks:
class MyClass: MyMixin by MyMixin(this) {} // Compilation error: `this` is not defined in this context
If you use this inside the mixin, you refer to the Holder class instance.
To improve understanding of the pattern I propose in this article, here are some realistic examples of mixins.
This mixin allows a class to "record" actions performed on an instance of that class. The mixin provides another method to retrieve the latest events.
import java.time.Instant data class TimestampedEvent( val timestamp: Instant, val event: String ) interface Auditable { fun auditEvent(event: String) fun getLatestEvents(n: Int): Listcompanion object { private class Holder : Auditable { private val events = mutableListOf () override fun auditEvent(event: String) { events.add(TimestampedEvent(Instant.now(), event)) } override fun getLatestEvents(n: Int): List { return events.sortedByDescending(TimestampedEvent::timestamp).takeLast(n) } } operator fun invoke(): Auditable = Holder() } } class BankAccount: Auditable by Auditable() { private var balance = 0 fun deposit(amount: Int) { auditEvent("deposit $amount") balance = amount } fun withdraw(amount: Int) { auditEvent("withdraw $amount") balance -= amount } fun getBalance() = balance } fun main() { val myAccount = BankAccount() // This function will call deposit and withdraw many times but we don't know exactly when and how giveToComplexSystem(myAccount) // We can query the balance of the account myAccount.getBalance() // Thanks to the mixin, we can also know the operations that have been performed on the account. myAccount.getLatestEvents(10) }
The design pattern Observable can be easily implemented using a mixin. This way, observable classes no longer need to define the subscription and notification logic, nor maintain the list of observers themselves.
interface Observable{ fun subscribe(observer: (T) -> Unit) fun notifyObservers(event: T) companion object { private class Holder : Observable { private val observers = mutableListOf Unit>() override fun subscribe(observer: (T) -> Unit) { observers.add(observer) } override fun notifyObservers(event: T) { observers.forEach { it(event) } } } operator fun invoke(): Observable = Holder() } } sealed interface CatalogEvent class PriceUpdated(val product: String, val price: Int): CatalogEvent class Catalog(): Observable by Observable() { val products = mutableMapOf () fun updatePrice(product: String, price: Int) { products[product] = price notifyObservers(PriceUpdated(product, price)) } } fun main() { val catalog = Catalog() catalog.subscribe { println(it) } catalog.updatePrice("lamp", 10) }
There is a disadvantage in this specific case, however: the notifyObservers method is accessible from outside the Catalog class, even though we would probably prefer to keep it private. But all mixin methods must be public to be used from the class using the mixin (since we aren’t using inheritance but composition, even if the syntax simplified by Kotlin makes it look like inheritance).
If your project manages persistent business data and/or you practice, at least in part, DDD (Domain Driven Design), your application probably contains entities. An entity is a class with an identity, often implemented as a numeric ID or a UUID. This characteristic fits well with the use of a mixin, and here is an example.
interface Entity { val id: UUID // Overriding equals and hashCode in a mixin may not always be a good idea, but it seems interesting for the example. override fun equals(other: Any?): Boolean override fun hashCode(): Int } class IdentityHolder( override val id: UUID ): Entity { // Two entities are equal if their ids are equal. override fun equals(other: Any?): Boolean { if(other is Entity) { return this.id == other.id } return false } override fun hashCode(): Int { return id.hashCode() } } class Customer( id: UUID, val firstName: String, val lastName: String, ) : Entity by IdentityHolder(id) val id = UUID.randomUUID() val c1 = Customer(id, "John", "Smith") val c2 = Customer(id, "John", "Doe") c1 == c2 // true
This example is a bit different: we see that nothing prevents us from naming the Holder class differently, and nothing prevents us from passing parameters during instantiation.
The mixin technique allows enriching classes by adding often transverse and reusable behaviors without having to modify these classes to accommodate these functionalities. Despite some limitations, mixins help facilitate code reuse and isolate certain functionalities common to several classes in the application.
Mixins are an interesting tool in the Kotlin developer’s toolkit, and I encourage you to explore this method in your own code, while being aware of the constraints and alternatives.
Fun fact: Kotlin has a trait keyword, but it is deprecated and has been replaced by interface (see https://blog.jetbrains.com/kotlin/2015/05/kotlin-m12-is-out/#traits-are-now-interfaces) ↩
Mixin Based Inheritance ↩
Classes and Mixins ↩
Object-Oriented Programming with Flavors ↩
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3