Last active
April 17, 2018 18:06
-
-
Save matthiasnoback/272be7f8c34b2a84a8393cf3a363ae14 to your computer and use it in GitHub Desktop.
Modeling exercise: currency conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also: https://github.com/matthiasnoback/modeling-exercises