1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/task2/solution05/src/org/apidesign/apifest08/currency/ConvertorImpl.java Wed Oct 01 10:43:05 2008 +0200
1.3 @@ -0,0 +1,56 @@
1.4 +package org.apidesign.apifest08.currency;
1.5 +
1.6 +/**
1.7 + * ConvetorImpl it the basic implementaion of Convertor interface.
1.8 + * @see Convertor Convertor for more details.
1.9 + * The 100 pences makes 1 amount of the currency.
1.10 + *
1.11 + * @author jindra
1.12 + */
1.13 +final class ConvertorImpl implements Convertor {
1.14 +
1.15 + private static final double P_TO_AM = 100;
1.16 + private double exchangeRate;
1.17 +
1.18 + ConvertorImpl(double exchangeRate) {
1.19 + this.exchangeRate = exchangeRate;
1.20 + }
1.21 +
1.22 + public Amount convert(Amount amount) {
1.23 + verifyInput(amount);
1.24 + double result = convertToDouble(amount) * exchangeRate;
1.25 + return convertToAmount(result);
1.26 + }
1.27 +
1.28 + public Amount convertBack(Amount amount) {
1.29 + if (amount == null) {
1.30 + throw new IllegalArgumentException("Amount must be not null");
1.31 + }
1.32 + double result = convertToDouble(amount) / exchangeRate;
1.33 + return convertToAmount(result);
1.34 + }
1.35 +
1.36 + private double convertToDouble(Amount amount) {
1.37 + double am = amount.getAmount();
1.38 + double pc = amount.getPence();
1.39 + return am + (pc / P_TO_AM);
1.40 + }
1.41 +
1.42 + private Amount convertToAmount(double result) {
1.43 + long resultAm = Math.round(Math.floor(result));
1.44 + long resultPc = Math.round(Math.floor((result * P_TO_AM - resultAm * P_TO_AM)));
1.45 + return new Amount(resultAm, resultPc);
1.46 + }
1.47 +
1.48 + private void verifyInput(Amount amount) {
1.49 + if (amount == null) {
1.50 + throw new IllegalArgumentException("Amount must be not null");
1.51 + }
1.52 + if (amount.getPence() < 0) {
1.53 + throw new IllegalArgumentException("Pences must not be negative");
1.54 + }
1.55 + if (amount.getPence() > P_TO_AM) {
1.56 + throw new IllegalArgumentException("Pences must not be over P_TO_AM");
1.57 + }
1.58 + }
1.59 +}