kotlinkotlin-extensionopen-closed-principle

Are Kotlin extension methods a good example of the Open/Closed Principle?


The Open/Closed Principle is sometimes hard to grasp but it seems to me that Kotlin extension methods are a prime example because they allow classes to remain closed to modification but open to extension.

Am I understanding the principle correctly?


Solution

  • In my eyes general idea behind OCP is how to modify (extend) software behavior without rewriting it much and do not break existing functionalities.

    Kotlin's extensions extend capabilities of a type however it is resolved statically, there is no dynamic function dispatch. In other words it's just a handy form to pack code that somehow relates to receiver.

    A textbook example of OCP is polymorphism. It gives ability to modify software behavior simply adding a new implementation of polymorphic type and replace existing one.

    an everyday example is passing a callback:

    fun <T, R> f(a: String, callback: (T) -> R) {}
    

    Via callback we can modify function behavior but cannot change its logic. So it is open to extend but closed to changes.