Chapter 21. Exceptions to Values

In Chapter 19 we looked at error-handling strategies for Kotlin, and how to refactor from exceptions in Java to more functional techniques. The truth is that most code ignores errors in the hope that they won’t happen. Can we do better?

Someone new in marketing has taken to tweaking the spreadsheet that we last saw in Chapter 20—the one that generates the high-value customer scores. We don’t know what they are doing in detail, but they keep on exporting files that break our parsing and then asking us to explain what a stack trace is. It’s getting a bit embarrassing on both sides of the relationship, so the cake has begun to dry up. Could there be any more incentive?

Well yes, there could. We’ve also been asked to write an unattended job so that marketing can save the file onto a server, and we will automatically write the summarized version. Without a person in the loop to interpret those stack traces, it looks like we’ll have to find a way to report errors properly.

Identifying What Can Go Wrong

Here’s the code as we left it:

fun Sequence<String>.toHighValueCustomerReport(): Sequence<String> {
    val valuableCustomers = this
        .withoutHeader()
        .map(String::toCustomerData)
        .filter { it.score >= 10 }
        .sortedBy(CustomerData::score)
        .toList()
    return sequenceOf("ID\tName\tSpend") +
        valuableCustomers.map(CustomerData::outputLine) +
        valuableCustomers.summarised()
}

private fun List<CustomerData>.summarised(): String =
    sumByDouble { it.spend }.let { total ...

Get Java to Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.