Kotlin:
Refactoring

How to:

Here’s a Kotlin snippet showing a common code smell and its refactored version. We start with a chunk of code that’s doing too much:

fun processOrders(orders: List<Order>) {
    for (order in orders) {
        print("Order ID: ${order.id}")
        // Calculating order total
        var total = 0.0
        for (item in order.items) {
            total += item.price
        }
        // Apply discount
        if (order.customer.isVIP) {
            total *= 0.9
        }
        print("Total: $total")
        // More processing...
    }
}

Refactored for better readability and separation of concerns:

fun printOrderSummary(order: Order) {
    print("Order ID: ${order.id}")
    val total = calculateTotal(order)
    print("Total: $total")
}

fun calculateTotal(order: Order): Double {
    var total = order.items.sumOf { it.price }
    return if (order.customer.isVIP) total * 0.9 else total
}

fun processOrders(orders: List<Order>) {
    orders.forEach { printOrderSummary(it) }
}

No sample output here since we didn’t change the functionality, but the code readability and maintainability got a huge boost!

Deep Dive

Refactoring as a concept has been around since programming began, but it really took off as a discipline in the 1990s, especially after Martin Fowler published “Refactoring: Improving the Design of Existing Code” in 1999. This book gave a name to the practice and defined an organized method for applying it, including a catalog of refactoring techniques.

Comparing refactoring to alternatives: you could rewrite code from scratch (risky and time-consuming), or simply make additive changes (leads to software bloat and potential tech debt). Refactoring hits the sweet spot—it modernizes and cleans up while keeping the risk low.

Implementation wise, it’s essential to have a robust set of tests before you start refactoring to ensure you don’t accidentally change the program’s behavior. Many modern IDEs (including IntelliJ for Kotlin) have automated refactoring tools to rename variables, extract methods, and more, which can speed up the process and reduce errors.

See Also