-
Notifications
You must be signed in to change notification settings - Fork 447
Description
I'm hoping the decision to enforce strict currency comparison when the amount is zero can be reconsidered. Currently, the library requires both operands to have the same currency for arithmetic operations, even when one of them is 0. This makes it unnecessarily tedious to perform calculations when a value might be null.
For example, given two Money instances, $first and $second, we can simply write:
$total = $first->add($second);However, if either $first or $second could be null, we must provide a default Money instance.
$total = ($first ?? Money::USD(0))->add($second ?? Money::USD(0));This introduces a significant issue:
- We must assume a currency (e.g., USD in the example above).
- If $second is in a different currency (e.g., EUR), the operation will fail, even though adding zero should logically not affect the total.
- This results in additional conditional logic to ensure that a default Money instance has the correct currency, which increases complexity and verbosity:
if ($first !== null) {
$currency = $first->getCurrency();
} elseif ($second !== null) {
$currency = $second->getCurrency();
} else {
$currency = new Currency('USD'); // Arbitrary default, which may be incorrect
}
$total = ($first ?? new Money(0, $currency))->add($second ?? new Money(0, $currency));This complexity arises only because the library enforces currency comparison for zero values. In reality, adding zero does not affect the sum, making this restriction unnecessary. Consider this: If you have 5 M&Ms and you add 0 Skittles, you still have 5 M&Ms, right? The fact that Skittles are a different type of candy doesn’t matter because you’re adding zero of them. The same logic should apply to money—if you add zero of a different currency, the total should remain unchanged, and strict currency enforcement shouldn’t apply in this case.
I understand the importance of strict currency enforcement in general, but relaxing this rule for zero would improve usability without introducing ambiguity. If there is interest from the maintainers, I would be happy to work on a PR.
Side note: It has occurred to me that we could extend the Money class and override the methods we want to, but even this is not a possibility, as Money is a final class.