Single Responsibility Principle violated with extensions?



Module Core
class Person

Module Cache
Person.saveToCache //extension function for Person

Module Network
Person.saveToNetwork //extension function for Person

This gives flexibility because allows to use only modules that are required in the app, but I wonder does defining extensions like this violates Single Responsibility Principle?


Extension methods are syntax sugar solution for typical problem.
Now we can have PersonUtilCache.kt and PersonUtilNetwork.kt :smiley:

On more serious note, your example shows no single responsibility is violated in Person itself, cache/network are external.
Btw why implement saveToCache as extension method?


[quote=“Konstantin-Khvan, post:2, topic:2397, full:true”]
Extension methods are syntax sugar solution for typical problem.
Now we can have PersonUtilCache.kt and PersonUtilNetwork.kt :smiley: [/quote]
You can also argue that it is the other way round: Util classes are a workaround for missing extension methods. Let’s say two people write their own extension method toArrayOfSubstrings() to class String. Then the Kotlin compiler should raise an error. So the compiler makes sure there is only one responsible party. Question is whether this also works when toArrayOfSubstrings() is defined in different jars in the classpath.

Your sample is not really ideal for the discussion as saveToCache and saveToNetwork violates the idea of polymorphism in OO. Making use of polymorphism it would be and


Since extension methods have to be imported that is not an issue and is no more of a problem than 2 classes with the same name in different packages

That would depend on where the extension is defined and how it is used. If I define it in a class that has the aCache or aNetwork property to be used within the class and its implementation is to make those calls then no it doesn"t


Extension methods are one of the very nicest of the “pragmatic” features that Kotlin added. In Java, you’re forced to accomplish the same functionality either by hacking your way into the core “Person” class, or by writing a static method somewhere that takes your Person as its first argument. Kotlin extension methods are a beautifully simple syntactic sugar that converts those static methods into something that feels like an instance method on Person, making the subsequent code read much cleaner without violating the abstraction boundaries that Person sets for itself.

The only downside, I suppose, is that blurring extension methods and normal class instance methods might lead to some confusion on the programmer’s part, if you were to try to extend your Person class and override a method that, oops, turned out to only be an extension method. With all the goodies that IDEs provide to help you with this sort of thing, I wouldn’t stress out about it very much.