<?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 George Papadopoulos on Medium]]></title>
        <description><![CDATA[Stories by George Papadopoulos on Medium]]></description>
        <link>https://medium.com/@george.719pap?source=rss-a8addc4b58c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sJ1VWB-wjfSuyMTveB3GLg.jpeg</url>
            <title>Stories by George Papadopoulos on Medium</title>
            <link>https://medium.com/@george.719pap?source=rss-a8addc4b58c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@george.719pap/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[Notes on Immutability]]></title>
            <link>https://medium.com/@george.719pap/notes-on-immutability-91ae70aedb10?source=rss-a8addc4b58c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ae70aedb10</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[code-readability]]></category>
            <category><![CDATA[mutation]]></category>
            <dc:creator><![CDATA[George Papadopoulos]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 16:44:18 GMT</pubDate>
            <atom:updated>2024-11-30T10:53:03.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AuhEjitugPCjMmzb" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=medium&amp;utm_medium=referral">Etienne Girardet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>tl;dr </strong>Writing code with Immutability in mind makes the code:</p><ul><li>easier to reason</li><li>easier to understand</li><li>less error-prone</li><li>thread-safe by default</li></ul><p>Immutability is increasingly becoming the standard practice in code development. In this article, I will share my notes on using immutable versus mutable code. All the examples are in Kotlin, but the same principles can be applied to all OOP languages.</p><h4>Immutable vs Mutable</h4><p>Let’s take a look at the first example which uses mutability to do its operations.</p><p><strong>Example 1</strong></p><pre>fun decodeToMutablePerson(json: String, city: String, postalCode: String): MutablePerson {<br>    val person = MutablePerson()<br>    person.city = city<br>    person.postalCode = postalCode<br>    decode(json, person)<br>    validatePerson(person)<br>    return person<br>}<br><br>fun decode(json: String, person: MutablePerson) {<br>    // Pretend we decode.<br>    person.name = &quot;name&quot;<br>    person.age = 100<br>}<br><br>fun validatePerson(person: MutablePerson) {<br>    require(!person.name.isNullOrBlank())<br>    requireNotNull(person.age)<br>    require(!person.city.isNullOrBlank())<br>    require(!person.postalCode.isNullOrBlank())<br>}<br><br>class MutablePerson {<br>    var name: String? = null<br>    var age: Int? = null<br>    var city: String? = null<br>    var postalCode: String? = null<br>}</pre><p>Notice the decodeToMutablePerson function. We initialize a MutablePerson and assign to it only some fields, and after this we pass it into decode function. This code flow raises questions about whether the variables are mutated within the function. Are the remaining fields populated inside the function or are some left unset? We cannot know for sure without examining the function. The same reasoning can be applied for the validatePerson function, unless we look inside it, we cannot trust it that it does not mutate anything for whatever reason.</p><p>Additionally, we can notice that we return a MutablePerson , and this leads to another question, are we mutating it afterwards or not, if yes, why?</p><p>Let’s refactor it with <strong>immutability in mind.</strong></p><pre>fun decodeToPerson(json: String, city: String, postalCode: String): Person {<br>    val info = decode(json)<br>    val person = Person(info.name, info.age, city, postalCode)<br>    validatePerson(person)<br>    return person<br>}<br><br>fun decode(json: String): PersonInfo {<br>    // Pretend we decode.<br>    return PersonInfo(&quot;name&quot;, 100)<br>}<br><br>class PersonInfo(val name: String, val age: Int)<br><br>fun validatePerson(person: Person) {<br>    require(person.name.isNotBlank())<br>    require(person.city.isNotBlank())<br>    require(person.postalCode.isNotBlank())<br>}<br><br>class Person(val name: String, val age: Int, val city: String, val postalCode: String)</pre><p>Now let’s examine the decodeToPerson function. We notice that the Person class is immutable and we cannot change its contents after the initialization. This helps the code flow significantly. Now it’s clear what the final state is and how it is created. Also, we can safely trust the validatePerson function does not exceed its responsibility as it is enforced by the class’s nature.</p><p>Refactoring the code using the immutability principle makes the code easier to reason and easier to understand. While, mutability makes it harder to reason what your code is doing.</p><h4>Example 2</h4><p>Note: List interface in Kotlin is an immutable type, unlike Java’s List interface which is a mutable one.</p><p>Let’s take a look at our second example. Here we see a simple main function that calls some simple functions. Just by reading the code, can we predict what the code will print without examining inside the functions?</p><pre>fun main() {<br>    val numbers = arrayListOf(1, 2, 3, 4)<br>    val filtered = filter(numbers) { it % 2 == 0 }<br>    // What this prints:<br>    // 1) - 1, 2, 3, 4<br>    // 2) - 2, 4<br>    // 3) - something else?<br>    println(filtered)<br>    val mapped = map(numbers) { it + 10 }<br>    // What this prints:<br>    // 1) - 10, 20, 30, 40<br>    // 2) - 12, 14<br>    // 3) - something else?<br>    println(mapped)<br>}</pre><p>Keep the printed numbers, and let’s analyse the functions.</p><pre>fun &lt;T&gt; filter(input: MutableList&lt;T&gt;, predicate: (T) -&gt; Boolean): MutableList&lt;T&gt; {<br>    val iterator = input.listIterator()<br>    for (element in iterator) {<br>        if (!predicate(element)) iterator.remove()<br>    }<br>    return input<br>}</pre><p>As we can see, the function is <strong>not using the immutable code principle.</strong> This leads to 3 key problems with the filter function:</p><p>1) The function does its job by<strong> mutating the input directly.</strong> Now we know the println(mapped) function will not print what we expected. While it is easy to blame the author of filter function, the root problem lies elsewhere.</p><blockquote><a href="https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#risks_of_mutation">Passing mutable objects around is a latent bug. It’s just waiting for some programmer to inadvertently mutate that list, often with very good intentions like reuse or performance, but resulting in a bug that may be very hard to track down.</a></blockquote><p>This problem is also called <strong>aliases</strong>, where we have multiple references for the same mutable object.</p><p>2) The behavior of mutating the input directly, can take by surprise many readers. When reading main, is it visible to the reader that numbers list is mutated by the filter function? Therefore, the function is not <strong>easy to either reason or to understand.</strong></p><p>3) Another big problem in the implementation is that we are using an iterator on a <strong>mutable</strong> list. If we have multiple active iterators iterating and mutating the list at the same time from another thread, the resulting behavior is that at best we might get a ConcurrentModificationException while at worst the behavior is <strong>undefined</strong>.</p><p>From the Javadoc on the ArrayList :</p><blockquote>Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.</blockquote><p>This is because the ArrayList implementation is not synchronized (not thread-safe).</p><p>Now, let’s take a look at the map function.</p><pre>fun &lt;T, R&gt; map(input: List&lt;T&gt;, transform: (T) -&gt; R): List&lt;R&gt; {<br>    val result = mutableListOf&lt;R&gt;()<br>    for (element in input) {<br>        val r = transform(element)<br>        result.add(r)<br>    }<br>    return result<br>}</pre><p>This function is a good example of how we can implement such functionality using immutability.</p><p>At this point, it’s fair to ask why this function is following the immutability principle, since we create a mutable-list and mutate it in the function. Actually, <strong>using mutable objects locally within a function and with only one reference is completely fine</strong>.</p><p>See that the function accepts a List type. While there are many angles to cover on why we choose type of List , we will focus only on one, <strong>writing intentional code.</strong> Choosing List we signify to the reader that we are not mutating the input. However, this does not solve the iterator issue. List is an interface extended by the MutableList, and both are implemented by ArrayList. Meaning a mutable input could still be passed.</p><p>Remember a little earlier where we mentioned that we have an aliasing problem in main. Solving it will also solve our problem with the iterator.</p><pre>fun main() {<br>    val numbers = listOf(1, 2, 3, 4) // &lt;-- changed to immutable structure<br>    val filtered = filter(numbers) { it % 2 == 0 } // &lt;-- compiler error: Argument type mismatch<br>    // What this prints:<br>    // 1) - 1, 2, 3, 4<br>    // 2) - 2, 4<br>    // 4) - something else?<br>    println(filtered)<br>    val mapped = map(numbers) { it + 10 }<br>    // What this prints:<br>    // 1) - 10, 20, 30, 40<br>    // 2) - 12, 14<br>    // 4) - something else?<br>    println(mapped)<br>}</pre><p>Now we have solved both the mutation and the iterator problem, since no one is able to mutate the numbers.</p><p>Due to this change, now we need to change the filter function to accept type of List. The implementation will be left as a reading exercise, but you can always check in Kotlin’s stdlib implementation of filter .</p><blockquote><strong>Note for Kotlin devs</strong>: technically List interface in Kotlin is read-only rather than a true immutable structure. Its contract does not require implementations to be immutable. Nevertheless, this does not change anything in what we have covered so far.</blockquote><p>Although this article covers several examples, the key point is that <strong>mutability should be used only when it is needed.</strong></p><h4>The cost</h4><p>This abstraction is more “costly” compared to its mutable counterpart, since following the <strong>immutability principle </strong>means that we have to copy values on each update. That being said, here we trade readability and maintainability over resources. Modern machines are really fast and cheap, so we can afford to choose this abstraction.</p><p>Keep in mind, reading code accounts for about ~75% of our programming tasks, and most of the code we write is only read and not updated.</p><h4>Further reading</h4><p>This topic of “Immutability vs Mutability” is broad, and in this article I only shared my “quick” notes on it. If you are interested in further reading, I have included some helpful links.</p><ul><li><a href="https://www.youtube.com/watch?v=FQERMVABRrQ&amp;t=2373s&amp;ab_channel=Devoxx">The Power and Practically of Immutability (<strong>beautiful talk</strong>) by Venkat Subramaniam</a></li><li><a href="https://elizarov.medium.com/immutability-we-can-afford-10c0dcb8351d">Immutability we can afford by Roman Elizarov</a></li><li><a href="https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#reading_9_mutability_immutability">Immutability &amp; Mutability MIT slides</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ae70aedb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Opinionated one-liners in kotlin]]></title>
            <link>https://medium.com/@george.719pap/opinionated-one-liners-in-kotlin-dfc628b4847a?source=rss-a8addc4b58c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc628b4847a</guid>
            <category><![CDATA[kotlin-scope-functions]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[George Papadopoulos]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 06:33:13 GMT</pubDate>
            <atom:updated>2024-07-27T12:46:29.604Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Opinionated one-liners in Kotlin</strong></h3><p>In kotlin we have a set of opinionated one-liners, such as let, apply, also, and takeIf. These are called scope functions, and quoting the <a href="https://kotlinlang.org/docs/scope-functions.html">official docs</a>: &quot;whose sole purpose is to execute a block of code within the context of an object&quot;.</p><p>Based solely on that, it is not clear when to use them, so official docs provide some scenarios to help you <a href="https://kotlinlang.org/docs/scope-functions.html#function-selection">choose the right scope function</a>. Building upon that, I will try to provide some rules of thumb based on my experience for these, as they are easy to misuse due to their nature as “general-purpose APIs”.</p><p>Note that, even though through the examples we will focus mostly on .let function the same advice applies to all scope functions.</p><h3>When to use them</h3><p>All scope functions are most effective when they are used as one-line functions with clear names and intents.</p><pre>fun example1(): Node? = Node().let(Util::process)</pre><p>The .also scope function shines the most when it is used for simple one-line side effects.</p><pre>fun example2() {<br>  val scope = createScope().also { it.name = &quot;test3&quot; }<br>  // ... more code<br>}</pre><p>The .let scope function is particularly useful when you want to execute a function on non-null receiver and return the result.</p><pre>fun example3() {<br>  val curOrNull = nodeOrNull?.let(::processNode) // nullable variant<br>  // ... more code<br>}</pre><p>Another good use-case is to use .let for break/return early scenarios.</p><pre>fun example4() {<br>  createExceptionOrNull()?.let { throw it }<br>  // ... more code<br>}</pre><pre>fun example5(): Result {<br>  tryGetResult()?.let { return it }<br>  // ... more code<br>  return Result(&quot;second try&quot;)<br>}</pre><h3>When to consider not using them</h3><p>When using the scope functions, it is a good time to remember these two pieces of advice from Roman Elizarov (Kotlin’s ex-project-lead):</p><blockquote><em>1. Don’t abuse Kotlin’s flexibility in your API design. Prefer to be explicit</em>.</blockquote><blockquote><em>2. The use of scope functions is idiomatic in Kotlin. However, resist the urge to use them just to make your code shorter. Make sure that their use is consistent with the intent of the code you are writing</em>.</blockquote><p><a href="https://elizarov.medium.com/with-the-receiver-in-scope-7b52bdcca6e9">Ref link for quotes</a>.</p><p>Having in mind these advices, we will check some cases where we should consider not using scope functions.</p><p>Chaining scope functions on return statements is probably not a good idea. Most of the time we should prefer being explicit even at the cost of “lengthier” code.</p><pre>fun example6(): Node? {<br>  // ... code<br>  // ... multiple lines of code<br>  return Node().let { process(it) /* returns new node or null */ }<br>}</pre><p>Without scope function:</p><pre>fun rewriteExample6(): Node? {<br>  // ... code<br>  // ... multiple lines of code<br>  val node = Node()<br>  val newNode = process(node)<br>  return newNode<br>}</pre><p><strong>Note</strong> here we emulate a big function with multiple lines of code, since it might have been ok if this was an one liner.</p><p>Another example:</p><pre>fun example7() {<br>  // ... code<br>  // ... multiple lines of code<br>  return Node().also { swap(it) }<br>}</pre><p>Without scope function:</p><pre>fun rewriteExample7() {<br>  // ... code<br>  // ... multiple lines of code<br>  val node = Node()<br>  swap(node)<br>  return node<br>}</pre><h3>When to avoid</h3><h4>Avoid using elvis right after a scope function</h4><p>Most of the time when using the elvis operator after a scope function, there is a simpler alternative.</p><pre>fun example8() {<br>  val processedOrNew = Node().let { Util.process(it) } ?: createNode()<br>}</pre><p>Without scope function:</p><pre>fun rewriteExample8() {<br>  val node = Node()<br>  val processedOrNew = process(node) ?: createNode()<br>}</pre><p>It gets even worse if we apply a .let on a nullable receiver:</p><pre>fun example9() {<br>  val processedOrNew = createNodeOrNull()?.let { Util.process(it) } ?: createNode()<br>}</pre><p>This is tricky because it <strong>does not</strong> translate directly to simple if-else.</p><pre>fun rewriteExample9() {<br>  val node = createNodeOrNull()<br>  val processedOrNew = if (node != null) {<br>    process(node) ?: createNode() // &lt;-- note this branch<br>  } else {<br>    createNode()<br>  }<br>}</pre><p>Even though code is shorter when using a scope function, we create extra “mental-overhead” for the reader. They need to understand how the branches are translated.</p><h4><strong>Avoid overuse of chaining</strong></h4><p>When we author a complex multiline function as a single expression, we have to be aware to not sacrifice code readability because of that.</p><pre>fun example10(): Node =<br>  createNodeOrNull()<br>    ?.let { return it }<br>    ?: createNode()<br>      .also {<br>        log(<br>          &quot;&quot;&quot;<br>                    Multiple lines<br>                    with important info for $it<br>                &quot;&quot;&quot;.trimIndent()<br>        )<br>      }</pre><pre>fun rewriteExample10() {<br>  createNodeOrNull()?.let { return it } // simple `let` is ok<br>  val node = createNode()<br>  log(<br>    &quot;&quot;&quot;<br>            Multiple lines<br>            with important info for $node<br>                &quot;&quot;&quot;.trimIndent()<br>  )<br>  return node<br>}</pre><h4>Avoid nesting scope functions</h4><p>Nesting scope-functions always sacrifices code readability and creates extra “mental-overhead” for the readers.</p><pre>fun example11(input: NodeInfo): Node =<br>  input.node?.let { node -&gt;<br>    Util.process(node)<br>      ?.takeIf { it.next != null }<br>      ?.let { Util.swap(it); it }<br>  } ?: Node()</pre><p>We can rewrite this using guard-clauses.</p><pre>fun rewriteExample11(): Node {<br>  if (input.node == null) return Node() // simple guard-clause<br>  val processed = process(input.node) ?: return Node() // simple guard-clause<br>  if (processed.next == null) return Node() // simple guard-clause<br>  swap(processed)<br>  return processed<br>}</pre><h3>Conclusion</h3><p>We have to be explicit about our intents when using general-purpose APIs from stdlib.</p><p><strong>tl;dr</strong></p><ul><li>Consider to not chain scope functions on return statements when body has multiple lines of code.</li><li>Avoid using elvis operator after a scope function.</li><li>Avoid overuse of chaining with scope functions.</li><li>Avoid nesting scope functions.</li></ul><h4>Credits</h4><p>I would like to give my thanks to the Kotlin community for pointing out my mistakes.</p><h4>Edits</h4><ul><li>Removed example4 due to its ambiguity and lack of clear intent. In most cases rewriting it without using a scope function leads to simpler and more readable code.</li><li>Corrected the phrase “.let shines the most when is used for side-effects”, as .also is the appropriate scope function to use for side-effects.</li><li>Rewrote example2 using .also instead of .let function, since the return type would be Unit and it would not make sense in that particular example.</li><li>Rewrote example7 using .also instead of .let function, to avoid the extra line using it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc628b4847a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>