Kotlin Code Smell 13 - Companion Object Functions

Kotlin Code Smell 13 - Companion Object Functions

Yet another global access coupled with laziness that cannot be mocked.

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()))
}

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())
}

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.

More info

Credits