Skip to content

Instantly share code, notes, and snippets.

@matthiasnoback
Last active April 17, 2018 18:06
Show Gist options
  • Save matthiasnoback/272be7f8c34b2a84a8393cf3a363ae14 to your computer and use it in GitHub Desktop.
Save matthiasnoback/272be7f8c34b2a84a8393cf3a363ae14 to your computer and use it in GitHub Desktop.
Modeling exercise: currency conversion
<?php
declare(strict_types=1);
function convert(string $from, string $to, float $amount)
{
$exchangeRates = [
'USD,EUR' => 1.240055,
// ...
];
$key = $from . ',' . $to;
if (isset($exchangeRates[$key])) {
$exchangeRate = $exchangeRates[$key];
}
else {
$alternativeKey = $to . ',' . $from;
if (isset($exchangeRates[$alternativeKey])) {
$exchangeRate = 1/$exchangeRates[$alternativeKey];
} else {
throw new \RuntimeException('Cannot determine an exchange rate.');
}
}
return $amount * 1/$exchangeRate;
}
// Convert to EUR
var_dump(convert('USD', 'EUR', 10.0));
// Convert back to USD
var_dump(convert('EUR', 'USD', 8.0641584445851));
/*
* Design issues:
*
* - What's the currency of the $amount parameter? What should it be?
* - What's the currency of the return value? What should it be?
* - What's the precision of the returned amount? What should it be?
* - There's way too many levels of indentation. How to fix this?
* - `1/$exchangeRate` is repeated knowledge about "inverting" an exchange rate. How to solve it?
*
* By means of introducing proper (value) objects, all of these issues will disappear.
*/
@matthiasnoback
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment