„Wenn ein Arbeiter seine Arbeit gut machen will, muss er zuerst seine Werkzeuge schärfen.“ – Konfuzius, „Die Gespräche des Konfuzius. Lu Linggong“
Titelseite > Programmierung > Implementieren von Mixins (oder Merkmalen) in Kotlin mithilfe von Delegation

Implementieren von Mixins (oder Merkmalen) in Kotlin mithilfe von Delegation

Veröffentlicht am 15.11.2024
Durchsuche:519

Implementing Mixins (or Traits) in Kotlin Using Delegation

(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.

  • Objective
    • Definition of the "Mixins" Pattern
    • Characteristics and Constraints
  • Implementation
    • Naive Approach by Composition
    • Use of Inheritance
    • Delegation to Contain the Mixin’s State
    • Final Implementation
  • Limitations
  • Examples
    • Auditable
    • Observable
    • Entity / Identity
  • Conclusion

Objective

Definition of the "Mixins" Pattern

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.

Characteristics and Constraints

An implementation of the pattern that closely matches these definitions must meet the following constraints:

  • We can add several mixins to a class. We’re in an object-oriented context, and if this constraint weren’t met, the pattern would have little interest compared to other design possibilities like inheritance.
  • Mixin functionality can be used from outside the class. Similarly, if we disregard this constraint, the pattern will bring nothing we couldn’t achieve with simple composition.
  • Adding a mixin to a class does not force us to add attributes and methods in the class definition. Without this constraint, the mixin could no longer be seen as a "black box" functionality. We could not only rely on the mixin’s interface contract to add it to a class but would have to understand its functioning (e.g., via documentation). I want to be able to use a mixin as I use a class or a function.
  • A mixin can have a state. Some mixins may need to store data for their functionality.
  • Mixins can be used as types. For example, I can have a function that takes any object as a parameter as long as it uses a given mixin.

Implementation

Naive Approach by Composition

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.

Use of Inheritance

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:

  • The class using the mixin doesn’t need to implement the mixin’s behavior thanks to default methods
  • A class can use multiple mixins as Kotlin allows a class to implement multiple interfaces.
  • Each mixin creates a type that can be used to manipulate objects based on the mixins included by their class.

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.

Delegation to Contain the Mixin’s State

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...
    }
}

Final Implementation

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...
    }
}

Limitations

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:

  • All mixin methods must be public. Some mixins contain methods intended to be used by the class using the mixin and others that make more sense if called from outside. Since the mixin defines its methods on an interface, it is impossible to force the compiler to verify these constraints. We must then rely on documentation or static code analysis tools.
  • Mixin methods don’t have access to the instance of the class using the mixin. At the time of the delegation declaration, the instance is not initialized, and we can’t pass it to the mixin.
    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.

Examples

To improve understanding of the pattern I propose in this article, here are some realistic examples of mixins.

Auditable

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): List

    companion 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)
}

Observable

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).

Entity / Identity

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.

Conclusion

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.


  1. 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) ↩

  2. Mixin Based Inheritance ↩

  3. Classes and Mixins ↩

  4. Object-Oriented Programming with Flavors ↩

Freigabeerklärung Dieser Artikel ist abgedruckt unter: https://dev.to/zenika/implementing-mixins-or-traits-in-kotlin-using-delegation-3pkh?1 Bei Verstößen wenden Sie sich bitte an [email protected], um ihn zu löschen Es
Neuestes Tutorial Mehr>

Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.

Copyright© 2022 湘ICP备2022001581号-3