CleverLabs
Apr 16 · 2 min read

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.

  1. 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.

CleverLabs

CleverLabs is a software engineering and IT consulting company. It focuses on developing web applications for businesses. The company provides custom applications development in a variety of fields: HRM, EDI, eCommerce, healthcare, blockchain storages, smart contracts and others.

CleverLabs

Written by

CleverLabs

CleverLabs is a software engineering and IT consulting company. It focuses on developing web applications for businesses. The company provides custom applications development in a variety of fields: HRM, EDI, eCommerce, healthcare, blockchain storages, smart contracts and others.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade