Every software engineer needs some basic rules in their head to ensure that the code will be written in time and the best way possible. A money-related code is no different. That is why I have put top-8 tricks on working with money-related code in one place. Enjoy.
- First of all: never use floating-point arithmetic for money calculations. You HAVE TO use BigDecimal instead. Why? Floating-point arithmetic usage leads to loss of precision.
2. Ensure that divider is a non-integer value. In Ruby, dividing integer value by integer value returns an integer result. One way to be confident in a result each time is to use to_d on a divider EVERY TIME.
3. Ensure that result value is non-negative (positive or zero) when you subtract one money value from another one. If application logic doesn’t allow such value, then it’s time to raise an exception. Otherwise, it’s possible to crop result value with .max.
4. Money-related code HAS TO be covered with 100% coverage, mutant-testing is preferable.
5. Money-related code HAS TO be isolated from any other services.
6. Money-related code on frontend HAS TO be moved out of any components to a separate service with only money-related logic. Additionally it MUST be duplicated on backend to ensure that values from frontend are correct and match up.
7. It’s possible to delegate money-related code to backed and call it via AJAX, but it’s still important to ensure received values correctness.
8. Protect code from exceptional cases with exceptions
So here you are, the basic rules on working with money-related code. Have any ideas on which rules to add to this list? Be sure to share them in the comments section.