1 package org.apidesign.apifest08.currency;
4 * ConvetorImpl it the basic implementaion of Convertor interface.
5 * @see Convertor Convertor for more details.
6 * The 100 pences makes 1 amount of the currency.
10 final class ConvertorImpl implements Convertor {
12 private static final double P_TO_AM = 100;
13 private double exchangeRate;
15 ConvertorImpl(double exchangeRate) {
16 this.exchangeRate = exchangeRate;
19 public Amount convert(Amount amount) {
21 double result = convertToDouble(amount) * exchangeRate;
22 return convertToAmount(result);
25 public Amount convertBack(Amount amount) {
27 throw new IllegalArgumentException("Amount must be not null");
29 double result = convertToDouble(amount) / exchangeRate;
30 return convertToAmount(result);
33 private double convertToDouble(Amount amount) {
34 double am = amount.getAmount();
35 double pc = amount.getPence();
36 return am + (pc / P_TO_AM);
39 private Amount convertToAmount(double result) {
40 long resultAm = Math.round(Math.floor(result));
41 long resultPc = Math.round(Math.floor((result * P_TO_AM - resultAm * P_TO_AM)));
42 return new Amount(resultAm, resultPc);
45 private void verifyInput(Amount amount) {
47 throw new IllegalArgumentException("Amount must be not null");
49 if (amount.getPence() < 0) {
50 throw new IllegalArgumentException("Pences must not be negative");
52 if (amount.getPence() > P_TO_AM) {
53 throw new IllegalArgumentException("Pences must not be over P_TO_AM");