Search code examples
androidkotlinsolid-principlesextension-function

Open Close Principle and Extension Functions


I have learned that Open Close Principle is allowing extension to classes and restricting from modification. So in Kotlin, when we use extension function

  1. Are we extending a class
  2. Or are we modifying a class
  3. Can extension functions in kotlin be an example for Open/Close Principle?

I assume extension means to apply inheritance and modification means to add or change code of existing class.

Thanks


Solution

  • 'Extension' in the context of the Open Closed Principle usually does not mean inheritance, it means somehow extending the class with new functionality. 'Modification' does refer to changing the code of the class, as you say.

    The extension facility of Kotlin allows you to add a method to a class without editing the code of the class. This is perfectly in keeping with the Open Closed Principle -- the class is extended with new functionality without the class itself being changed.