Java to Kotlin by Duncan McGregor

Java to Kotlin by Duncan McGregor

Author:Duncan McGregor
Language: eng
Format: epub
Publisher: O'Reilly Media
Published: 2021-08-20T00:00:00+00:00


Calculate per-currency totals, so the calculation doesn’t accumulate rounding errors.

Convert costs to the traveler’s preferred currency.

Calculate the grand total in the traveler’s preferred currency.

Sort the currency conversions in alphabetical order of the original currency code.

Store the currency conversions and grand total so they can be displayed to the traveler.

Such smearing of responsibilities across classes is common when we compute by mutating shared state. We’d like to disentangle the responsibilities and simplify the implementation. What final structure we should we aim for?

One clue is in the name of the CostCurrencyCalculator class. In linguistic jargon, the CostCurrencyCalculator is an agent noun: a noun derived from a verb that means no more than a thing that performs the action identified by the verb, like driver or baker or calculator. CostCurrencyCalculator is a so-called “doer class.”

Another clue is in the data that the class holds. The traveler’s preferred currency and source of exchange rates are the context for the calculation. They are managed elsewhere in the application and held by CostCurrencyCalculator so that they are close at hand for its calculations. The map of totals by currency (currencyTotals) contains transient, intermediate results of the calculation that are irrelevant after the calculation is complete and, in fact, should be discarded to avoid aliasing errors. The class doesn’t own any data, only holds it temporarily for operational reasons.

The CostCurrencyCalculator class doesn’t represent a concept in our application domain model, but a function that we perform upon elements of that domain model. In Kotlin, we usually implement functions not with objects but with, well, functions.

Let’s refactor the calculation from mutable classes to functions that work with immutable data.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.