August 2021
Intermediate to advanced
422 pages
10h 18m
English
Input and output are problematic in code. Our program is subject to errors talking to the outside world when files disappear or network sockets fail. I/O is also an action and so limits our ability to reason with and refactor our code. How can we limit the scope of the problems that I/O causes?
Now that earlier chapters have built some foundations, we’re going to up the pace here, going straight into refactoring and learning lessons as we go.
In Chapter 10, we looked at some Java code that produced a report for marketing.
When we left the code, we had introduced extension functions to the HighValueCustomersReport, giving us:
@Throws(IOException::class)fungenerate(reader:Reader,writer:Writer){valvaluableCustomers=reader.readLines().toValuableCustomers().sortedBy(CustomerData::score)writer.appendLine("ID\tName\tSpend")for(customerDatainvaluableCustomers){writer.appendLine(customerData.outputLine)}writer.append(valuableCustomers.summarised())}privatefunList<String>.toValuableCustomers()=withoutHeader().map(String::toCustomerData).filter{it.score>=10}privatefunList<String>.withoutHeader()=drop(1)privatefunList<CustomerData>.summarised():String=sumByDouble{it.spend}.let{total->"\tTOTAL\t${total.toMoneyString()}"}
Here are the tests after conversion to Kotlin:
class ...Read now
Unlock full access