task2/solution10/src/org/apidesign/apifest08/currency/ConstantRateConverter.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 01 Oct 2008 10:43:05 +0200
changeset 29 f6073056b9fe
parent 6 task1/solution10/src/org/apidesign/apifest08/currency/ConstantRateConverter.java@97662396c0fd
permissions -rw-r--r--
Getting ready for task2: copying all solutions to new locations
     1 package org.apidesign.apifest08.currency;
     2 
     3 import java.util.*;
     4 
     5 final class ConstantRateConverter implements CurrencyConverter {
     6 
     7 	private final Currency from;
     8 	private final Currency to;
     9 
    10 	private final double rate;
    11 
    12 	public ConstantRateConverter(Currency from, Currency to, double rate) throws IllegalArgumentException {
    13 		if (from == null || to == null)
    14 			throw new NullPointerException("None of the currencies can be null");
    15 		if (from.equals(to))
    16 			throw new IllegalArgumentException("Cannot create converter with two equal currencies");
    17 		this.from = from;
    18 		this.to = to;
    19 		this.rate = rate;
    20 	}
    21 
    22 	@Override
    23 	public double convert(double value, String from, String to)
    24 			throws CurrencyConversionException, NullPointerException {
    25 		return convert(value, Currency.getInstance(from), Currency.getInstance(to));
    26 	}
    27 
    28 	@Override
    29 	public double convert(double value, Currency from, Currency to)
    30 			throws NullPointerException, CurrencyConversionException {
    31 
    32 		if (this.from.equals(from)) {
    33 			if (!this.to.equals(to))
    34 				throw new CurrencyConversionException(from, to, "Unsupported currency");
    35 			return value * rate;
    36 		}
    37 		if (this.from.equals(to)) {
    38 			if (!this.to.equals(from))
    39 				throw new CurrencyConversionException(from, to, "Unsupported currency");
    40 			return value / rate;
    41 		}
    42 		throw new CurrencyConversionException(from, to, "Unsupported currency"); 
    43 	}
    44 }