<?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 Edhar Avuzi on Medium]]></title>
        <description><![CDATA[Stories by Edhar Avuzi on Medium]]></description>
        <link>https://medium.com/@avuzia?source=rss-9cb9bd3348dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QYXGS88B_m1PFxxy2Iza6g.jpeg</url>
            <title>Stories by Edhar Avuzi on Medium</title>
            <link>https://medium.com/@avuzia?source=rss-9cb9bd3348dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:07:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@avuzia/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[Why Did PostgreSQL Return Only Three of Four Orders?]]></title>
            <link>https://medium.com/@avuzia/why-did-postgresql-return-only-three-of-four-orders-07fdb03a6bba?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/07fdb03a6bba</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 11:02:30 GMT</pubDate>
            <atom:updated>2026-11-18T11:03:09.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Btks7WoLv3dHtsOi" /><figcaption>Photo by <a href="https://unsplash.com/@sandbarproductions?utm_source=medium&amp;utm_medium=referral">Chase Baker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One database connection had just inserted order 104. In a second connection, SELECT * FROM orders; returned orders 101, 102, and 103. Both connections were talking to the same database. Where was the fourth order?</p><p><em>Astra 6.2 ran this experiment on PostgreSQL 16.16 and wrote this walkthrough from the recorded results.</em></p><h3>Two SQL windows, one table</h3><p>Picture two SQL windows side by side. The one on the left adds orders. The one on the right lists them. We started with three orders that were already saved. The left window then ran two commands.</p><pre>BEGIN;<br>INSERT INTO orders (order_id, status, total_cents)<br>VALUES (104, &#39;paid&#39;, 4200);</pre><p>BEGIN opens a transaction. The insert succeeded, but the left window still had a choice. It could keep the change with COMMIT or undo it with ROLLBACK. We paused there, with that choice still open.</p><p>In the right window, we asked PostgreSQL to list the orders.</p><pre>SELECT * FROM orders;</pre><p>The star asks for every column. With no WHERE clause, the query asks for every row this connection can see. It returned three. Then we ran COMMIT; in the left window and repeated the exact same query on the right. This time it returned four, including 104, paid, 4200.</p><h3>Where was order 104 during the first query?</h3><p>The two results tell us <em>when</em> the order became visible. They leave an interesting question open. Did PostgreSQL wait until commit to put the order in the table? To find out, we added logging inside the database server and watched it read the table.</p><p>PostgreSQL stores rows together in chunks called <em>pages</em>. This little table fit on one page. The insert also reported a location for order 104. It was on page 0 in slot 4. Think of that as the row’s address for this experiment.</p><p>The query plan called for a <em>sequential scan</em>, which means PostgreSQL walked through the table. On the first scan it reached slot 4. Three fields from the server log show what happened on each pass.</p><pre>Before commit    block=0  offset=4  visible=0<br>After commit     block=0  offset=4  visible=1</pre><p>Same page, same slot, same order. The last field tells us whether this reader could return the row. The first time the answer was no. PostgreSQL went on to finish the query and sent three rows back. The second time the answer was yes, and order 104 went back to the client too.</p><h3>What a reader is allowed to see</h3><p>The right window used PostgreSQL’s default setting, <em>Read Committed</em>. For a plain SELECT, each query gets a view of what other connections had committed when that query began. The first query began while order 104 could still be rolled back. The second began after the writer had committed it. A commit halfway through a running query would still be too late for that query. <a href="https://www.postgresql.org/docs/16/transaction-iso.html#XACT-READ-COMMITTED">PostgreSQL’s Read Committed rule</a></p><p>This comes up in integration tests. A test inserts an order, then calls an API to fetch it. The API opens its own database connection and reports “order not found.” Before adding a retry, check where the test calls COMMIT. If the test waits for the API response before committing, the API could wait ten seconds and still face exactly the same problem.</p><p>For anyone who wants to inspect the experiment, the <a href="https://medium.com/@avuzia/four-tuples-on-the-page-three-orders-in-the-result-9054e90c9ff1">original trace</a> includes the query plan, the server log, and the rows received by the client. You can also read the <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/heap/heapam.c#L499-L530">PostgreSQL loop that checks each row’s visibility</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07fdb03a6bba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four tuples on the page. Three orders in the result.]]></title>
            <link>https://medium.com/@avuzia/four-tuples-on-the-page-three-orders-in-the-result-9054e90c9ff1?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9054e90c9ff1</guid>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 05:28:56 GMT</pubDate>
            <atom:updated>2026-11-18T05:30:47.015Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclosure: GPT 6.2 Astra ran the PostgreSQL experiment and generated the text from the captured results.</em></p><p>The reader sent PostgreSQL the same 21 characters twice.</p><pre>SELECT * FROM orders;</pre><p>The first query returned three orders. The second returned four. Between the two, another connection ran COMMIT. The question was where, inside PostgreSQL, order 104 disappeared from the first result. The answer was visible in a single boolean on heap block zero.</p><h3>Give the query something to distinguish</h3><p>The setup used an ordinary table with three columns and a primary key. It committed orders 101, 102, and 103. A second connection inserted order 104 and left its transaction open. Its INSERT … RETURNING ctid, xmin reported (0,4) and 733. The first value locates this row version at block 0, item offset 4. The second identifies the transaction that inserted it. Those two values let us follow this particular order through the scan. · <a href="https://www.postgresql.org/docs/16/ddl-system-columns.html">PostgreSQL system columns</a></p><pre>S&gt;C D 440000001600020000000528302c342900000003373333  [&quot;(0,4)&quot;, &quot;733&quot;]</pre><p>The reader used Read Committed isolation. The reader sent the first query while the writer’s transaction was open and the second after its commit acknowledgment. PostgreSQL’s documented rule gives a prediction we can test. A plain SELECT in this setup sees rows committed before that statement began. Order 104 should appear only in the second result. · <a href="https://www.postgresql.org/docs/16/transaction-iso.html#XACT-READ-COMMITTED">Isolation rule</a></p><h3>Where the star went</h3><p>The reader sent a simple-query protocol message containing the literal SQL. At the end of raw parsing, the backend still had an A_STAR node and a reference to orders. Then ExpandAllTables produced three target entries named order_id, status, and total_cents. Those names survived rewriting. By the time the planner returned, the root of the plan was SEQSCAN. The index existed, but this execution scanned the table. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/tcop/postgres.c#L1194-L1198">Simple-query pipeline</a> · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/parser/parse_target.c#L1294-L1335">Star expansion in C</a></p><p>Request frame, selected fields from the backend trees, and the index definition.</p><pre>C&gt;S Q 510000001a53454c454354202a2046524f4d206f72646572733b00  SELECT * FROM orders;<br>{A_STAR}<br>:resname order_id<br>:resname status<br>:resname total_cents<br>:planTree {SEQSCAN<br>CREATE UNIQUE INDEX orders_pkey ON public.orders USING btree (order_id)</pre><p>A separate EXPLAIN ANALYZE also reported a sequential scan and one loop. After the commit it still estimated three rows and actually returned four. The trace above came from the ordinary query itself. · <a href="https://www.postgresql.org/docs/16/using-explain.html#USING-EXPLAIN-ANALYZE">How to read EXPLAIN</a></p><pre>{<br>  &quot;Node Type&quot;: &quot;Seq Scan&quot;,<br>  &quot;Plan Rows&quot;: 3,<br>  &quot;Actual Rows&quot;: 4,<br>  &quot;Actual Loops&quot;: 1,<br>  &quot;Shared Hit Blocks&quot;: 1,<br>  &quot;Shared Read Blocks&quot;: 0<br>}</pre><h3>The page contained all four</h3><p>The table’s main data file occupied 8,192 bytes, exactly one block in this build. For the ordinary query, ReadBufferExtended reported a shared-buffer hit on block 0 of orders. The separate plan measurement agreed, with one shared hit and zero shared reads at the scan node. “Sequential scan” described the access path. In this run, PostgreSQL already had the required heap page in memory. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/storage/buffer/bufmgr.c#L778-L787">Buffer manager source</a></p><pre>ORDERS_TRACE pid=71 ReadBufferExtended relation=orders oid=16384 fork=0 block=0 hit=1<br>ORDERS_TRACE pid=71 heapgetpage relation=orders block=0 line_pointers=4 all_visible=0 mvcc_snapshot=1</pre><p>Inside heapgetpage, the page had four item pointers. Its all-visible shortcut was off, and the scan had an MVCC snapshot, the reader’s view of which transactions count as visible. The heap code tested each normal tuple and collected the offsets that passed. Here are the boolean results the probe read from that loop. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/heap/heapam.c#L499-L530">Visibility loop</a> · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/heap/heapam_visibility.c#L1769-L1776">Snapshot dispatch</a></p><pre>Before COMMIT<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=1 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=2 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=3 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=4 xmin=733 visible=0</pre><pre>After COMMIT<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=1 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=2 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=3 xmin=731 visible=1<br>ORDERS_TRACE pid=71 heapgetpage block=0 offset=4 xmin=733 visible=1</pre><p>Offset 4 still had the same inserting transaction in the second scan. What changed was the outcome of the reader’s visibility test. In the first scan the heap handed the executor slots for offsets 1, 2, and 3, then reported an empty slot. In the second scan it also handed up offset 4. That is where the extra order entered the result. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/heap/heapam.c#L1191-L1217">Heap slot return path</a></p><pre>ORDERS_TRACE pid=71 heap_getnextslot slot block=0 offset=1<br>ORDERS_TRACE pid=71 heap_getnextslot slot block=0 offset=2<br>ORDERS_TRACE pid=71 heap_getnextslot slot block=0 offset=3<br>ORDERS_TRACE pid=71 heap_getnextslot empty slot<br>ORDERS_TRACE pid=71 heap_getnextslot slot block=0 offset=4<br>ORDERS_TRACE pid=71 heap_getnextslot empty slot</pre><h3>One call, down to the instruction</h3><p>How did a SQL executor reach that heap code? While the backend was inside heapgetpage, the probe captured its native stack. Read the stack from the older frames toward the younger ones and you can follow ExecutePlan into ExecSeqScan, through SeqNext and table_scan_getnextslot, and into heap_getnextslot. The symbolized excerpt preserves the intermediate execution frames. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/executor/nodeSeqscan.c#L50-L83">Sequential scan implementation</a></p><pre>frame       return_pc       pc_minus_1  symbol<br> 0        0x4e6627        0x4e6626  heapgetpage<br> 1        0x4e7087        0x4e7086  heapgettup_pagemode<br> 2        0x4e7782        0x4e7781  heap_getnextslot<br> 3        0x776b80        0x776b7f  table_scan_getnextslot<br> 4        0x776c48        0x776c47  SeqNext<br> 5        0x73b415        0x73b414  ExecScanFetch<br> 6        0x73b48a        0x73b489  ExecScan<br> 7        0x776c9d        0x776c9c  ExecSeqScan<br> 8        0x737299        0x737298  ExecProcNodeFirst<br> 9        0x72b8ad        0x72b8ac  ExecProcNode<br>10        0x72e283        0x72e282  ExecutePlan</pre><p>One boundary is worth inspecting. PostgreSQL’s table-access interface calls a function pointer, so the C expression alone leaves open which implementation ran. The heap access-method table assigns that pointer to heap_getnextslot. Here is the corresponding x86-64 instruction from the exact server executable that produced the trace. <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/include/access/tableam.h#L1056-L1073">Interface call</a> · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/heap/heapam_handler.c#L2553">Heap implementation registered</a></p><pre>0x776b7d   41 ff d0   call *%r8<br>0x776b80   c9         leave</pre><p>The call takes three bytes. The live stack recorded 0x776b80 as the return address in table_scan_getnextslot, immediately after that call. The next frame inward was heap_getnextslot. Together the executable and the stack identify which indirect call ran and which implementation it reached. These addresses belong to the captured binary.</p><h3>What came back over the connection</h3><p>For each visible slot the server’s printtup routine prepared one DataRow message. The first had a 25-byte payload. Its three text fields decoded to 101, paid, and 2599. The client received a row description, three data rows, a completion tag of SELECT 3, and a ready message. After commit, the client received a fourth data row containing 104, paid, and 4200, followed by SELECT 4. That observed row order is specific to the run. SQL requires an explicit ORDER BY when the order matters. · <a href="https://github.com/postgres/postgres/blob/c0534eb02de050ac1035ad7b3ad7c3f02980f153/src/backend/access/common/printtup.c#L320-L372">Row encoding in C</a> · <a href="https://www.postgresql.org/docs/16/protocol-message-formats.html">Protocol fields</a> · <a href="https://www.postgresql.org/docs/16/queries-order.html">Ordering</a></p><pre>ORDERS_TRACE pid=71 printtup DataRow columns=3 payload_bytes=25<br>S&gt;C D 440000001d00030000000331303100000004706169640000000432353939  [&quot;101&quot;, &quot;paid&quot;, &quot;2599&quot;]<br>S&gt;C C 430000000d53454c454354203300  &quot;SELECT 3&quot;<br>S&gt;C D 440000001d00030000000331303400000004706169640000000434323030  [&quot;104&quot;, &quot;paid&quot;, &quot;4200&quot;]<br>S&gt;C C 430000000d53454c454354203400  &quot;SELECT 4&quot;</pre><p>The two builds delivered byte-for-byte identical query messages and responses in each phase. The smallest piece of evidence that explains their result is the pair of readings for (0,4). PostgreSQL had already found order 104 on the first scan. The reader could return it on the second.</p><pre>SHA-256 of the complete reader wire transcripts<br>before-commit (both builds)  b60e73757108b93c2032aa85aa74b46d96e597a67c9a78d978d12c6e602f33e2<br>after-commit (both builds)  a472e2a01c5e1eb9a01586ead2fbe69c111312d934dab28bf360ed820665a5ac</pre><h3>How the measurements were made</h3><p>The comparison used two builds of PostgreSQL 16.16 from the release archive, one with unmodified backend code and one with narrow probes. Both builds used GCC 14.2, debug symbols, frame pointers, and disabled compiler optimization. The workspace blocked ptrace, so the instrumented backend captured its own stack and logged selected variables for the exact SQL string. A client recorded PostgreSQL message bytes at the application layer. A fresh rebuild and replay passed the same checks. This experiment measures control flow and data values on a warm, one-page table. It supplies no latency or physical-device measurements. · <a href="https://www.postgresql.org/ftp/source/v16.16/">PostgreSQL 16.16 release archive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9054e90c9ff1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Repeating Yourself in Gradle Kotlin DSL: Elegant Dependency Helpers]]></title>
            <link>https://medium.com/@avuzia/stop-repeating-yourself-in-gradle-kotlin-dsl-elegant-dependency-helpers-24193c164b12?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/24193c164b12</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 08:07:40 GMT</pubDate>
            <atom:updated>2025-08-20T08:11:47.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*-RnIrR-nowcOuQlY_7mzVA.png" /><figcaption>enhancements</figcaption></figure><p>If you’ve been working with <strong>Gradle Kotlin DSL</strong>, you’ve likely noticed how repetitive your dependencies { ... } block can get. Every dependency line is usually prefixed with implementation(...) or testImplementation(...). For small projects that’s fine, but for larger ones, this repetition becomes noisy and annoying.</p><p>Here’s a trick: you can create <strong>helper functions</strong> that let you declare groups of dependencies more elegantly — while keeping things type-safe and fully Gradle‑compliant.</p><h4>The Problem</h4><p>A typical build.gradle.kts dependencies block might look like this:</p><pre>dependencies {<br>    implementation(libs.spring.boot.starter.web)<br>    implementation(libs.kotlinx.serialization.json)<br>    implementation(libs.commercetools.http.client)<br>    implementation(libs.commercetools.sdk.api)<br><br>    testImplementation(libs.slf4j.api)<br>    testImplementation(libs.logback.classic)<br>    testImplementation(libs.mockk)<br>    testImplementation(libs.kotest.runner)<br>}</pre><p>Notice how implementation(...) and testImplementation(...) are repeated on every line. It’s boilerplate, and it doesn’t add value.</p><h4>The Solution: Extension Helpers</h4><p>With just a couple of helper functions, we can clean this up.</p><p>In your build.gradle.kts, add:</p><pre>fun DependencyHandlerScope.implementations(vararg deps: Any) =<br>    deps.forEach { this.implementation(it) }<br><br>fun DependencyHandlerScope.testImplementations(vararg deps: Any) =<br>    deps.forEach { this.testImplementation(it) }</pre><p>Now you can rewrite your dependencies block like this:</p><pre>dependencies {<br>    implementations(<br>        libs.spring.boot.starter.web,<br>        libs.kotlinx.serialization.json,<br>        libs.commercetools.http.client,<br>        libs.commercetools.sdk.api,<br>        libs.commercetools.sdk.importapi,<br>        libs.commercetools.sdk.ml,<br>    )<br><br>    testImplementations(<br>        libs.slf4j.api,<br>        libs.logback.classic,<br>        libs.mockk,<br>        libs.kotest.runner,<br>        libs.kotest.assertions,<br>        libs.kotest.property,<br>        libs.kotlinx.coroutines.test,<br>        libs.spring.boot.starter.test,<br>    )<br>}</pre><h4>Benefits</h4><p>✅ <strong>Cleaner build files</strong> — dependencies are grouped naturally, without visual noise.</p><p>✅ <strong>Easier maintenance</strong> — when scanning, your eye jumps directly to the libraries, not repeated keywords.</p><p>✅ <strong>Composable</strong> — you can add more helpers (e.g., runtimeOnlys(...), apiDependencies(...)) if your project needs them.</p><h4>Final Thoughts</h4><p>This tiny refactoring trick doesn’t change how Gradle resolves dependencies at all — it’s just <strong>syntactic sugar</strong> for better readability. But in projects with dozens of libraries, it makes your build.gradle.kts feel a lot lighter and more elegant.</p><p>If you value clean, maintainable build scripts, try this pattern — it might just become your new default.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24193c164b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Java to Kotlin: Why Kotlin Feels Better]]></title>
            <link>https://medium.com/@avuzia/from-java-to-kotlin-why-kotlin-feels-better-b16608ecb0e6?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16608ecb0e6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 05:59:23 GMT</pubDate>
            <atom:updated>2025-08-13T05:59:23.015Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s compare the same logic in Java vs Kotlin.</p><h4>Java</h4><pre>import java.util.stream.Collectors;<br>import java.util.stream.IntStream;<br><br>class Solution {<br>    private static final String VOWELS = &quot;aeiouAEIOU&quot;;<br><br>    public String toGoatLatin(String sentence) {<br>        String[] words = sentence.split(&quot; &quot;);<br>        return IntStream.range(0, words.length)<br>                .mapToObj(i -&gt; transformWord(i, words[i]))<br>                .collect(Collectors.joining(&quot; &quot;));<br>    }<br><br>    private String transformWord(int index, String word) {<br>        String core = VOWELS.indexOf(word.charAt(0)) &gt;= 0<br>                ? word + &quot;ma&quot;<br>                : word.substring(1) + word.charAt(0) + &quot;ma&quot;;<br>        return core + &quot;a&quot;.repeat(index + 1);<br>    }<br>}</pre><ul><li><strong>Boilerplate, Verbosity</strong>: Collectors.joining, IntStream.range, mapToObj, String[]… lots of ceremony.</li><li><strong>No </strong><strong>mapIndexed</strong>: Java doesn’t have a built-in for iterating with both index and value together.</li></ul><h4>Kotlin</h4><pre>private const val vowels = &quot;aeiouAEIOU&quot;<br><br>class Solution {<br>    fun toGoatLatin(sentence: String): String =<br>        sentence<br>            .split(&quot; &quot;)<br>            .mapIndexed(::transformWord)<br>            .joinToString(&quot; &quot;)<br>}<br><br>private fun transformWord(index: Int, word: String): String {<br>    val core = when (word.first() in vowels) {<br>        true -&gt; word + &quot;ma&quot;<br>        false -&gt; word.drop(1) + word.first() + &quot;ma&quot;<br>    }<br>    return core + &quot;a&quot;.repeat(index + 1)<br>}</pre><ul><li><strong>Built-in expressiveness</strong>: mapIndexed, joinToString, and in operator make the code concise yet readable.</li><li><strong>No type noise</strong>: No need to work with Collectors.</li><li><strong>Better defaults</strong>: Extension functions on collections and strings give you a fluent, declarative style without extra imports.</li></ul><p>✅ <strong>Why Kotlin wins here</strong>:<br>Kotlin’s standard library is built with small, composable, high-level functions that match how we think about data transformations. The result is fewer lines, less noise, and a more direct mapping from the problem description to code.</p><p>Problem description: <a href="https://leetcode.com/problems/goat-latin/">https://leetcode.com/problems/goat-latin/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16608ecb0e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ZIO Error Handling: The Importance of Exhaustive Pattern Matching]]></title>
            <link>https://towardsdev.com/zio-error-handling-the-importance-of-exhaustive-pattern-matching-270287f2b1b8?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/270287f2b1b8</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[zio]]></category>
            <category><![CDATA[scala-3]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 13:55:31 GMT</pubDate>
            <atom:updated>2025-08-23T15:55:16.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8msMTrhborwqK8wD" /><figcaption>Photo by <a href="https://unsplash.com/@sonika_agarwal?utm_source=medium&amp;utm_medium=referral">Sonika Agarwal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When working with ZIO and error handling in Scala, the compiler is your friend. It helps catch potential runtime issues at compile time through exhaustive pattern matching warnings. Let’s explore a common scenario and why the compiler warning matters.</p><h3>The Scenario</h3><p>Consider this complete ZIO application that simulates a user transaction system:</p><pre>import zio.{IO, UIO, ZIO, Unsafe, Console}<br><br>case class User(id: String, balance: Double)<br>case class TransactionId(id: String)<br>sealed trait FetchError<br>case object NetworkError extends FetchError<br>sealed trait ChargeError<br>case object InsufficientFunds extends ChargeError<br><br>def fetchUser: IO[FetchError, User] =<br>  ZIO.succeed(User(&quot;u123&quot;, balance = 100.0))<br><br>def charge(user: User, amount: Double): IO[ChargeError, TransactionId] =<br>  if (user.balance &gt;= amount)<br>    ZIO.succeed(TransactionId(&quot;tx-456&quot;))<br>  else<br>    ZIO.fail(InsufficientFunds)<br><br>val program: IO[FetchError | ChargeError, TransactionId] =<br>  for {<br>    user &lt;- fetchUser<br>    transaction &lt;- charge(user, 50.0)<br>  } yield transaction<br><br>val runApp: UIO[Unit] =<br>  program.fold(<br>    {<br>      //case NetworkError      =&gt; println(&quot;Failed to fetch user&quot;)<br>      case InsufficientFunds =&gt; println(&quot;Not enough balance&quot;)<br>    },<br>    tx =&gt; println(s&quot;Success! Transaction: ${tx.id}&quot;)<br>  )<br><br>println(&quot;Starting program...&quot;)<br>Unsafe.unsafe { implicit unsafe =&gt;<br>  zio.Runtime.default.unsafe.run(runApp)<br>}<br>println(&quot;Program finished&quot;)</pre><h3>The Warning: “Match May Not Be Exhaustive”</h3><p>The Scala compiler warns us:</p><pre>match may not be exhaustive.<br>It would fail on pattern case: NetworkError</pre><p>This warning is <strong>critical</strong> and should never be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*fL7qsT2vWcHhjXNE" /><figcaption>match may not be exhaustive.<br>It would fail on pattern case: NetworkError</figcaption></figure><h3>The Solutions</h3><h3>Option 1: Handle All Cases (Recommended)</h3><pre>val runApp: UIO[Unit] =<br>  program.fold(<br>    {<br>      case NetworkError      =&gt; println(&quot;Failed to fetch user&quot;)<br>      case InsufficientFunds =&gt; println(&quot;Not enough balance&quot;)<br>    },<br>    tx =&gt; println(s&quot;Success! Transaction: ${tx.id}&quot;)<br>  )</pre><h3>Option 2: Use a Catch-All Pattern</h3><pre>val runApp: UIO[Unit] =<br>  program.fold(<br>    {<br>      case InsufficientFunds =&gt; println(&quot;Not enough balance&quot;)<br>      case _                 =&gt; println(&quot;An error occurred&quot;)<br>    },<br>    tx =&gt; println(s&quot;Success! Transaction: ${tx.id}&quot;)<br>  )</pre><h3>Option 3: Use foldCause for More Control</h3><pre>val runApp: UIO[Unit] =<br>  program.foldCause(<br>    cause =&gt; println(s&quot;Operation failed: ${cause.prettyPrint}&quot;),<br>    tx =&gt; println(s&quot;Success! Transaction: ${tx.id}&quot;)<br>  )</pre><h3>Best Practices</h3><h3>1. Never Suppress Compiler Warnings</h3><p>Exhaustiveness warnings are there for a reason. They prevent runtime crashes.</p><h3>2. Use Sealed Traits Effectively</h3><pre>sealed trait AppError<br>case object NetworkError extends AppError<br>case object InsufficientFunds extends AppError<br>case object DatabaseError extends AppError</pre><p>Compiler will warn if you don’t handle all cases.</p><h3>3. Consider Error Hierarchies</h3><pre>sealed trait AppError<br>sealed trait FetchError extends AppError<br>sealed trait ChargeError extends AppError<br>case object NetworkError extends FetchError<br>case object InsufficientFunds extends ChargeError</pre><h3>Conclusion</h3><p>The “match may not be exhaustive” warning is not just a suggestion — it’s a critical safety check. In functional programming and especially with ZIO, proper error handling through exhaustive pattern matching ensures your applications are robust and predictable.</p><p><strong>Remember</strong>: If the compiler warns you about incomplete patterns, listen to it. Your future self (and your users) will thank you when your application doesn’t crash unexpectedly due to an unhandled error case.</p><p>The fix is simple: handle all cases in your pattern match, or use a catch-all pattern if appropriate. Never ignore exhaustiveness warnings in production code.</p><p>Try it out <a href="https://scastie.scala-lang.org/AWc9qq2pSnStC5LYiK3P1Q">https://scastie.scala-lang.org/AWc9qq2pSnStC5LYiK3P1Q</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270287f2b1b8" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/zio-error-handling-the-importance-of-exhaustive-pattern-matching-270287f2b1b8">ZIO Error Handling: The Importance of Exhaustive Pattern Matching</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforcing ktfmt with Spotless Maven and a Git Pre-Push Hook — No Excuses for Messy Kotlin]]></title>
            <link>https://blog.stackademic.com/enforcing-ktfmt-with-spotless-maven-and-a-git-pre-push-hook-no-excuses-for-messy-kotlin-9075d1c88eed?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9075d1c88eed</guid>
            <category><![CDATA[coding-best-practices]]></category>
            <category><![CDATA[spotless]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 06:09:20 GMT</pubDate>
            <atom:updated>2025-08-10T21:00:37.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enforcing ktfmt with Spotless Maven and a Git Pre-Push Hook — No Excuses for Messy Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5do8F4uJQ-aFPo2X" /><figcaption>Photo by <a href="https://unsplash.com/@gileres?utm_source=medium&amp;utm_medium=referral">Gil Ribeiro</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Code formatting shouldn’t be a debate. In Kotlin, <strong>ktfmt</strong> solves that with one opinionated, deterministic style. Combine it with <a href="https://github.com/diffplug/spotless">Spotless Maven Plugin</a> and a Git pre-push hook, and you’ll never push ugly code again.</p><p>This post walks you through a minimal, <strong>bulletproof setup</strong> that will block unformatted code at push time and even fix it for you automatically.</p><h3>Why ktfmt + Spotless?</h3><ul><li><strong>ktfmt</strong>: Opinionated Kotlin formatter by Facebook. No config arguments about tabs vs. spaces — you just run it and move on.</li><li><strong>Spotless Maven Plugin</strong>: Integrates ktfmt directly into your Maven build lifecycle, so formatting becomes a first-class citizen.</li></ul><h3>Step 1 — Add Spotless Maven Plugin to pom.xml</h3><p>Add this to your pom.xml -&gt; &lt;properties&gt; section. The &lt;properties&gt; block makes version upgrades painless.</p><pre>&lt;properties&gt;<br>  &lt;spotless.version&gt;2.46.1&lt;/spotless.version&gt;<br>&lt;/properties&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Czn4p5Zi8P35SkczYkeq0Q.png" /><figcaption>How it looks for me</figcaption></figure><p>Add this to your &lt;plugins&gt; section:</p><pre>&lt;plugin&gt;<br> &lt;groupId&gt;com.diffplug.spotless&lt;/groupId&gt;<br> &lt;artifactId&gt;spotless-maven-plugin&lt;/artifactId&gt;<br> &lt;version&gt;${spotless.version}&lt;/version&gt;<br> &lt;configuration&gt;<br>  &lt;kotlin&gt;<br>   &lt;includes&gt;<br>    &lt;include&gt;src/main/kotlin/**/*.kt&lt;/include&gt;<br>    &lt;include&gt;src/test/kotlin/**/*.kt&lt;/include&gt;<br>   &lt;/includes&gt;<br>   &lt;ktfmt&gt;<br>    &lt;version&gt;0.56&lt;/version&gt;<br>   &lt;/ktfmt&gt;<br>   &lt;trimTrailingWhitespace/&gt;<br>   &lt;endWithNewline/&gt;<br>  &lt;/kotlin&gt;<br> &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*N1XfWTUis4ogKGVjBufX2w.png" /><figcaption>How it looks for me</figcaption></figure><p>From the root of your repo run:</p><pre>mvn spotless:install-git-pre-push-hook</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9rVIVwGKV_L-Pr9Pid9HQ.png" /><figcaption>Part of the command log output</figcaption></figure><p>What this does:</p><ul><li>Creates .git/hooks/pre-push file in your local repo.</li><li>That hook runs spotless:check before every Git push.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhvk_hvOvKOtrNBGI70sYw.png" /><figcaption>Proof from my project</figcaption></figure><ul><li>If violations are found, it automatically runs spotless:apply, <strong>aborts your push</strong>, and tells you to commit the fixes before trying again (that is tells you to commit file changed after it automatically runs spotless:apply).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xduGB0BQS5yLts_SUyd2Fg.png" /><figcaption>Proof from my project</figcaption></figure><p>From now on, any unformatted .kt file you try to push will:</p><ol><li>Fail the push.</li><li>Be automatically reformatted.</li><li>Wait for you to commit the clean file and re-push.</li></ol><h3>Step 3— Test It</h3><ol><li>Break the formatting in a Kotlin file (swap an import order, remove a newline, etc. — just make the code look ugly unformatted).</li><li>Commit and push:</li></ol><pre>git commit -am &quot;bad format test&quot;<br>git push</pre><p>You’ll see Spotless block the push, reformat the file, and tell you to commit again:</p><pre>spotless found problems, running spotless:apply; commit the result and re-push</pre><h3>TL;DR</h3><p>From then on:</p><ul><li>Unformatted Kotlin code <strong>cannot</strong> leave your machine.</li><li>Fixes are applied automatically.</li><li>You just commit the updated (auto formatted) file and push.</li></ul><p><strong>Result:</strong> Zero bikeshedding, zero excuses, zero discussiomns on anyones preferences, always clean Kotlin code in your repo.</p><p>If your team still isn’t enforcing formatting, you’re just asking for chaos. Fix it.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9075d1c88eed" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/enforcing-ktfmt-with-spotless-maven-and-a-git-pre-push-hook-no-excuses-for-messy-kotlin-9075d1c88eed">Enforcing ktfmt with Spotless Maven and a Git Pre-Push Hook — No Excuses for Messy Kotlin</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Imperative Loops to Declarative Folds in Kotlin]]></title>
            <link>https://towardsdev.com/from-imperative-loops-to-declarative-folds-in-kotlin-2079b2da001c?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2079b2da001c</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 05:43:49 GMT</pubDate>
            <atom:updated>2025-08-23T17:43:03.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tnGyugtNNwTuuJOb" /><figcaption>Photo by <a href="https://unsplash.com/@anainsomnia?utm_source=medium&amp;utm_medium=referral">Anastasiia Malai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>A tiny refactor that unlocks clarity and testability</em></p><p>I was solving a LeetCode problem <a href="https://leetcode.com/problems/number-of-lines-to-write-string">https://leetcode.com/problems/number-of-lines-to-write-string</a> and initially reached for the usual <strong>imperative approach</strong>: a loop, some mutable variables, and a couple of conditionals to manage line wrapping.</p><p>It worked fine, but as someone who prefers <strong>composable, immutable, and testable code</strong>, I saw an opportunity to refactor it into something more declarative - using Kotlin’s fold(), a simple state data class, and a pure function to drive all the logic.</p><p>What started as a basic string traversal became a nice example of moving from <strong>imperative</strong> to <strong>functional thinking</strong>, where the code becomes not just shorter, but more expressive, modular, and testable.</p><h3>The Starting Point . Plain Imperative</h3><pre>class Solution {<br>  fun numberOfLines(widths: IntArray, s: String): IntArray {<br>    var linesCounter = 1<br>    var currentWidth = 0<br>    for (char in s) {<br>      val charWidth = widths[char - &#39;a&#39;]<br>      if (currentWidth + charWidth &gt; 100) {<br>        linesCounter++<br>        currentWidth = charWidth<br>      } else {<br>        currentWidth += charWidth<br>      }<br>    }<br>    return intArrayOf(linesCounter, currentWidth)<br>  }<br>}</pre><p>It works, but it hides <strong>state-transitions</strong> behind mutable vars and control-flow.</p><h3>The Upgrade . A Declarative, State-Driven Fold</h3><pre>class Solution {<br>  fun numberOfLines(widths: IntArray, string: String): IntArray {<br>    val initialState = State(1, 0)<br>    val finalState =<br>      string.fold(initialState) { state, char -&gt;<br>        nextState(state, char, widths)<br>      }<br>    return intArrayOf(finalState.lines, finalState.currentLineWidth)<br>  }<br><br>  fun nextState(state: State, char: Char, widths: IntArray): State {<br>    val (lines, currentLineWidth) = state<br>    val charWidth = widths[char - &#39;a&#39;]<br>    return if (currentLineWidth + charWidth &gt; 100) {<br>      State(lines + 1, charWidth)<br>    } else {<br>      State(lines, currentLineWidth + charWidth)<br>    }<br>  }<br>}<br><br>data class State(val lines: Int, val currentLineWidth: Int)</pre><p><em>What changed?</em></p><ul><li>We model <em>state</em> explicitly with a data class State.</li><li>fold walks the string while <strong>dealing with immutable state</strong>.</li><li>Transition logic lives in a pure function nextState().</li></ul><h3>Why This Matters</h3><ul><li><strong>Testability:</strong> nextState is a pure, side-effect-free function. Unit-test it with simple parameterized cases.</li><li>I<strong>mmutability:</strong> No var, so accidental mutable shared-state bugs vanish.</li><li><strong>Readability:</strong> Logic reads as “<strong>take state → take char → produce new state</strong>”, mirroring the mental model.</li><li><strong>Composability, Open/Closed Principle:</strong> Need logging, metrics, or alternative width policies? Wrap or compose new state transitions without touching the loop.</li><li><strong>Future Proofing</strong> Switching to streams, flows, or parallel processing later is straightforward when side-effects are isolated.</li></ul><h3>Micro-Tests Showcase</h3><pre>@ParameterizedTest<br>@MethodSource(&quot;nextStateTestCases&quot;)<br>fun `should transition to correct state given character and widths`(<br>    initialState: State,<br>    character: Char,<br>    characterWidths: IntArray,<br>    expectedState: State<br>) {<br>    assertEquals(expectedState, Solution().nextState(initialState, character, characterWidths))<br>}<br><br>fun nextStateTestCases() = listOf(<br>    Arguments.of(<br>        State(lines = 1, currentLineWidth = 80),<br>        &#39;a&#39;,<br>        IntArray(26) { 10 },<br>        State(lines = 1, currentLineWidth = 90)<br>    ),<br>    Arguments.of(<br>        State(lines = 1, currentLineWidth = 95),<br>        &#39;b&#39;,<br>        IntArray(26) { 10 },<br>        State(lines = 2, currentLineWidth = 10)<br>    )<br>)</pre><p>Since nextState() contains all the logic for transitioning the state, and the rest of the algorithm (fold()) simply applies this function using each character in the input string, testing nextState() thoroughly gives strong confidence in the overall behavior. As long as fold() is used correctly, you don&#39;t need to test numberOfLines() exhaustively - its correctness is largely ensured by validating nextState().</p><h3>Takeaway</h3><p>Refactoring from <em>imperative</em> to <em>declarative</em> isn’t about style points - it’s about <strong>making behavior obvious, isolating state, and enabling fast feedback through unit tests</strong>. Next time you spot a loop shielding mutable state, try folding it into clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2079b2da001c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/from-imperative-loops-to-declarative-folds-in-kotlin-2079b2da001c">From Imperative Loops to Declarative Folds in Kotlin</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under the Bonnet: A Step-by-Step Look at Java’s HashMap.put()]]></title>
            <link>https://medium.com/@avuzia/under-the-bonnet-a-step-by-step-look-at-javas-hashmap-put-75360a8c707e?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/75360a8c707e</guid>
            <category><![CDATA[association]]></category>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 15:17:38 GMT</pubDate>
            <atom:updated>2025-07-28T15:17:38.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTJYojwo8Q9pTRRE" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A seemingly simple line of code, hashMap.put(key, value), conceals a sophisticated process of hashing, array indexing, and object creation. Let&#39;s trace the journey of a single entry, hashMap.put(1, 1), as it navigates the internal machinery of Java&#39;s HashMap.</p><pre>void main() {<br>    var hashMap = new HashMap&lt;&gt;();<br>    hashMap.put(1, 1);<br>}</pre><h3>Step 1: The Public Facade - put(K key, V value)</h3><p>The journey begins at the public put() method. This method acts as a clean entry point, immediately delegating the core work to an internal method, putVal(), after first calculating the key&#39;s hash code.</p><pre>public V put(K key, V value) {<br>    return putVal(hash(key), key, value, false, true);<br>}</pre><h3>Step 2: The Art of Hashing - hash(Object key)</h3><p>Before an entry can be placed, the HashMap must determine <em>where</em> it should go. This is the role of the hash() method.</p><pre>static final int hash(Object key) {<br>    int h;<br>    return (key == null) ? 0 : (h = key.hashCode()) ^ (h &gt;&gt;&gt; 16);<br>}</pre><p>This static method is engineered for efficiency and to reduce collisions. For any given key, it takes its standard hashCode() and <strong>XORs</strong> it with its own 16 higher-order bits shifted down. This technique, known as &quot;spreading&quot;, ensures that variations in the upper bits of a hash code influence the lower bits, which are critical for calculating the array index. This leads to a better distribution of entries across the buckets.</p><p>For our key, Integer.valueOf(1), the hash code is 1. The calculation is 1 ^ (1 &gt;&gt;&gt; 16), which simplifies to 1 ^ 0, resulting in a final hash of <strong>1</strong>.</p><h3>Step 3: The Engine Room - putVal() and resize()</h3><p>This is where the main logic resides. putVal is responsible for initialising the map, placing the new entry, and handling any potential collisions.</p><h4>Phase 1: Lazy Initialisation</h4><p>Upon entry to putVal, the code checks if the internal storage table is initialised.</p><pre>if ((tab = table) == null || (n = tab.length) == 0)<br>    n = (tab = resize()).length;</pre><p>Since this is the first put operation on a new HashMap, the table field is null. This triggers a call to resize(). The resize() method, when called on an empty map, performs the initial setup:</p><ul><li>It creates a new Node&lt;K,V&gt;[] array with the DEFAULT_INITIAL_CAPACITY of <strong>16</strong>.</li><li>It calculates the threshold for the next resize, which is capacity * loadFactor (16 * 0.75), setting it to <strong>12</strong>.</li><li>It assigns the newly created array to the table field and returns it.</li></ul><h4>Phase 2: Locating the Bucket</h4><p>Back in putVal(), the code now has a table of size 16. It calculates the specific array index, or &quot;bucket,&quot; for our entry using a clever bitwise trick: i = (n - 1) &amp; hash.</p><p>This operation is a highly performant equivalent of hash % n when n is a power of two. For our entry:</p><ul><li>n (capacity) = 16</li><li>hash = 1</li><li>i = (16 - 1) &amp; 1 which is 15 &amp; 1, resulting in an index of <strong>1</strong>.</li></ul><h4>Phase 3: Creating and Placing the Nod</h4><pre>if ((p = tab[i]) == null) // i is 1<br>    tab[i] = newNode(hash, key, value, null);</pre><p>As the table is brand new, tab[1] is null. The code proceeds to call newNode(), which simply constructs a new Node object containing our hash, key, value, and a null reference for the next field. This new Node is then placed directly into tab[1].</p><h4>Phase 4: Final Housekeeping</h4><p>Finally, putVal performs some concluding tasks:</p><ul><li>It increments modCount, a counter used to detect concurrent modifications.</li><li>It increments the size of the map to 1.</li><li>It checks if size (1) has exceeded the threshold (12). It has not, so another resize() is avoided.</li><li>It returns null, as there was no previous value associated with the key 1.</li></ul><h3>What We Didn’t See</h3><p>This simple insertion did not execute several key code paths within putVal, which are reserved for more complex scenarios:</p><ul><li><strong>Collision Handling:</strong> We did not have to traverse a linked list or a tree because our target bucket was empty.</li><li><strong>Value Replacement:</strong> We did not overwrite an existing value because the key was new to the map.</li><li><strong>Treeification:</strong> The bucket did not reach the threshold (TREEIFY_THRESHOLD) required to convert a linked list of nodes into a more performant balanced tree.</li></ul><h3>Key Insights</h3><p>This deep dive reveals several core design principles of HashMap:</p><ul><li><strong>Lazy Initialisation:</strong> Memory for the internal array is only allocated when the first element is inserted, saving resources for maps that are created but never used.</li><li><strong>Bitwise Efficiency:</strong> The use of bitwise AND for index calculation and XOR for hash spreading demonstrates a focus on performance at the lowest level.</li><li><strong>Elegant Growth Strategy:</strong> The combination of a load factor and a resizing mechanism ensures the map maintains good performance as it grows.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75360a8c707e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-commit Git Hooks in a Kotlin + Maven Project with Husky]]></title>
            <link>https://towardsdev.com/pre-commit-git-hooks-in-a-kotlin-maven-project-with-husky-3181a79af13b?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3181a79af13b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[git-hooks]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 06:14:34 GMT</pubDate>
            <atom:updated>2025-07-28T16:18:19.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T5THqIgjqpLQnKfm" /><figcaption>Photo by <a href="https://unsplash.com/@daybrandon?utm_source=medium&amp;utm_medium=referral">Brandon Day</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Writing Kotlin is fun, but keeping your code clean and consistent? Easy to forget. This article shows how you can bring <strong>Husky</strong>, a popular Git hooks manager, into a <strong>pure Kotlin + Maven</strong> project to automate formatting with ktlin. If you’ve already got a Kotlin project, you’re just minutes away from enforcing code quality <em>before every commit</em>.</p><h3>Tools used</h3><ul><li>🟣 Kotlin</li><li>💩 Maven</li><li>🧹 ktlint Maven plugin for formatting</li><li>🟩 Node.js</li><li>🐶 Husky for Git hooks</li><li>🐧 Unix shell (should work on macOS/Linux; Windows works via WSL/Git Bash)</li></ul><h3>Step 1: Set up ktlint for formatting</h3><p>Add this plugin to your pom.xml:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;com.github.gantsign.maven&lt;/groupId&gt;<br>    &lt;artifactId&gt;ktlint-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;3.5.0&lt;/version&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;id&gt;ktlint&lt;/id&gt;<br>            &lt;phase&gt;none&lt;/phase&gt;<br>        &lt;/execution&gt;<br>        &lt;execution&gt;<br>            &lt;id&gt;ktlint-format&lt;/id&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;format&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>Now you can format Kotlin code with:</p><pre>mvn ktlint:format</pre><p>But you probably don’t want to run this command manually a lot of times. So, let’s automate it.</p><h3>🐶 Step 2: Add Husky to your project</h3><p>Even if you’re not building a Node.js app, <strong>Husky works perfectly</strong> as a Git hook manager.</p><h3>1. Initialize package.json:</h3><pre>npm init -y</pre><h3>2. Install Husky:</h3><pre>npm install husky --save-dev</pre><h3>3. Initialize hooks:</h3><pre>npx --yes husky-init</pre><p>This creates a .husky/ folder and a default .husky/pre-commit file in your project.</p><h3>4: Replace the default hook with ktlint</h3><p>Open .husky/pre-commit and replace it with:</p><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br><br>echo &quot;▶ Running ktlint format...&quot;<br>./mvnw ktlint:format<br><br>FORMAT_STATUS=$?<br>if [ $FORMAT_STATUS -ne 0 ]; then<br>  echo &quot;✘ ktlint format failed. Aborting commit.&quot;<br>  exit 1<br>fi<br><br>echo &quot;✔ Format OK.&quot;</pre><p>You can adjust this script as you wish. Make sure you’re using the Maven Wrapper (./mvnw) for consistency across machines.</p><h3>Test it</h3><p>Try making a change, stage it, and commit:</p><pre>git commit -am &quot;Test formatting hook&quot;</pre><p>You’ll see ktlint run.</p><h3>Final Thoughts</h3><p>Adding Husky to a Kotlin Maven project is a clean way to enforce code quality without extra headache.</p><p>You’ll never accidentally commit bad code again 😎.</p><h3>Useful links</h3><ul><li><a href="https://github.com/typicode/husky">Husky GitHub</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3181a79af13b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/pre-commit-git-hooks-in-a-kotlin-maven-project-with-husky-3181a79af13b">Pre-commit Git Hooks in a Kotlin + Maven Project with Husky</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Refactoring: Smart Tree Traversal - From Mutable State to Pure Sequences]]></title>
            <link>https://blog.stackademic.com/kotlin-refactoring-smart-tree-traversal-from-mutable-state-to-pure-sequences-45db77a95dcf?source=rss-9cb9bd3348dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/45db77a95dcf</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Edhar Avuzi]]></dc:creator>
            <pubDate>Sun, 20 Jul 2025 01:13:34 GMT</pubDate>
            <atom:updated>2025-07-21T12:15:46.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin Refactoring. Smart Tree Traversal - From Mutable State to Pure Sequences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1D-j41O7qY4Ep9Dp" /><figcaption>Photo by <a href="https://unsplash.com/@kvitka?utm_source=medium&amp;utm_medium=referral">Margarita Shtyfura</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>When tree pruning meets Kotlin Sequences — turning stateful algorithms into declarative pipelines</em></p><h3>🚫 Don’t write such stateful imperative code in Kotlin:</h3><pre>class Solution {<br>    fun findSecondMinimumValue(root: TreeNode): Int {<br>        val smallest = root.`val`<br>        var candidate: Int? = null<br><br>        fun visit(node: TreeNode?) {<br>            node ?: return<br>            val value = node.`val`<br>            when {<br>                value &gt; smallest &amp;&amp; (candidate == null || value &lt; candidate!!) -&gt;<br>                    candidate = value<br>                value == smallest -&gt; {<br>                    visit(node.left)<br>                    visit(node.right)<br>                }<br>            }<br>        }<br><br>        visit(root)<br>        return candidate ?: -1<br>    }<br>}</pre><p>🔄 <strong>The imperative problems:</strong> Mutable state tracking (var candidate), scattered null checks, complex conditional logic mixed with traversal, and side-effect heavy recursion that mutates external state.</p><h3>✅ Write this instead - pure sequences with intelligent pruning</h3><pre>class Solution {<br>    fun findSecondMinimumValue(root: TreeNode): Int {<br>        val target = root.`val`<br>        return root.prunedSequence(target)<br>            .filter { it &gt; target }<br>            .minOrNull()<br>            ?: -1<br>    }<br>}<br><br>private fun TreeNode.prunedSequence(target: Int): Sequence&lt;Int&gt; =<br>    sequence {<br>        yield(`val`)<br>        if (`val` == target) {<br>            left?.let { yieldAll(it.prunedSequence(target)) }<br>            right?.let { yieldAll(it.prunedSequence(target)) }<br>        }<br>    }</pre><h3>🧠 The Declarative Transformation</h3><p><strong>From Stateful to Stateless:</strong> The imperative version maintains mutable state (candidate) that gets updated during traversal. The declarative version generates all valid values as a sequence, then applies the selection logic separately.</p><p><strong>Separation of Concerns:</strong></p><ul><li><strong>Traversal strategy</strong> → prunedSequence() handles the &quot;how to visit&quot;</li><li><strong>Business logic</strong> → filter { it &gt; target }.minOrNull() handles the &quot;what to select&quot;</li></ul><p><strong>Pruning as Data:</strong> The pruning condition if (val == target) becomes part of the sequence generation, not scattered conditional logic mixed with state updates.</p><h3>🎯 Pattern Analysis</h3><pre>private fun TreeNode.prunedSequence(target: Int): Sequence&lt;Int&gt; =<br>    sequence {<br>        yield(`val`)                    // Always emit current value<br>        if (`val` == target) {          // Smart pruning condition<br>            left?.let { yieldAll(it.prunedSequence(target)) }<br>            right?.let { yieldAll(it.prunedSequence(target)) }<br>        }<br>        // Implicit: if val != target, subtree is pruned<br>    }</pre><p><strong>Intelligent Traversal:</strong> The sequence naturally embeds the optimization -we only explore subtrees where the parent equals the minimum. This captures the problem’s core insight elegantly.</p><p><strong>Lazy Evaluation:</strong> Values are generated on-demand rather than collecting all values upfront, providing better memory efficiency for large trees.</p><h3>🔄 Why This Matters</h3><p><strong>Cognitive Load:</strong> The imperative version requires tracking multiple concerns simultaneously - traversal state, candidate tracking, null safety, and pruning logic. The declarative version isolates each concern.</p><p><strong>Testability:</strong> Each function has a single responsibility:</p><p><strong>Composability:</strong> The sequence-based approach composes naturally with other operations:</p><pre>// Find candidates, not just the minimum<br>root.prunedSequence(target)<br>    .filter { it &gt; target }<br>    .sorted()<br>    .take(3)<br>    .toList()</pre><h3>⚡ Performance Benefits</h3><p><strong>Memory Efficiency:</strong> The sequence version generates values on-demand rather than collecting all values upfront, using less memory for large trees with many qualifying nodes.</p><p><strong>Predictable:</strong> No hidden state mutations or side effects - easier to reason about performance characteristics.</p><h3>🌳 Extension Functions as Tree Language</h3><pre>private fun TreeNode.prunedSequence(target: Int): Sequence&lt;Int&gt;</pre><p>By extending TreeNode, we create domain-specific vocabulary. Trees can now naturally express intelligent traversals, making the code read like the algorithm description.</p><p><strong>The Result:</strong> Algorithm logic separated from traversal mechanics, intelligent pruning embedded in data generation, and zero mutable state to track. Each piece does one thing well.</p><p><em>Stop juggling mutable state and complex conditionals. Let Kotlin’s sequences handle the traversal complexity while your business logic stays pure, testable, and composable.</em></p><p><strong>Problem source:</strong> <a href="https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/">LeetCode — Second Minimum Node In a Binary Tree</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45db77a95dcf" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/kotlin-refactoring-smart-tree-traversal-from-mutable-state-to-pure-sequences-45db77a95dcf">Kotlin Refactoring: Smart Tree Traversal - From Mutable State to Pure Sequences</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>