Do 'Sealed (exhaustive) `when` statements' break OCP(open-closed-principle)?

hi everyone,
I saw the new sealed when compiler feature on Kotlin 1.6.0 and shared it to my team, thinking we could use it, but there was an opinion that this kind of logic breaks the ocp rule because,
If you add new inheritors to the sealed class(or interface), you would have to change all the when statements that take that sealed class(which is the parent class) and thus, ocp is broken
Would this be true? We agreed that the oop rules were made before sealed classes/interfaces were introduced and this might be the “trend” of programming languagues, but still some are hesitant to use it.
Any kind of related opinion & reading material is welcome to be shared,
thanks! (편집됨)

I also shared this on the kotlin slack and got a lot of good answers

Sealed classes are not a replacement for a proper OOP and if used this way they really break OCP. They are a replacement for enums and similar cases when we prefer to have a finite set of known items. We intentionally forbid extensibility, so OCP is pretty much irrelevant in such cases (?). I’m interested whether others have a different opinion.

Also, I think enums/sealed classes are not really meant to be updated very often. They are more for cases like: Message { Request; Response } than: Animal { Dog; Cat }. Library authors should not add new sealed subtypes too often and if they do, it should be considered a backwards-incompatible change.


It’s arguable whether sealed classes/interfaces are open at all, since only the module authors can introduce new implementations, but the same authors can also modify the source code, making it not closed.

That said, I’m not sure how sealed conforming to OCP is in any way a deal breaker to you? Every final class breaks OCP; String, Int, Double, data classes, enums, etc. break OCP. Yet you wouldn’t stop using those classes and features because of that, no?

1 Like