task2/solution05/src/org/apidesign/apifest08/currency/ConvertorImpl.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 01 Oct 2008 10:43:05 +0200
changeset 29 f6073056b9fe
parent 6 task1/solution05/src/org/apidesign/apifest08/currency/ConvertorImpl.java@97662396c0fd
permissions -rw-r--r--
Getting ready for task2: copying all solutions to new locations
     1 package org.apidesign.apifest08.currency;
     2 
     3 /**
     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.
     7  *
     8  * @author jindra
     9  */
    10 final class ConvertorImpl implements Convertor {
    11 
    12     private static final double P_TO_AM = 100;
    13     private double exchangeRate;
    14 
    15     ConvertorImpl(double exchangeRate) {
    16         this.exchangeRate = exchangeRate;
    17     }
    18 
    19     public Amount convert(Amount amount) {
    20         verifyInput(amount);
    21         double result = convertToDouble(amount) * exchangeRate;
    22         return convertToAmount(result);
    23     }
    24 
    25     public Amount convertBack(Amount amount) {
    26         if (amount == null) {
    27             throw new IllegalArgumentException("Amount must be not null");
    28         }
    29         double result = convertToDouble(amount) / exchangeRate;
    30         return convertToAmount(result);
    31     }
    32 
    33     private double convertToDouble(Amount amount) {
    34         double am = amount.getAmount();
    35         double pc = amount.getPence();
    36         return am + (pc / P_TO_AM);
    37     }
    38 
    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);
    43     }
    44 
    45     private void verifyInput(Amount amount) {
    46         if (amount == null) {
    47             throw new IllegalArgumentException("Amount must be not null");
    48         }
    49         if (amount.getPence() < 0) {
    50             throw new IllegalArgumentException("Pences must not be negative");
    51         }
    52         if (amount.getPence() > P_TO_AM) {
    53             throw new IllegalArgumentException("Pences must not be over P_TO_AM");
    54         }
    55     }
    56 }