https://kotlinlang.org logo
#codereview
Title
# codereview
s

Szymon Jeziorski

03/27/2022, 11:55 AM
Hello, I have a use case where I have 2 separate files witch expose public top-level functions (extension functions for mapping objects) calling private helper functions inside them. The issue is that some of those private functions duplicate and I would like to reuse them rather than copy-paste them and don't want to make them public so that they're visible from everywhere. The first thing that comes to my mind is OOP approach where I encapsulate those private functions to an abstract class, implement public extensions inside singleton objects inheriting this abstract class, and then import those extensions statically when used to work on them as on top-level functions. Example: SampleModifications.kt:
Copy code
abstract class SampleModifications {
    protected fun helper1(...) [...]

    protected fun SampleField.helper2(...) [...]
}
helpers usage: SampleMapper.kt
Copy code
object SampleMapper : SampleModifications() {
    fun Sample.toSomethingElse() = [...] // calling helper1 from SampleModifications inside

    [...]
}
extensions usage:
Copy code
import [...].SampleMapper.toSomethingElse

[...]

sampleRepository.findByIdOrNull(id)?.toSomethingElse()
This works fine and does what I want but declaring abstract classes for such use case seems like overkill for me so wondering if I could achieve the same cleaner or maybe more idiomatic, how would you approach it?
i

ildar.i [Android]

03/27/2022, 7:41 PM
It's not really clear what you are doing with all those omissions. Are helper1 and helper2 the same? Do you want to call the same function as a child class and as an extension? What you can do to avoid inheritance is composition. For example, you can make a delegate class (or object) which would do the inner job instead of a parent class
a

alex.krupa

04/02/2022, 8:43 AM
Inheritance with abstract classes does seem like overkill. If those mapping functions live in a smaller module I'd keep the helpers
internal
, because then visibility impact isn't that big. If not, and they're part of a monolithic or just a larger module, I'd merge both files into one, that way you can still have those shared
private
helpers.
4 Views