Kotlin Code Smell 25 - State as Properties
Avoiding State Pitfalls

I've started to work as a software engineer at 2014, however, I started to write code at high-school.
My first language was Assembly, but still, I fall in love with the possibilities to make the computer to do as you wish, shortly after that I started to write in C.
Later on I studied a practical engineering in electricity, and during this time discovered that I preferred much more writing code than design electrical components.
As a result of this understanding I decided to switch and study bachelor degree in computer science in Reichman university, where the focus was of the Java language.
Today I'm working at SumUp using Kotlin, SpringBoot & Micronaut, Cassandra and Kafka
When an object changes its state, the best solution is to modify the attribute, right?
Problems
Mutability
Attribute Polluting
Setters
Solutions
Use immutable objects
The model states as mathematical set inclusion.
Separate the state from the object as it is accidental.
Examples
- State diagrams
Sample Code
Wrong
sealed class OrderState
data object OrderStatePending : OrderState()
data object OrderStateConfirmed: OrderState()
class Order(private val items: List<Int>) {
private var state: OrderState = OrderStatePending
fun changeState(newState: OrderState) {
state = newState
}
}
Right
sealed class OrderState
data object OrderStatePending : OrderState()
data object OrderStateConfirmed: OrderState()
data class Order(val items: List<Int>, val state: OrderState)
val items = listOf(1, 2, 3)
val pendingOrder = Order(items, OrderStatePending)
val confirmedOrder = pendingOrder.copy(state = OrderStateConfirmed)
Exceptions
Over Design
Performance issues (if a serious benchmark supports it).
Conclusion
This technique is elegant but can lead to overdesign. For example, changing a visual component's color should be a counterexample of this smell.
We should be aware and very cautious as with any other smell.
These are hints and not rigid rules.




