https://kotlinlang.org logo
#library-development
Title
# library-development
g

George

01/25/2023, 3:13 PM
Hi folks, after reading this Programming with assertions it got me thinking if i should also program like that my library. What's your input/review/pov on this? Side note: From the official libraries kotlin-team provides kotlinx.coroutines seems to follow this technique but not kotlinx.serialization. Wondering what was the decisions behind this to include or not assertions.
r

Rob Elliot

01/25/2023, 4:04 PM
I like to enforce the invariant in the constructor of a value class, to capture it in the type system. (I'm personally inclined to make the constructor private and return an
Either<Success, Failure>
from an
operator fun invoke
on the companion object, rather than throw an exception, but that's not generally considered the Kotlin Way.)
But yes, I'd say enforce your invariants in some form or another rather than assuming them. Unchecked else branches are suspicious. If you think it's impossible but the compiler doesn't prove it's impossible, chuck an exception - it should never happen, right?
3 Views