DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

Kotlin Smell 13 - Companion Object Functions

TL;DR: Companion object functions are globally available and cannot be replaced for testing.

Problems

  • Coupling

  • Testability

  • Protocol Overloading

  • Cohesion

Solutions

  • Honor the Single Responsibility Principle by creating an instance for a class whenever possible.

  • Delegate the method to the instance, if feasible.

  • Create stateless objects instead of referring to them as "helpers."

Examples

  • Static class initializers

  • Static class methods

  • Static attributes

Sample Code

Wrong

class DateStringHelper {
    companion object {
        private val formatter = 
            DateTimeFormatter.ofPattern("yyyy-MM-dd")

        fun format(date: OffsetDateTime): String  =
            formatter.format(date)
    }
}

fun main() {
    print(DateStringHelper.format(OffsetDateTime.now()))
}
Enter fullscreen mode Exit fullscreen mode

Right

class DateToStringFormatter(private val date: OffsetDateTime) {

    fun englishFormat(): String {
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        return formatter.format(date)
    }
}

fun main() {
    print(DateToStringFormatter(OffsetDateTime.now()).englishFormat())
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using companion object methods pollutes the class protocol with "library methods," which breaks cohesion and generates coupling. It is advisable to extract them through refactorings.

We cannot manipulate companion classes and use them polymorphically, so we can't mock or test them effectively.

As a result, we end up with a globally accessible reference that is challenging to decouple.


Stay updated with my latest thoughts and ideas by registering for my newsletter. Connect with me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!


More info

Credits

Top comments (0)