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
japod@6
     1
package org.apidesign.apifest08.currency;
japod@6
     2
japod@6
     3
/**
japod@6
     4
 * ConvetorImpl it the basic implementaion of Convertor interface.
japod@6
     5
 * @see Convertor Convertor for more details.
japod@6
     6
 * The 100 pences makes 1 amount of the currency.
japod@6
     7
 *
japod@6
     8
 * @author jindra
japod@6
     9
 */
japod@6
    10
final class ConvertorImpl implements Convertor {
japod@6
    11
japod@6
    12
    private static final double P_TO_AM = 100;
japod@6
    13
    private double exchangeRate;
japod@6
    14
japod@6
    15
    ConvertorImpl(double exchangeRate) {
japod@6
    16
        this.exchangeRate = exchangeRate;
japod@6
    17
    }
japod@6
    18
japod@6
    19
    public Amount convert(Amount amount) {
japod@6
    20
        verifyInput(amount);
japod@6
    21
        double result = convertToDouble(amount) * exchangeRate;
japod@6
    22
        return convertToAmount(result);
japod@6
    23
    }
japod@6
    24
japod@6
    25
    public Amount convertBack(Amount amount) {
japod@6
    26
        if (amount == null) {
japod@6
    27
            throw new IllegalArgumentException("Amount must be not null");
japod@6
    28
        }
japod@6
    29
        double result = convertToDouble(amount) / exchangeRate;
japod@6
    30
        return convertToAmount(result);
japod@6
    31
    }
japod@6
    32
japod@6
    33
    private double convertToDouble(Amount amount) {
japod@6
    34
        double am = amount.getAmount();
japod@6
    35
        double pc = amount.getPence();
japod@6
    36
        return am + (pc / P_TO_AM);
japod@6
    37
    }
japod@6
    38
japod@6
    39
    private Amount convertToAmount(double result) {
japod@6
    40
        long resultAm = Math.round(Math.floor(result));
japod@6
    41
        long resultPc = Math.round(Math.floor((result * P_TO_AM - resultAm * P_TO_AM)));
japod@6
    42
        return new Amount(resultAm, resultPc);
japod@6
    43
    }
japod@6
    44
japod@6
    45
    private void verifyInput(Amount amount) {
japod@6
    46
        if (amount == null) {
japod@6
    47
            throw new IllegalArgumentException("Amount must be not null");
japod@6
    48
        }
japod@6
    49
        if (amount.getPence() < 0) {
japod@6
    50
            throw new IllegalArgumentException("Pences must not be negative");
japod@6
    51
        }
japod@6
    52
        if (amount.getPence() > P_TO_AM) {
japod@6
    53
            throw new IllegalArgumentException("Pences must not be over P_TO_AM");
japod@6
    54
        }
japod@6
    55
    }
japod@6
    56
}