lundi 27 février 2023

When to use sealed interface wrappers vs just an interface?

When refactoring code like:


interface Offer {
    val sharedProperty: Property
}

class Product(...): Offer {
    override...
}

class Category(...): Offer {
    override...
}

fun Offer.doSomething(...) {
    when(this) {
        is Product -> ...
        is Category -> ...
        else -> <handle not supported implementation>
    }
}

I've recently been using this pattern quite a bit:

class Product(...)

class Category(...)

sealed interface Offer {

    val sharedProperty: Property

    class ProductOffer(
        val product: Offer
        override...
    ): Offer

    class CategoryOffer(
        val category: Category
        override...
    ): Offer
}

fun Offer.doSomething(...) {
    when(this) {
        is ProductOffer -> ...
        is CategoryOffer -> ...
    }
}

Now I realize the semantics and particularities this implies when containing an item vs being an item. I also realize consumers of my code won't be able to extend external classes with my sealed interface but I was wondering if there are other potential pitfalls from using this wrapping pattern?

Aucun commentaire:

Enregistrer un commentaire