Skip to main content

Command Palette

Search for a command to run...

Kotlin Code Smell 25 - State as Properties

Avoiding State Pitfalls

Updated
1 min read
Kotlin Code Smell 25 - State as Properties
Y

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

  1. Use immutable objects

  2. The model states as mathematical set inclusion.

  3. 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.

Credits

Kotlin Code Smells

Part 12 of 36

In this series, we will see several symptoms and situations that make us doubt the quality of our development. We will present possible solutions. Most are just clues. They are no hard rules.

Up next

Kotlin Code Smell 24 - Tackling Too Many Attributes

Trimming the Attribute Fat

More from this blog

Yonatan Karp-Rudin | kotlin for backend developer skills | java for backend developer skills | SpringBoot | Tutorials

57 posts

Experienced Senior Software Engineer passionate about functional programming & Kotlin. Excels in app development, optimization, and team collaboration. Let's create something amazing!