<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leon Klinke on Medium]]></title>
        <description><![CDATA[Stories by Leon Klinke on Medium]]></description>
        <link>https://medium.com/@leon.klinkea?source=rss-86bdf576559e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A5OXjAQvR6Oi3D5B_Napuw.png</url>
            <title>Stories by Leon Klinke on Medium</title>
            <link>https://medium.com/@leon.klinkea?source=rss-86bdf576559e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:30:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leon.klinkea/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handling Monetary Amounts]]></title>
            <link>https://medium.com/@leon.klinkea/handling-monetary-amounts-7393e0d77ac7?source=rss-86bdf576559e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7393e0d77ac7</guid>
            <category><![CDATA[monetary-system]]></category>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[floating-points]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Leon Klinke]]></dc:creator>
            <pubDate>Thu, 08 May 2025 23:23:30 GMT</pubDate>
            <atom:updated>2025-05-08T23:23:30.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oenSKfCMkKuHVQQgKLU9Qw.jpeg" /></figure><p>When dealing with financial applications, the way we store and handle monetary values is crucial. Many developers decide using floating-point numbers (float or double) to represent money, which can lead to significant precision errors and financial discrepancies. This article explores some common market approaches.</p><h3><strong>Floating-Point Numbers Problem</strong></h3><p>Floating-point numbers are designed for scientific calculations where absolute precision isn’t critical. However, when dealing with money, even the smallest rounding error can lead to significant problems. Let’s look at some examples:</p><pre>func main() {<br>  // Example 1: Simple addition<br>  price1 := 0.1<br>  price2 := 0.2<br>  total := price1 + price2<br>  fmt.Printf(&quot;0.1 + 0.2 = %.20f\n&quot;, total) <br>  // Output: 0.1 + 0.2 = 0.30000000000000004441<br><br>  // Example 2: Accumulating errors<br>  var sum float64<br>  for i := 0; i &lt; 10; i++ {<br>    sum += 0.1<br>  }<br>  fmt.Printf(&quot;0.1 added 10 times = %.20f\n&quot;, sum) <br>  // Output: 0.1 added 10 times = 0.99999999999999988898<br>}</pre><p><strong>Why that happens?<br></strong>Floating numbers are represented in binary format. This system has three main components (ex of a 32-bit float):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*ZAPFhlR2XU4HJE3IsqkNAw.png" /><figcaption>image from: <a href="https://numeral-systems.com/ieee-754-add/">https://numeral-systems.com/ieee-754-add/</a></figcaption></figure><p>The imprecision occurs because many decimal numbers cannot be represented exactly in binary. For example, the decimal number <strong>0.1</strong> in binary is an infinite repeating fraction:</p><pre>0.1 (decimal) = 0.0001100110011... (binary)</pre><p>These small errors might seem insignificant (c’mon is just a .20f), but in financial calculations, they can accumulate and lead to significant discrepancies over time, especially when dealing with large numbers of transactions or complex calculations.</p><h3><strong>Solution 1 : Using Cents</strong></h3><p>A better approach is to store monetary values as integers representing the smallest currency unit (cents in USD, for example). This eliminates floating-point precision issues and makes calculations more reliable.</p><pre>type Currency string<br><br>const ( <br>  USD Currency = &quot;USD&quot;<br>  //other currencies...<br>)<br><br>type Money struct {<br>  Amount      int64<br>  Currency    string<br>  Precision   int<br>}<br><br>func NewMoney(currency Currency, amount uint64) Money {<br>  return Money{<br>    Amount:     amount,<br>    Currency:   currency,<br>    Symbol:     getCurrencySymbol(currency),<br>    Precision:  getCurrencyPrecision(currency),<br>  }<br>}<br><br>func (m Money) Print() string {<br>  decimalValue := float64(m.Amount) / float64(math.Pow(10, m.Precision))<br>  return fmt.Sprintf(&quot;%s %.2f&quot;, m.Symbol, decimalValue)<br>}<br><br>func (m Money) Add(other Money) Money {<br>  return Money{<br>    Cents: m.Amount + other.Amount,<br>  }<br>}<br><br>func main() {<br>  // Example of using cents<br>  price1 := NewMoney(USD, 1099)<br>  price2 := NewMoney(USD, 2050)<br>  total := price1.Add(price2)<br>  <br>  fmt.Printf(&quot;%s + %s = %s\n&quot;, <br>    price1.Print(),<br>    price2.Print(),<br>    total.Print(),<br>  )<br>  // $10,99 + $20,50 = $31,49<br>}</pre><p>Using cents like this can look weird for those that are not familiar with it, but this approach brings some important benefits like:</p><ol><li><strong>Performance</strong><em>:</em> It&#39;s considerably faster to perform operations (add, multiply…) in two ints rather than with floats or even special decimal types.</li><li><strong>Precision &amp; consistency</strong>: All operations are exact, no rounding errors, values are consistent all over the place and no type issues.</li><li><strong>Storage</strong>: using ints not just saves memory space while dealing with the values in code execution, but also saves space in the database and provides better indexing performance.</li></ol><p>But like everything else, it also brings some disadvantages, like requiring an extra step when showing the data (also in the database, the value wouldn&#39;t be clear as a ready float)</p><h3>Solution 2: using external packages</h3><p>While the cents approach is often used, decimal libraries like <a href="https://pkg.go.dev/github.com/shopspring/decimal">shopspring/decimal</a> provide powerful features for handling complex financial calculations. Let’s explore when and why you might choose to use a decimal library:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;github.com/shopspring/decimal&quot;<br>)<br><br>func main() {<br>    // Create precise decimal values<br>    price := decimal.NewFromFloat(19.99)<br>    quantity := decimal.NewFromInt(3)<br>    <br>    // Calculate total with precise multiplication<br>    total := price.Mul(quantity)<br>    <br>    // Apply tax rate with precise division<br>    taxRate := decimal.NewFromFloat(0.0825) // 8.25%<br>    tax := total.Mul(taxRate)<br>    <br>    fmt.Printf(&quot;Price: $%s\n&quot;, price.String())<br>    fmt.Printf(&quot;Quantity: %s\n&quot;, quantity.String())<br>    fmt.Printf(&quot;Total: $%s\n&quot;, total.String())<br>    fmt.Printf(&quot;Tax: $%s\n&quot;, tax.String())<br>}</pre><p>Such packages help us work with decimal values in code execution, and modern databases provide decimal types to store such values, making the data presentation cleaner than using cents.</p><h3><strong>Benchmarking</strong></h3><p>Let’s compare the performance of different approaches to handling monetary values:</p><pre>package main<br>import (<br>  &quot;testing&quot;<br>  &quot;github.com/shopspring/decimal&quot;<br>)<br><br>// Using cents<br>type MoneyCents struct {<br>  Cents int64<br>}<br>// Using decimal package<br>type MoneyDecimal struct {<br>  Value decimal.Decimal<br>}<br><br>func BenchmarkCents(b *testing.B) {<br>  for i := 0; i &lt; b.N; i++ {<br>    m1 := MoneyCents{Cents: 1000}<br>    m2 := MoneyCents{Cents: 2000}<br>    _ = m1.Cents + m2.Cents<br>  }<br>}<br><br>func BenchmarkDecimal(b *testing.B) {<br>  for i := 0; i &lt; b.N; i++ {<br>    m1 := MoneyDecimal{Value: decimal.NewFromFloat(10.00)}<br>    m2 := MoneyDecimal{Value: decimal.NewFromFloat(20.00)}<br>    _ = m1.Value.Add(m2.Value)<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXAYejE5hkS8SEamkdqv8A.png" /></figure><p>Results typically show that using cents is significantly faster than using the decimal package, as it involves simple integer arithmetic rather than more complex decimal calculations.</p><h3><strong>Comparing</strong></h3><p><strong>Cents</strong></p><p><em>Pros</em>:</p><ul><li>Simple integer arithmetic</li><li>No floating-point precision issues</li><li>Better performance</li><li>Easy to understand and implement</li><li>No external dependencies</li></ul><p><em>Cons</em>:</p><ul><li>Need to handle currency conversion manually</li><li>May need to handle different currency decimal places</li><li>Requires careful handling of division operations</li></ul><p><strong>Decimal Libs</strong></p><p><em>Pros</em>:</p><ul><li>Built-in support for different currencies</li><li>Handles complex financial calculations</li><li>Better for international applications</li><li>Built-in rounding rules</li></ul><p><em>Cons</em>:</p><ul><li>Slower performance</li><li>External dependency</li><li>More complex API</li><li>Higher memory usage</li></ul><h3><strong>Conclusion</strong></h3><p>The only certain conclusion we can draw is to avoid <strong>floats</strong> when dealing with financial calculations and storage. But when considering <strong>cents</strong> or a <strong>decimal</strong> library, you must consider some important points:</p><ul><li>Is your system dealing with a gigantic throughput? If so consider the performant choice (cents)</li><li>Are you dealing with several currencies and lots of operations? Decimal can make your life easier.</li><li>Do you have a microservice architecture? Independently of the choice, try to use the same approach for all of them.</li></ul><p>The key is to understand your application’s requirements and choose the approach that best fits your needs. For most applications, the simplicity and reliability of using cents make it the preferred choice, in my last years working at Fintechs, that was the most common approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7393e0d77ac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code]]></title>
            <link>https://medium.com/@leon.klinkea/clean-code-960744644ce6?source=rss-86bdf576559e------2</link>
            <guid isPermaLink="false">https://medium.com/p/960744644ce6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[uncle-bob]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Leon Klinke]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 13:26:03 GMT</pubDate>
            <atom:updated>2021-09-01T13:26:03.194Z</atom:updated>
            <content:encoded><![CDATA[<p>This can be an overpast concept for a lot of programmers, but the reason for writing this article is that I thought I was in this group.</p><p>In fact, a lot of people write clean enough codes, but recap the concepts of clean code is a great practice for all programmers, experienced or not. This requires continuous practice.</p><p>Of course, I will use Robert C. Martin (Uncle Bob) “Clean code” as a reference for this article. If you never heard about it, I think you should read this book, it is really great.</p><p>In the book’s chapter 17º we can see some kind of summary of concerns and rules to write a clean code. I will not go over every single one of them, but those I believe we need to pay close attention to.</p><p>As the purpose of the concept doesn’t relate to the language itself, I will cover the examples using my favorite one, Golang. If you are more familiar with Java, please take a look at the book’s examples.</p><p>I may separate this article into some parts because it is an extensive subject. so you can index in your best interest.</p><p>In this part I will talk about: Commentaries, Names, and Functions.</p><p>Ready? Let‘s go!</p><h3>// Commentaries</h3><p>I think we all have some phases dealing with commentaries. When we are learning how to program, we almost never use commentaries. But when we start to learn about documentation and work with linters, we develop codes with a lot of commentaries.</p><p>A rule we can use is: <strong>A comment only needs to exist if it will really help.</strong></p><p>That’s why we need to be careful writing out commentaries, because of the following:</p><p><strong>Useless commentaries:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*jgR1oqlOZ8YC6YbPAiTc6g.png" /></figure><p>Who has never seen a comment like this? Apparently, it is a harmless comment, but it’s clear out of context. Information of authors, creation, and update dates, should be handled by the version control system, not the code itself. This provides a lot of useless lines of code, and will certainly cause the next problem.</p><p><strong>Outdated comments:</strong></p><p>We have few certainties in life, one is death, other is that your commentary will become outdated sometimes.</p><p>Not just header comments like the above example, but things like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ne8WU2gxNlWUV3ar0-kEDg.png" /></figure><p>As we can see, at the time we created the comment, the function only received an Id, name, and phone, but now the function expects an address as well. This is a clear case of comments that don’t help you at all, and worst, generate more work and confusion for the future.</p><p><strong>A well-written code doesn’t need this kind of comment, it describes itself.</strong></p><p><strong>Bad written and redundant commentaries:</strong></p><p>This problem is auto-describing. When we write redundant comments, we are just adding more and more useless lines of code, and forcing developers to read what they don’t need to, like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*e2XCtePIbVqfgBDwc6MXzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*URl5abr8qjQImzsSdP7z8A.png" /></figure><p>When you are creating commentaries, <strong>be calm, think if it is really necessary</strong>. If it is, write it as well as possible. Remember, the comment needs to help you, not cause trouble.</p><p><strong>Commented Code:</strong></p><p>Everyone did (or do) this. Sometimes we think “I may use this in the future”, and leave a whole block of code commented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*020oqbYz2T1lsFTBP8wqlA.png" /></figure><p>Ok, this is normal, but one thing we have to put in mind is that most of these codes will never be used, or will be, but in a different form.</p><p>The problem with this kind of comment is: If I didn’t write this comment, I will not erase that, because someone may have a good reason to leave that there.</p><p>And guess what, this someone will never appear, the needer uses the code. So probably this commented code will lie there forever.</p><p>Avoid this, <strong>if that piece of code is so important, it shouldn’t be a comment</strong>, agree?</p><h3>Names</h3><p>Maybe this is the most significant part when we are talking about clean code. Setting good names for everything, variables, functions, classes, interfaces, etc.</p><p>Spending some time picking good names can look like a waste of time, but it is an investment in code quality. <strong>Do not rush what makes your code readable.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*S5lmBWcM5wSZlYoQOen8tg.png" /></figure><p><strong>Meaning Names</strong></p><p>Take a look at this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*CeYAwC4fA9vv__-BeqMhZw.png" /></figure><p>Just taking a quick look, it is obvious that this is a median function right? Of course not.</p><p>The function and variable names are short but meaningless. Take a look at the same example with well-picked names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*OkzUc5bRlncMZYIaJqCDDQ.png" /></figure><p>See the difference with those carefully chosen names, just looking into the function’s name, I already know what it is about and what it does, without needing to read all the function’s body, everything is crystal clear.</p><p><strong>Project Patterns</strong></p><p>One good practice choosing names is following a project convention. For example, if you have a function dealing with a User object, don’t create function names like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*fVFg3ZNJxSuO5Mz5GICqbw.png" /></figure><p>Member? Wasn’t that about Users?</p><p>Understand how confusing this kind of name pick is?</p><p><strong>Ambiguous names</strong></p><p>As we saw before, names have to help us describe what a variable is, or what this function does. That is why we need to be careful not to use ambiguous names, like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*WgMTrwFCKHFJsSbhYdtw8g.png" /></figure><p>Ok, but renaming what? It’s better to create big names instead of short ones, but ambiguous. So it would be better to create something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*-Fki636tu9taFOR8_nhXBQ.png" /></figure><p><strong>Effect Names</strong></p><p>Don’t hide effects from the name, let’s see this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*nEYvr5ar-PAx-prPHkYqDQ.png" /></figure><p>As you can see, this function is not just detaching a User from an Account, it is deleting the User as well, a better name for this is <em>DetachUserAndRemove()</em></p><h3>Functions</h3><p>These old friends have become more important recently with the growth of functional languages such as Elixir, Scala, Kotlin, Swift, Haskell, and of course our example language Golang.</p><p>Almost every programmer knows how to write and use functions, but are we doing it in a clean way?</p><p><strong>Short</strong></p><p>Have you ever seen a function with hundreds, or thousands of lines right? Maybe you were the author of one of those…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*jCG8ysMF6oPoA1bimnP5Zw.png" /></figure><p>Functions need to be easy to read and understand. You are able to understand what a function does in a few seconds if it is well written, and of course, short.</p><p>Ok, but how short they may be? I don’t like to impose some magic number of lines, but if your function passes 20 lines, it can be refactored into a smaller one.</p><p>One practical way to shrink your functions is to avoid adding logic into if, else, while… indentations, see this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*yR07yo1bzZPi99eS2oqvEQ.png" /></figure><p>Ok, by the name it is easy to know that this function prints prime numbers, between 2 arbitrary numbers. But there are more simple ways to read and understand faster what is going on inside the function as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*kAVEnMtRb_Y8OkXCqAuEOQ.png" /></figure><p>Much faster to understand what is going on, right? Basically, we remove the logic inside if and for other functions, so we can describe what we want to do by the names of the new functions, see the full the other two functions now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*j-6Hu-O9AbhT4i10sq0jVA.png" /></figure><p>See how it is easier to understand each one of them separately, each function doing only what it is supposed to.</p><p>Note: Take a look at the order of the functions. When you are decomposing the function responsibility, the reader of <strong>your code must read it as easily as a journal</strong>, a story. Try to keep the order of your functions, so we can read it top-down.</p><p><strong>Single responsibility</strong></p><p>One important concept of functions is the single responsibility principle (the first one in <a href="https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">SOLID</a>). <strong>Your function has to do one thing, one thing only, and well done</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*1aPDq84WztpFWPLGNA3Kyw.png" /></figure><p>Is not difficult to see that this function has much more than 1 responsibility, right? When we create a function name, we define what it will do. If you are creating multiple functionalities to one single function, then um should refactor it.</p><p><strong>Parameters</strong></p><p>Is easy to see why a function with a lot of parameters is difficult to understand, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*3ANIR9rZH43k2AWw2sRtSw.png" /></figure><p>It does not just increase the time we need to read all the functions, as it becomes ugly, and in some cases out of control. Imagine this same function with 10 different filters…</p><p>We have to prevent this kind of trouble, not just to keep the code beautiful, but cleaner and easy to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*d3A5_DBq8Vkb-zBc_i-xmA.png" /></figure><p>See how we can keep things cleaner and easy to add or remove some arguments and show clearly what this function expects.</p><p>Note: The same idea to deal with return arguments</p><p>All these concepts are just a few approaches that you will find in the Clean Code book, you can see all of those much more accurately there.</p><p>This is already too big, so I will write more about the book in future articles.</p><p>Thank you for reading.</p><p><strong><em>Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=960744644ce6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>