Kotlin Code Smell 22 - Accidental Methods on Business Objects

Kotlin Code Smell 22 - Accidental Methods on Business Objects

Bloated Cars & Code: When Your Objects Carry Too Much Junk in the Trunk

Adding code for persistence, serialization, displaying, importing, and exporting to an object can lead to bloating its protocol and create unnecessary coupling.

Problem

  • Readability

  • Coupling

  • Maintainability

Solution

  1. Keep your objects clean by focusing on their core responsibilities.

  2. Decouple business objects from unrelated concerns.

  3. Separate accidental concerns: Move functionality related to a specific dedicated objects (e.g. Persistence, Formatting, Serialization).

  4. Keep the essential protocol of your objects concise and focused.

Examples

  • Persistence

  • Identifiers

  • Serialization

  • Formatting

Sample Code

Wrong

class Car(
    private val company: Company,
    private val color: Color,
    private val engine: Engine
) {
    fun goTo(coordinate: Coordinate) {
        move(coordinate)
    }

    fun startEngine() {
        engine.start()
    }

    fun display() {
        println("This is a $color $company")
    }

    fun toJson(): String {
        return "json"
    }

    fun updateOnDatabase() {
        database.update(this)
    }

    fun getId(): Int {
        return id
    }

    fun fromRow(row: Row) {
        database.convertFromRow(row, this)
    }

    fun forkCar() {
        // Concurrency is accidental
        ConcurrencySemaphoreSingleton.getInstance().forkCar(this)
    }

    // ...
}

Right

class Car(
    private val company: Company,
    private val color: Color,
    private val engine: Engine
) {
    fun goTo(coordinate: Coordinate) {
        move(coordinate)
    }

    fun startEngine() {
        // Code to start the engine - all logic was extracted
        engine.start()
    }

    // ...
}

Exceptions

  • In some cases, certain frameworks may force us to inject code related to unrelated concerns into our objects (e.g., identifiers). In such cases, it is advisable to explore better frameworks that allow for cleaner designs.

Conclusion

It is common to encounter business objects with mixed responsibilities. However, it is essential to consider the consequences and coupling that such designs can introduce.

Credits

Did you find this article valuable?

Support Yonatan Karp-Rudin by becoming a sponsor. Any amount is appreciated!