May 2025
Intermediate to advanced
424 pages
6h 12m
Chinese
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
输入和输出是代码中的问题所在。 当文件消失或网络套接字失效时,我们的程序与外界对话就会出错。 I/O 也是一种操作,因此限制了我们对代码进行推理和重构的能力。 如何限制 I/O 导致的问题的范围?
前面的章节已经为我们打下了一定的基础,现在我们要加快步伐,直接进入重构阶段,边做边学。
在 第 10 章中,我们研究了一些为市场营销制作报告的 Java 代码。当我们离开代码时,我们已经在HighValueCustomersReport 中引入了扩展函数,为我们提供了:
@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()}"}
以下是转换为 Kotlin 后的测试结果:
classHighValueCustomersReportTests{@Testfuntest(){check(inputLines=listOf("ID\tFirstName\tLastName\tScore\tSpend","1\tFred\tFlintstone\t11\t1000.00","4\tBetty\tRubble\t10\t2000.00","2\tBarney\tRubble\t0\t20.00","3\tWilma\tFlintstone\t9\t0.00"),expectedLines=listOf("ID\tName\tSpend","4\tRUBBLE, Betty\t2000.00","1\tFLINTSTONE, Fred\t1000.00","\tTOTAL\t3000.00"))}...privatefun ...
Read now
Unlock full access