Kotlin Code Smell 22 - Accidental Methods on Business Objects
Bloated Cars & Code: When Your Objects Carry Too Much Junk in the Trunk
Play this article
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
Keep your objects clean by focusing on their core responsibilities.
Decouple business objects from unrelated concerns.
Separate accidental concerns: Move functionality related to a specific dedicated objects (e.g. Persistence, Formatting, Serialization).
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.