```open class ParticipantsExtension { companio...
# codereview
j
Copy code
open class ParticipantsExtension {
    companion object {
        const val ELEMENT = "participants"
    }

    open fun getElement() = ELEMENT

    fun parse() {
        // common code used with ELEMENT from child
    }
}

class UpdatedParticipantsExtension : ParticipantsExtension() {
    companion object {
        const val ELEMENT = "updated-participants"
    }
    override fun getElement() = ELEMENT
}

class AddedParticipantsExtension : ParticipantsExtension() {
    companion object {
        const val ELEMENT = "added-participants"
    }
    override fun getElement() = ELEMENT
}
IS there a better way with no redundant code ? I must access overridden
ELEMENT
as static fiel in an other class, AND use
ELEMENT
in the base function
parse()
with the overridden value
g
Are you planning on using the
getElement()
value or is it just for conditional logic? If it's only for conditional logic, you could replace the above with Sealed Classes and have an exhaustive
when
statement to handle all cases
m
or implement the specific functionality in each class. Depends on exactly what is being done. But ultimately, shouldn't need/use the static elements. Either do it by Type, but I would also recommend
sealed class
as the correct approach here.
j
yes
getElement()
is for use inside the parent method
parse()
. So i guess sealed class with a property in the parent class and overirded in each child class constructor is the best choice ?
m
I would get rid of ELEMENT in companion and just use an overridable property (it’s a literal constant so the JVM will intern it). You could even eliminate
getElement()
and just use the property. About using sealed classes, consider if this hierarchy has to be closed only for you to control, or can be extended by users of your code — if it’s a library. Using
sealed
cuts off the latter possibility,
👍 1
j
contrary to the article that says "enum with superpowers", sealed classes seem a bit like hitting a fly with a sledge hammer for enum usecases
m
I think the intent is to express 'when an enum isn't enough for the job, then a sealed class is more powerful, and better than a plain old class hierarchy'. It certainly isn't saying 'replace all usage of enum with sealed class'.
j
while that may be the case, i seem to be the first person to mention enums for an enum-applicable solution? maybe i missed a comment somewhere
i would think an enum is parsimonious and clearer for utilities with singletons