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.
I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my newsletter. You can also find me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!
Top comments (0)