I'm writing a PHP application that deals with monetary values. For this purpose, I use the BigDecimal
object from the Brick\Math library. This object allows for precise representations of monetary values and precise operations on them. To create a BigDecimal
object out of a string
, an int
or a float
, I have to call the BigDecimal::of
method, like so:
BigDecimal::of('1.25');
Now, say that I have the following method:
function withdraw_currency(string $currency, BigDecimal $amount);
If I want to call it, I will often have to create a BigDecimal
object, like so:
withdraw_currency('USD', BigDecimal::of('1.25'));
I find this horrendous to read. It does not seem clean at all. It gets worse if the method requires more than one BigDecimal
parameter of I'm invoking this method multiple times with, each time, a new BigDecimal
object.
I had thought of doing this:
$amount = BigDecimal::of('1.25');
withdraw_currency('USD', $amount);
This is surely more readable, but it feels like the method should be called in one line.
I also thought of changing the withdraw_currency
method so that the $amount
parameter is a string
instead of BigDecimal
. $amount
would then be converted into a BigDecimal
object inside the method; or in other words, it would "hide" the ugliness from the programmer.
Then, the method could be called like so:
withdraw_currency('USD', '1.25');
This looks clean, but it feels wrong as it misleads the programmer into thinking that the method deals with a string, when, in reality, it deals with a BigDecimal
object.
It seems like there is no perfect answer, but I wanted the input of other programmers. What would be the "cleanest" way of dealing with the BigDecimal
object in that situation?