<?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 Christian Hansen on Medium]]></title>
        <description><![CDATA[Stories by Christian Hansen on Medium]]></description>
        <link>https://medium.com/@pixelreverb?source=rss-bd1cfa505d44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dhduIOR8VtVKQjFWHLTBzg@2x.jpeg</url>
            <title>Stories by Christian Hansen on Medium</title>
            <link>https://medium.com/@pixelreverb?source=rss-bd1cfa505d44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:24:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pixelreverb/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[Next level if-statement]]></title>
            <link>https://medium.com/@pixelreverb/next-level-if-statement-96b6c1a614d9?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b6c1a614d9</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 20:52:02 GMT</pubDate>
            <atom:updated>2026-07-15T20:52:02.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Your if-statement, but next level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mF6KAcypYLpF-RD0" /><figcaption>Photo by <a href="https://unsplash.com/@sophiakunkel?utm_source=medium&amp;utm_medium=referral">Sophia Kunkel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since working with React and TypeScript is not currently part of my daily work, I regularly revisit and refactor my personal projects. Not because it’s strictly necessary — but to stay sharp in a fast-moving ecosystem and to keep my skills from getting rusty.</p><p>In the end, programming — like anything else — is a skill you need to practice to maintain proficiency.</p><p>This short article takes a look at chained if statements and how we can refactor them. Finally, the refactored code is used in a small React hook to determine breakpoints for different screen sizes. You can find the hook implementation at the end of this article.</p><h3>The starting point</h3><p>While working on one of my projects, I needed to detect the screen size to apply certain logic. In the React ecosystem, this is typically done using a hook.</p><p>Since this is a common problem (and I prefer not to reinvent the wheel), I did a quick search and found a suitable implementation.</p><p>It worked fine, but it contained the following logic:</p><pre>const handleResize = () =&gt; {<br>  if (window.innerWidth &lt; 640) {<br>    setScreenSize(&quot;xs&quot;);<br>  } else if (window.innerWidth &gt;= 640 &amp;&amp; window.innerWidth &lt; 768) {<br>    setScreenSize(&quot;sm&quot;);<br>  } else if (window.innerWidth &gt;= 768 &amp;&amp; window.innerWidth &lt; 1024) {<br>    setScreenSize(&quot;md&quot;);<br>  } else if (window.innerWidth &gt;= 1024 &amp;&amp; window.innerWidth &lt; 1280) {<br>    setScreenSize(&quot;lg&quot;);<br>  } else if (window.innerWidth &gt;= 1280 &amp;&amp; window.innerWidth &lt; 1536) {<br>    setScreenSize(&quot;xl&quot;);<br>  } else if (window.innerWidth &gt;= 1536) {<br>    setScreenSize(&quot;2xl&quot;);<br>  }<br>};</pre><p>There is nothing inherently wrong with this code — it works as expected.</p><p>However, it duplicates boundary logic and introduces unnecessary complexity. Maintaining such conditions over time can become error-prone, especially when breakpoints change.</p><h3>Considerations</h3><p>I know, I know — “It is just an if-statement.”, you might say. But — just for the next few minutes — let’s be a little bit crazy and follow me into the rabbit hole by applying a few refactoring steps:</p><ul><li>Introduce a variable to hold the result and call setScreenSize only once</li><li>Replace else if chains with sequential if statements</li><li>Remove duplicated boundary definitions</li></ul><p>Some of these refactoring steps may seem counter-intuitive at first, but we use them to build our mental model for our final solution.</p><h3>Step 1 — Extract the result</h3><p>First, we introduce a local variable and remove multiple state updates:</p><pre>const handleResize = () =&gt; {<br>  let result = &quot;&quot;;<br><br>  if (window.innerWidth &lt; 640) {<br>    result = &quot;xs&quot;;<br>  } else if (window.innerWidth &gt;= 640 &amp;&amp; window.innerWidth &lt; 768) {<br>    result = &quot;sm&quot;;<br>  } else if (window.innerWidth &gt;= 768 &amp;&amp; window.innerWidth &lt; 1024) {<br>    result = &quot;md&quot;;<br>  } else if (window.innerWidth &gt;= 1024 &amp;&amp; window.innerWidth &lt; 1280) {<br>    result = &quot;lg&quot;;<br>  } else if (window.innerWidth &gt;= 1280 &amp;&amp; window.innerWidth &lt; 1536) {<br>    result = &quot;xl&quot;;<br>  } else if (window.innerWidth &gt;= 1536) {<br>    result = &quot;2xl&quot;;<br>  }<br><br>  setScreenSize(result);<br>};</pre><p>This already improves debuggability and separation of concerns.</p><h3>Step 2 — Sequential conditions</h3><p>Next, we replace the else if chain with independent if statements.</p><p>It works in this scenario because:</p><ul><li>all conditions depend on the same value (window.innerWidth)</li><li>thresholds are ordered</li><li>later conditions can safely overwrite earlier ones</li></ul><pre>const handleResize = () =&gt; {<br>  let result = &quot;&quot;;<br><br>  if (window.innerWidth &lt; 640) result = &quot;xs&quot;;<br>  if (window.innerWidth &gt;= 640 &amp;&amp; window.innerWidth &lt; 768) result = &quot;sm&quot;;<br>  if (window.innerWidth &gt;= 768 &amp;&amp; window.innerWidth &lt; 1024) result = &quot;md&quot;;<br>  if (window.innerWidth &gt;= 1024 &amp;&amp; window.innerWidth &lt; 1280) result = &quot;lg&quot;;<br>  if (window.innerWidth &gt;= 1280 &amp;&amp; window.innerWidth &lt; 1536) result = &quot;xl&quot;;<br>  if (window.innerWidth &gt;= 1536) result = &quot;2xl&quot;;<br><br>  setScreenSize(result);<br>};</pre><p>Performance differences are negligible here — the benefit is structural clarity.</p><h3>Step 3 — Let it “fall through”</h3><p>Since the thresholds are ascending, we can simplify further by removing upper bounds and introducing a default:</p><pre>const handleResize = () =&gt; {<br>  let result = &quot;xs&quot;;<br><br>  if (window.innerWidth &gt;= 640) result = &quot;sm&quot;;<br>  if (window.innerWidth &gt;= 768) result = &quot;md&quot;;<br>  if (window.innerWidth &gt;= 1024) result = &quot;lg&quot;;<br>  if (window.innerWidth &gt;= 1280) result = &quot;xl&quot;;<br>  if (window.innerWidth &gt;= 1536) result = &quot;2xl&quot;;<br><br>  setScreenSize(result);<br>};</pre><p>The “fall through“ approach works well because each condition builds upon the previous one. The final value reflects the highest matching breakpoint.</p><p>The result is:</p><ul><li>easier to read</li><li>less error-prone</li><li>free of duplicated constraints</li></ul><h3>Bonus — Extracting intent</h3><p>If you want to push this a bit further, you can extract the comparison:</p><pre>const isGreaterOrEqual = (bound: number) =&gt; window.innerWidth &gt;= bound;<br><br>const handleResize = () =&gt; {<br>  let result = &quot;xs&quot;;<br><br>  if (isGreaterOrEqual(640)) result = &quot;sm&quot;;<br>  if (isGreaterOrEqual(768)) result = &quot;md&quot;;<br>  if (isGreaterOrEqual(1024)) result = &quot;lg&quot;;<br>  if (isGreaterOrEqual(1280)) result = &quot;xl&quot;;<br>  if (isGreaterOrEqual(1536)) result = &quot;2xl&quot;;<br><br>  setScreenSize(result);<br>};</pre><p>This can improve readability slightly, although it may be unnecessary for such a simple case.</p><h3>Exotic alternative — switch(true)</h3><p>For completeness, here’s a more unusual pattern: switch(true).</p><p>It can express the same logic — but it’s more controversial and generally less readable.</p><p><strong>Important:</strong> Order matters here. The cases must be evaluated from highest to lowest.</p><pre>const isGreaterOrEqual = (limit: number) =&gt; window.innerWidth &gt;= limit;<br><br>const handleResize = () =&gt; {<br>  let result = &quot;&quot;;<br><br>  switch (true) {<br>    case isGreaterOrEqual(1536): result = &quot;2xl&quot;; break;<br>    case isGreaterOrEqual(1280): result = &quot;xl&quot;; break;<br>    case isGreaterOrEqual(1024): result = &quot;lg&quot;; break;<br>    case isGreaterOrEqual(768): result = &quot;md&quot;; break;<br>    case isGreaterOrEqual(640): result = &quot;sm&quot;; break;<br>    default: result = &quot;xs&quot;;<br>  }<br><br>  setScreenSize(result);<br>};</pre><p>While valid, this approach is rarely preferred in modern JavaScript/TypeScript codebases. But it is good to know that something like that can be done. It kind of reflects a possibility that is introduced by other programming languages where logical expressions can be used as a criteria for a case.</p><h3>Make it data-driven</h3><p>At this point, we can take a step back.</p><p>All implementations so far are still <strong>code-driven</strong>. But the problem itself is actually <strong>data-driven</strong>.</p><p>A more scalable solution is to define breakpoints as data:</p><pre>const breakpoints = [<br>  { min: 1536, label: &quot;2xl&quot; },<br>  { min: 1280, label: &quot;xl&quot; },<br>  { min: 1024, label: &quot;lg&quot; },<br>  { min: 768, label: &quot;md&quot; },<br>  { min: 640, label: &quot;sm&quot; },<br>];<br><br>const getScreenSize = () =&gt; {<br>  const width = window.innerWidth;<br>  return breakpoints.find(bp =&gt; width &gt;= bp.min)?.label ?? &quot;xs&quot;;<br>};</pre><h4>It is a good approach because</h4><ul><li>No duplicated logic</li><li>Easy to extend or modify</li><li>Clear separation between <strong>data</strong> and <strong>behavior</strong></li><li>Scales well for more complex scenarios (themes, configs, user settings)</li></ul><p>This is typically the direction you’d take in larger or production-grade systems.</p><h3>Conclusion</h3><p>The original implementation was correct — but not optimal in terms of maintainability.</p><p>By</p><ul><li>removing duplicated constraints</li><li>leveraging ordered conditions</li><li>and simplifying control flow</li></ul><p>we significantly improved readability and robustness.</p><p>And by stepping back and recognizing the underlying structure, we can even move toward a fully data-driven solution.</p><p>Sometimes, improving an if statement is not about making it shorter—but about making it easier to reason about.</p><h4>The Hook</h4><p>Finally, the hook I’m currently using (requires React &gt;=19 because of useEffectEvent):</p><pre>&#39;use client&#39;;<br><br>import { useEffect, useEffectEvent, useState } from &#39;react&#39;;<br><br>type ScreenSize = &#39;xs&#39; | &#39;sm&#39; | &#39;md&#39; | &#39;lg&#39; | &#39;xl&#39; | &#39;2xl&#39; | &#39;&#39;;<br><br>const breakpoints = [<br>  { min: 1536, label: &quot;2xl&quot; },<br>  { min: 1280, label: &quot;xl&quot; },<br>  { min: 1024, label: &quot;lg&quot; },<br>  { min: 768, label: &quot;md&quot; },<br>  { min: 640, label: &quot;sm&quot; },<br>];<br><br>const useDeviceSize = () =&gt; {<br>  const [width, setWidth] = useState(0);<br>  const [height, setHeight] = useState(0);<br>  const [screenSize, setScreenSize] = useState&lt;ScreenSize&gt;(&#39;&#39;);<br><br>  const handleWindowResize = useEffecEvent(() =&gt; {<br>    // track the sizes<br>    setWidth(window.innerWidth);<br>    setHeight(window.innerHeight);<br><br>    // track breakpoints<br>    const size = breakpoints.find(bp =&gt; window.innerWidth &gt;= bp.min)?.label ?? &quot;xs&quot;;<br>    setScreenSize(size);<br>  });<br><br>  useEffect(() =&gt; {<br>    // add the listener<br>    window.addEventListener(&#39;resize&#39;, handleWindowResize);<br><br>    // call it once<br>    handleWindowResize();<br><br>    // clean-up the listener on unmount<br>    return () =&gt; window.removeEventListener(&#39;resize&#39;, handleWindowResize);<br>  }, []);<br><br>  return { width, height, screenSize };<br>};<br><br>export default useDeviceSize;</pre><p>Thanks for reading.</p><p>If you liked this little digression about if statements, don’t hesititate to leave a clap.</p><p>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b6c1a614d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Inheritance Trap: How to Avoid Fragile Base Classes]]></title>
            <link>https://medium.com/@pixelreverb/the-inheritance-trap-how-to-avoid-fragile-base-classes-deb6a49bb86d?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb6a49bb86d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 10:55:30 GMT</pubDate>
            <atom:updated>2026-03-15T11:03:28.620Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why your deep class hierarchies are breaking your app and how Composition can save it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5CtzhdTtK8tKdZwY" /><figcaption>Photo by <a href="https://unsplash.com/@kazuo513?utm_source=medium&amp;utm_medium=referral">Kazuo ota</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a previous article, we broke down the SOLID principles. In this article, we are going to dive a bit deeper into the considerations regarding inheritance.</p><p>A bold follow-up analogy — we examine closely — is: <br>If SOLID is the foundation, then <strong>Composition Over Inheritance</strong> is the framing of the house. It’s the difference between a building that can be remodeled and one that has to be torn down the moment you want to add a window.</p><p><a href="https://medium.com/@pixelreverb/beyond-the-acronym-when-solid-principles-clash-and-where-they-dont-fit-113e76ebacd8">Beyond the Acronym: When SOLID Principles Clash (and Where They Don’t Fit)</a></p><p>That sounds quite drastic, right?<br>Don’t overreact. Calm down (if you shortly implemented a base class) and let’s take a closer look if everything is really that bad.</p><h3>The “Is-A” Trap</h3><p>In early Computer Science classes, or if you fight your way through guides and tutorials as programming autodidact, we are taught that Object-Oriented Programming (OOP) is about hierarchies.</p><ul><li>A Dog <strong>is a</strong> Mammal.</li><li>A Mammal <strong>is an</strong> Animal.</li></ul><p>This works great in a textbook and, of course, is a very valid approach for starters. But in the real world, requirements change. They always do. Often when you don’t expect it.</p><p>So, what happens when you have a Bird class with a fly() method, and your boss asks you to add a Penguin?</p><p>If you use inheritance, you’re somewhat stuck. You either:</p><ol><li><strong>Override </strong>fly()<strong> to do nothing</strong> (Breaking the Liskov Substitution Principle).</li><li><strong>Throw an Exception</strong> (Crashing the app at runtime).</li><li><strong>Pollute the base class</strong> with canFly flags.</li></ol><h3>The Alternative: The “Has-A” Relationship</h3><p>Composition shifts the focus. Instead of asking what an object <em>is</em>, we ask what it <em>does</em> or what it <em>has</em>.</p><blockquote>Instead of a Bird inheriting flight, a Bird <strong>has</strong> a FlightBehavior.</blockquote><p>Let’s have a look at another example.</p><p>Imagine you are working in the field of robotics and want to share your core logic between different types of robots.</p><p><strong>The Inheritance Way</strong></p><pre>open class Robot {<br>    open fun move() = println(&quot;Walking...&quot;)<br>}<br><br>class CleaningRobot : Robot() {<br>    // Inherits walking, but what if it needs to roll?<br>}</pre><p><strong>The Composition Way</strong></p><p>We define behaviors as interfaces and “plug” them into our classes.</p><pre>interface MovementStrategy {<br>    fun move()<br>}<br><br>class Walking : MovementStrategy {<br>    override fun move() = println(&quot;Walking on legs.&quot;)<br>}<br><br>class Rolling : MovementStrategy {<br>    override fun move() = println(&quot;Rolling on wheels.&quot;)<br>}<br><br>// The Robot &quot;has a&quot; movement strategy<br>class Robot(private val movement: MovementStrategy) {<br>    fun move() = movement.move()<br>}</pre><p>Now, if you want a CleaningRobot that rolls, you don&#39;t change the Robot class. You just pass it a different &quot;part.&quot;</p><blockquote>The implementation above demonstrates a design pattern known as the Strategy Pattern. If you want to learn more, I got you covered and prepared an article about it:</blockquote><p><a href="https://medium.com/@pixelreverb/the-strategy-pattern-replacing-if-else-with-polymorphism-85e9a30f9fd2">The Strategy Pattern — Replacing if else with Polymorphism</a></p><p>Inheritance and Composition are two options that you can choose from. It is important to always keep an eye on (reconsider) what you are building. Having a massive super class is probably as unmaintainable as having a class that inherits twenty interfaces, only because composition makes it “more flexible“.</p><p>And in fact, the world is not just black and white. If your project benefits from it, why shouldn’t it be an option to combine the two?</p><h3>Your Benefits using Composition</h3><h4>Loose Coupling</h4><p>Firstly, by switching from inheritance to composition you achieve loose coupling. Methods that might be inherited but wouldn’t be of any use do not need to be implemented with an empty body anymore — and this leads to cleaner code.</p><p>The Robot doesn&#39;t need to know <em>how</em> Rolling works. It just knows it can call move(). And we all like it when a robot moves, right?</p><h4>Runtime Flexibility</h4><p>Secondly, you achieve an extra layer of runtime flexibility. With inheritance, a Robot is a Robot forever.</p><p>With composition, you could swap a Walking behavior for a Running behavior while the app is actually running.</p><h4>Testability</h4><p>Thirdly, you increase the testability of your code. It is significantly easier to “mock” a small interface like MovementStrategythan it is to mock a massive Parent Class.</p><h3>Kotlin Bonus: Delegation</h3><p>Just because we are using Kotlin in the code examples:</p><p>While the principle is universal, Kotlin developers have a “cheat code” called <strong>Interface Delegation</strong>. It allows you to use composition while making the code look as clean as inheritance.</p><pre>class CombatRobot(movement: MovementStrategy) : MovementStrategy by movement {<br>    // The &#39;by&#39; keyword forwards all MovementStrategy <br>    // calls to the movement object automatically!<br>}</pre><p>This gives you the architectural power of composition with the zero-boilerplate feel of inheritance. Neat, right?</p><h3>Conclusion: When to Use Which?</h3><p>Inheritance isn’t “evil”, but you should consider other options before blindly creating or extending a Super class. Use inheritance only when the relationship is <strong>permanent and total</strong>. For everything else, build your objects like LEGO sets — piece by piece.</p><p>You never gonna know what you create next, and if you have an isolated piece of well-tested logic to reuse in another project without much modification - that is just nice.</p><p><em>If you found this article helpful, feel free to 👏 and follow for more.</em></p><p>See you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb6a49bb86d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Strategy Pattern — Replacing if else with Polymorphism]]></title>
            <link>https://medium.com/@pixelreverb/the-strategy-pattern-replacing-if-else-with-polymorphism-85e9a30f9fd2?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/85e9a30f9fd2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 17:26:57 GMT</pubDate>
            <atom:updated>2026-03-15T11:04:01.299Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Classic design pattern. Modern code. Practical context.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fuZK-F7wunbFp6LK" /><figcaption>Photo by <a href="https://unsplash.com/@kaleidico?utm_source=medium&amp;utm_medium=referral">Kaleidico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I think most of us developers agree: It is difficult — if not impossible — to predict the complexity of a new project right from the beginning. Requirements change, technology evolves, you always need a plan B.</p><p>But how to manage requirement changes efficiently? In this article, we will take a look at the <em>Strategy Pattern</em> — what it is, when it is a good choice and when not (just because a pattern exists doesn’t mean it is always an appropriate choice).</p><p>Let’s start with a simplified use case we can built our little story on:</p><h3>1. A Problem You’ve Definitely Seen Before</h3><p>Sooner or later, many codebases end up with logic that looks like this:</p><pre>fun calculatePrice(type: PricingType, price: BigDecimal): BigDecimal {<br>  return when (type) {<br>    PricingType.REGULAR -&gt; price<br>    PricingType.DISCOUNT -&gt; price * BigDecimal(&quot;0.9&quot;)<br>    PricingType.PREMIUM -&gt; price * BigDecimal(&quot;1.2&quot;)<br>  }<br>}</pre><p>At first glance, this looks reasonable:</p><ul><li>The logic is easy to follow</li><li>All behavior is in one place</li><li>Adding a new case feels trivial</li></ul><p>So what’s the problem?</p><p>The problem is not <em>what the code looks like today</em> — it’s what happens <strong>after the fifth or sixth change</strong>.</p><h3>2. The Naive Evolution</h3><p>You know it: Requirements change. They always do.</p><ul><li>Marketing introduces a new pricing model</li><li>A/B tests require temporary pricing logic</li><li>One customer gets a special case</li></ul><p>Your when/if/switch blocks grow. Your tests multiply. Your confidence drops.</p><p>Every new condition requires modifying existing logic. The function becomes a hotspot for merge conflicts and regressions.</p><p>This is a classic violation of the <strong>Open/Closed Principle</strong>:</p><blockquote><em>Software entities should be open for extension, but closed for modification.</em></blockquote><p><a href="https://medium.com/@pixelreverb/beyond-the-acronym-when-solid-principles-clash-and-where-they-dont-fit-113e76ebacd8">Beyond the Acronym: When SOLID Principles Clash (and Where They Don’t Fit)</a></p><p>And this is exactly the kind of problem the <strong>Strategy Pattern</strong> was designed to solve.</p><h3>3. The Core Idea of the Strategy Pattern</h3><p>The Strategy Pattern is conceptually simple:</p><blockquote><em>Define a family of algorithms, encapsulate each one, and make them interchangeable.</em></blockquote><p>Instead of encoding behavior in conditional logic, we:</p><ul><li>Define a common interface</li><li>Implement each behavior separately</li><li>Inject the behavior where it’s needed</li></ul><p>A simplified mental model:</p><pre>Context ──▶ Strategy<br>               ▲<br>        ┌──────┼────────┐<br>        │      │        │<br>  StrategyA StrategyB StrategyC</pre><p>The <strong>context</strong> doesn’t care <em>which</em> strategy it uses — only that it conforms to the expected contract.</p><h3>4. A Basic Strategy Implementation</h3><p>Let’s refactor the pricing example using the Strategy Pattern.</p><h4>The Strategy Interface</h4><pre>interface PricingStrategy {<br>  fun calculate(price: BigDecimal): BigDecimal<br>}</pre><h4>Concrete Strategies</h4><pre>class RegularPricing : PricingStrategy {<br>  override fun calculate(price: BigDecimal) = price<br>}<br><br>class DiscountPricing : PricingStrategy {<br>  override fun calculate(price: BigDecimal) = price * BigDecimal(&quot;0.9&quot;)<br>}<br><br>class PremiumPricing : PricingStrategy {<br>  override fun calculate(price: BigDecimal) = price * BigDecimal(&quot;1.2&quot;)<br>}</pre><h4>The Context</h4><pre>class PriceCalculator(<br>  private val pricingStrategy: PricingStrategy<br>) {<br>  fun finalPrice(price: BigDecimal): BigDecimal = pricingStrategy.calculate(price)<br>}</pre><h4>Usage</h4><pre>val calculator = PriceCalculator(DiscountPricing())<br>val result = calculator.finalPrice(BigDecimal(&quot;100&quot;))</pre><p>No conditionals. No branching logic. Just behavior selection.</p><h3>5. Language Features vs Design Patterns</h3><p>Some languages offer features — like higher-order functions or lambdas — that can <em>replace</em> simple Strategy implementations.</p><p>That can be useful.</p><p>However, this article deliberately focuses on <strong>the pattern itself</strong>, not on promoting a specific language or feature set.</p><p>The important takeaway is this:</p><blockquote><em>The Strategy Pattern is about </em>separating behavior<em>, not about how concise the syntax is.</em></blockquote><p>Even if the syntax changes, the underlying design problem — and solution — remains the same.</p><h3>6. The Strategy Pattern Helps with Scaling</h3><p>With the Strategy Pattern:</p><ul><li>New behavior = new class — an encapsulated piece of logic</li><li>Existing code remains untouched</li><li>Each strategy can be tested independently</li><li>Behavior is explicit and named</li></ul><p>This becomes especially valuable when:</p><ul><li>Strategies grow more complex</li><li>Behavior depends on external systems</li><li>Different teams own different strategies</li></ul><h3>7. Common Misuses of the Strategy Pattern</h3><p>Now you (re)learned about the Strategy pattern and are full of excitement, but like with all patterns, also the Strategy pattern can be overused.</p><h4>Strategy Explosion</h4><p>Creating a new strategy for trivial variations that don’t justify abstraction.</p><h4>Premature Abstraction</h4><p>Replacing a simple if with three interfaces and six classes <em>before</em> complexity exists.</p><h4>Hidden Selection Logic</h4><p>Moving the conditional logic somewhere else instead of eliminating it.</p><blockquote><strong>Patterns are tools — not goals.</strong></blockquote><h3>8. When Not to Use the Strategy Pattern</h3><p>So, to avoid overuse of the Strategy we also need to think about when it makes sense to just not hop onto the Strategy train — and that is when:</p><ul><li>There is only one stable behavior</li><li>The logic is unlikely to change</li><li>The abstraction adds more cognitive load than value</li></ul><p>Sometimes, a simple conditional really <em>is</em> the best solution.</p><h3>9. Closing Thoughts</h3><p>The Strategy Pattern isn’t about clever code. It’s about <strong>making change easier</strong>. If your system frequently needs to vary behavior — and that variation keeps leaking into conditionals — Strategy is often the cleanest way out.</p><p>Do you use the Strategy Pattern intentionally, or do you have a different approach? Let us know in the comments.</p><p>In the next article, we’ll look at <strong>Factory vs Builder</strong> — two patterns that are often confused, misused, or combined without clear intent.</p><p><em>If you found this article helpful, feel free to 👏 and follow for more.</em></p><p>See you next time.</p><p><em>Series: Design Patterns, Revisited</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e9a30f9fd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Acronym: When SOLID Principles Clash (and Where They Don’t Fit)]]></title>
            <link>https://medium.com/@pixelreverb/beyond-the-acronym-when-solid-principles-clash-and-where-they-dont-fit-113e76ebacd8?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/113e76ebacd8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[fundamentals]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-principles]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 20:59:26 GMT</pubDate>
            <atom:updated>2026-01-27T20:59:26.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2UQukfQ85SNA9LWb" /><figcaption>Photo by <a href="https://unsplash.com/@scottwebb?utm_source=medium&amp;utm_medium=referral">Scott Webb</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A truly famous acronym — <strong>SOLID</strong> — and you’ve probably heard of it before. In this article, we revisit which principles are hidden behind the acronym. And, we also check whether it is technically possible ( and a good idea ) to implement it fully.</p><h3>The SOLID Breakdown</h3><p>SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable.</p><ul><li><strong>S</strong> - Single Responsibility Principle (SRP)</li></ul><p>A class should have one, and only one, reason to change. It shouldn’t be a “Swiss Army Knife” that handles everything. Database logic, UI rendering, and data validation — each should have a place on its own.</p><ul><li><strong>O</strong> - Open/Closed Principle (OCP)</li></ul><p>Software entities should be open for extension but closed for modification. The goal is to be able to add new functionality without touching existing code.</p><ul><li><strong>L -</strong> Liskov Substitution Principle (LSP)</li></ul><p>Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.</p><ul><li><strong>I -</strong> Interface Segregation Principle (ISP)</li></ul><p>No client should be forced to depend on methods it does not use. Better to have many small, specific interfaces than one large, general one.</p><ul><li><strong>D -</strong> Dependency Inversion Principle (DIP)</li></ul><p>High-level modules should not depend on low-level modules; both should depend on abstractions.</p><h4>Need Some Examples?</h4><p>Maybe you haven’t heard of the principles before, or need a quick refresh. Just in case, let’s take a look at some code snippets explaining each principle briefly:</p><h4><strong>Single Responsibility Principle (SRP)</strong></h4><p><strong>The Problem: </strong>A class that handles both data logic and reporting logic.</p><pre>// ❌ Bad: One class handles data and formatting<br>class Invoice(val amount: Double) {<br>    fun saveToDatabase() { /* DB logic */ }<br>    fun generatePDF() { /* PDF logic */ }<br>}</pre><p><strong>The Solution:</strong> Separate the concerns and encapsulate the logic.</p><pre>// ✅ Good: Responsibilities are split<br>class Invoice(val amount: Double)<br>class InvoiceRepository { fun save(invoice: Invoice) { /* ... */ } }<br>class InvoiceReporter { fun generatePDF(invoice: Invoice) { /* ... */ } }</pre><h4><strong>Open/Closed Principle (OCP)</strong></h4><p><strong>The Problem: </strong>Using when/switch/if blocks that you have to modify every time you add a new type.</p><pre>// ❌ Bad: Must modify this class to add a new shape<br>class AreaCalculator {<br>    fun calculate(shape: Any): Double = when(shape) {<br>        is Rectangle -&gt; shape.width * shape.height<br>        is Circle -&gt; 3.14 * shape.radius * shape.radius<br>        else -&gt; 0.0<br>    }<br>}</pre><p><strong>The Solution:</strong> Use polymorphism. The calculator is now “closed” to modification but “open” to new shapes.</p><pre>// ✅ Good: Just add a new class implementing Shape<br>interface Shape { fun area(): Double }<br><br>class Rectangle(val w: Double, val h: Double) : Shape {<br>    override fun area() = w * h<br>}<br><br>class AreaCalculator {<br>    fun calculate(shape: Shape) = shape.area()<br>}</pre><h4><strong>L: Liskov Substitution Principle (LSP)</strong></h4><p><strong>The Problem:</strong> A subclass that breaks the behavior of the parent (the “Classic Bird” trap).</p><pre>open class Bird {<br>    open fun fly() = println(&quot;Flying...&quot;)<br>}<br><br>// ❌ Bad: Ostrich is a Bird but it can&#39;t fly. <br>// This will crash code that expects all birds to fly.<br>class Ostrich : Bird() {<br>    override fun fly() = throw UnsupportedOperationException()<br>}</pre><p><strong>The Fix:</strong> Don’t force behaviors that don’t apply to all subclasses.</p><pre>open class Bird<br>open class FlyingBird : Bird() { fun fly() { /* ... */ } }<br><br>class Ostrich : Bird() // No fly method, no problem.</pre><h4>I: Interface Segregation Principle (ISP)</h4><p><strong>The Problem:</strong> A “fat” interface that forces classes to implement things they don’t need.</p><pre>interface Worker {<br>    fun work()<br>    fun eat()<br>}<br><br>// ❌ Bad: Robot doesn&#39;t eat, but must implement it.<br>class Robot : Worker {<br>    override fun work() = println(&quot;Working&quot;)<br>    override fun eat() = Unit // Empty/Useless<br>}</pre><p><strong>The Fix:</strong> Break interfaces into smaller pieces.</p><pre>interface Workable { fun work() }<br>interface Feedable { fun eat() }<br><br>class Robot : Workable { override fun work() = println(&quot;Working&quot;) }</pre><h4>D: Dependency Inversion Principle (DIP)</h4><p><strong>The Problem:</strong> High-level logic depends on a specific, low-level implementation.</p><pre>// ❌ Bad: Database is &quot;hardcoded&quot; inside the service<br>class UserLogic {<br>    private val db = SQLDatabase()  // Tight coupling<br>    fun save() = db.save()<br>}</pre><p><strong>The Fix:</strong> Depend on an abstraction (Interface).</p><pre>interface Storage { fun save() }<br><br>class SQLDatabase : Storage {<br>    override fun save() { /* SQL specific save logic goes here */ }<br>}<br><br>// ✅ Good: UserLogic doesn&#39;t care if it&#39;s SQL, NoSQL, or Mock<br>class UserLogic(private val storage: Storage) {<br>    fun save() = storage.save()<br>}<br><br>val userLogic = UserLogic(SQLDatabase())</pre><h3>Where the Principles Clash</h3><p>While they are meant to work together, in the real world, these principles often pull in opposite directions.</p><h4>SRP vs. ISP</h4><p>Sometimes, following the <strong>Interface Segregation Principle</strong> strictly leads to a massive explosion of tiny interfaces. If you apply <strong>Single Responsibility</strong> to those interfaces, you might end up with a fragmented codebase where finding where the “actual work” happens becomes a scavenger hunt.</p><h4>OCP vs. Simplicity (YAGNI)</h4><p>The <strong>Open/Closed Principle</strong> often requires introducing interfaces or abstract classes to allow for future extension. However, this can conflict with the “You Ain’t Gonna Need It” (YAGNI) philosophy. Over-applying OCP leads to “AbstractFactoryProvider” syndrome — where the code is so “open for extension” that it’s impossible to read.</p><h4>LSP vs. Real-World Logic</h4><p>The classic example is the Square-Rectangle problem. In math, a square is a rectangle. In code, if Square inherits from Rectangle, setting a width might unexpectedly change the height, breaking the expectations of the calling code.</p><h3>The Friction: Granularity vs. Cohesion</h3><p>The conflict between the <strong>Single Responsibility Principle (SRP)</strong> and the <strong>Interface Segregation Principle (ISP)</strong> usually boils down to one question: <em>How small is too small?</em></p><ul><li><strong>ISP</strong> pushes you to split interfaces so clients aren’t forced to depend on methods they don’t use.</li><li><strong>SRP</strong> pushes you to ensure a class has only one reason to change.</li></ul><p>The “clash” happens when you follow ISP to its logical conclusion. You end up with a “fragmented” codebase where a single business process is scattered across dozens of tiny interfaces and implementation classes, making the system’s flow nearly impossible to trace.</p><h3>Code Example: The “Smart Printer” Dilemma</h3><p>Imagine we are building software for a multi-function printer.</p><h4>1. The “Fat” Interface (Violating ISP)</h4><p>Initially, we might create a single interface. But a BasicPrinter doesn&#39;t know how to fax, yet it&#39;s forced to provide an implementation.</p><pre>interface SmartDevice {<br>    fun print(doc: String)<br>    fun scan(doc: String)<br>    fun fax(doc: String)<br>}<br><br>class BasicPrinter : SmartDevice {<br>    override fun print(doc: String) = println(&quot;Printing: $doc&quot;)<br>    override fun scan(doc: String) = <br>              throw UnsupportedOperationException(&quot;Can&#39;t scan!&quot;)<br>    override fun fax(doc: String) = <br>              throw UnsupportedOperationException(&quot;Can&#39;t fax!&quot;)<br>}</pre><h4>2. The ISP Fix (Splitting the Interfaces)</h4><p>To fix this, we follow ISP and split the interfaces. Now, the BasicPrinter only implements what it actually does.</p><pre>interface Printer { fun print(doc: String) }<br>interface Scanner { fun scan(doc: String) }<br>interface FaxMachine { fun fax(doc: String) }<br><br>class BasicPrinter : Printer {<br>    override fun print(doc: String) = println(&quot;Printing: $doc&quot;)<br>}</pre><h4>3. The Clash: SRP vs. Implementation</h4><p>Now, consider a HighEndOfficeMachine. It <em>can</em> do all three. If we create one class that implements all three interfaces, we might be violating SRP because that class now has three different reasons to change (printing logic changes, scanning firmware updates, or fax protocols shift).</p><p><strong>The “Strict SRP” approach leads to fragmentation:</strong> To satisfy SRP perfectly, you’d have to create three separate classes and “compose” them.</p><pre>// Now we have 3 interfaces AND 3 classes for one physical machine<br>class PhotoPrinter : Printer { ... }<br>class OpticalScanner : Scanner { ... }<br>class LegacyFax : FaxMachine { ... }<br><br>class HighEndOfficeMachine(<br>    private val printer: Printer,<br>    private val scanner: Scanner,<br>    private val fax: FaxMachine<br>) : Printer by printer, Scanner by scanner, FaxMachine by fax <br>// Kotlin&#39;s &#39;by&#39; keyword helps, but the architectural overhead is high.</pre><blockquote>The Takeaway: The clash is real!</blockquote><ol><li><strong>Strict ISP</strong> leads to “Interface Explosion.”</li><li><strong>Strict SRP</strong> leads to “Class Fragmentation.”</li></ol><p>As a developer, you have to decide where the “sweet spot” of complexity lies. In a small project, the “Fat Interface” might actually be easier to maintain than a web of tiny, delegated classes.</p><h3>Language Fit: Is SOLID Always the Answer?</h3><p>SOLID was born in the era of <strong>Strictly Typed Object-Oriented Programming</strong>. Applying it everywhere can sometimes be a “square peg, round hole” situation.</p><h3>Languages that Profit Highly</h3><ul><li><strong>Kotlin &amp; Java:</strong> Built for these principles. Kotlin’s interface and sealed class features make implementing OCP and DIP very natural.</li><li><strong>C# / Swift:</strong> Similar to Kotlin, these languages rely heavily on protocols/interfaces to manage large-scale app complexity.</li></ul><h3>Languages Where SOLID is “Different”</h3><ul><li><strong>Functional Languages (Haskell, Elixir, Clojure):</strong> These languages don’t use classes. While the <em>ideas</em> (like decoupling) exist, trying to apply “Interface Segregation” in a language without interfaces is confusing. They use different patterns like Higher-Order Functions.</li><li><strong>JavaScript/Python:</strong> Because these are dynamically typed, the <strong>Dependency Inversion Principle</strong> feels different. You don’t always need an explicit interface to swap out a dependency—you just pass a different object. Over-engineering SOLID in JS can lead to unnecessary boilerplate.</li><li><strong>Go (Golang):</strong> Go uses “implicit” interfaces. It naturally favors ISP (Interface Segregation) because interfaces are defined by the consumer, not the producer.</li></ul><p><strong>What’s your “SOLID nightmare” story?</strong></p><p>We’ve all been there — trying to follow the Open/Closed Principle so strictly that we ended up with a dozen interfaces for a single feature. Which of these principles do you find the hardest to balance in your daily work? Drop a comment below and let’s discuss!</p><p><em>If you found this guide helpful, feel free to 👏 and follow for more.</em></p><p>See you in the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113e76ebacd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proof-of-Concept: Crafting a TCP Broker for Mirth Connect]]></title>
            <link>https://medium.com/@pixelreverb/proof-of-concept-crafting-a-tcp-broker-for-mirth-connect-1ebd1537ef8f?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ebd1537ef8f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[health-data]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[mirth-connect]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 16:42:06 GMT</pubDate>
            <atom:updated>2025-07-22T16:42:06.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cr2V-bkGvXE2P9bt" /><figcaption>Photo by <a href="https://unsplash.com/@tvick?utm_source=medium&amp;utm_medium=referral">Taylor Vick</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, I started working with Mirth Connect and was confronted with a situation where I had to do quite some research before I coming up with a possible solution.</p><p>If you are working in the IT health sector you have probably heard of Mirth Connect before. For those who don’t know it: Mirth Connect is a versatile software solution that helps converting and manipulating messages and/or files while they are transmitted from one location to another.</p><p>Throughout the article I assume that you are somewhat familiar with Mirth Connect and the related terminology. I’ll try my best to explain everything as general as possible, but if you start to feel lost while reading the article, I’d like to encourage you to inform yourself a little bit more about Mirth Connect and then return here.</p><h3>TL;DR</h3><p>The task is to create a solution that allows bidirectional communication with multiple channels in Mirth Connect for a TCP client that is only able to open a single port for sending and receiving messages. As the default setup of Mirth Connect is not able to handle this scenario, one needs to add an additional communication layer between the TCP client and Mirth Connect — namely, a TCP connection broker in combination with a message queue (RabbitMQ in this case).</p><h3>GitHub Repo</h3><p>Of course, I prepared a repository if you want to dive deeper into this topic. You can have a look at the repository <a href="https://github.com/pixelreverb/mirth-connect-tcp-broker">here</a> to see the solution described in this article.</p><h3>Share your thoughts</h3><p>If you have faced a similar situation, I’m eager to hear how you approached it and with which solution you came up with. This is the story of one possible proof-of-concept approach and I am sure there are multiple ways to solve it. Please, let me (and other interested people) know in the comments if you made any experience, and are willing to share it.</p><h3>Overview</h3><p>As the article will cover quite some content, I am going to divide it into two major sections:</p><ol><li>The Problem Description</li><li>The Proof-of-Concept Description</li></ol><p>The second part will also contain parts of the problem description, although in a more condensed way. Feel free to directly jump to the second part if you are more interested in the technical stuff.</p><p>Ready? Okay, let’s start.</p><h3>The Problem Description</h3><p>Imagine the following situation:</p><p>You have a client that needs to communicate with another system via a TCP connection. The client and the target system do not speak the same protocol. Also, the client is restricted to operate in <em>client mode</em> and can open only a single port to communicate with external systems. To solve the message transformation issue, you decide to introduce Mirth Connect because you have to deal with health message formats (e.g. HL7 ) anyway.</p><p>A high-level view then looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOEkmhz-GEBhbacqAEGxkw.jpeg" /><figcaption>We want bidirectional communication via TCP connections</figcaption></figure><h4>What is possible</h4><p>To create a simple setup using TCP channels is actually very doable with the functionality that comes built-in with Mirth Connect. You can create a communication channel in Mirth Connect that has a TCP listener as source connector and a TCP sender as destination connector. The listener then is set to <em>server mode</em> for clients to be able to connect to it, and the destination connector is put into <em>client mode</em> to establish a connection to the target endpoint.</p><p>With this setup the client is able to establish a connection to Mirth Connect’s TCP Listener connector and send its message. While Mirth Connect processes the message, it might be altered through various filters and transformers before it finally is forwarded to the target endpoint by the destination connector.</p><p>Now, the destination connector has to keep the connection open to the target until it returns a response message. The response travels the communication chain in reverse such that it is received by the connected client.</p><p>In a diagram it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSdXqvBRWiXfwS5QtSnPeA.jpeg" /><figcaption>TCP communication via a single channel in Mirth Connect</figcaption></figure><h4>What is not possible</h4><p>So far, so good. Now, it starts to be interesting.</p><p>We extend our scenario. The target endpoint now also wants to communicate to the connected client without receiving a previous message from it. That means the target endpoint becomes the initiator of the communication flow.</p><p>And this is (already) the point where we need to think about more complex solutions because this scenario cannot be realized with Mirth Connect anymore. (Correct me if I&#39;m wrong, please.)</p><p>Have a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oi-tG7lM6EaqrXnXSdj8Jw.jpeg" /><figcaption>We also want a second channel communicate with the client</figcaption></figure><p>As the client runs the TCP connection in <em>client mode</em> and can only open <em>a single port </em>for communication, neither Mirth Connect nor the client itself can establish additional connections to receive messages from multiple channels.</p><p>Because the client needs to operate through Channel A, it keeps the connection open. In that case there is no chance for Channel B to connect to the client because the port is blocked. And even if the client is not connected to Channel A, Channel B would not be able to establish a connection because the client runs in <em>client mode</em>; meaning that the client is initiator of the connection.</p><h4>How to solve it</h4><p>“And now what?”, you may ask.</p><p>Well, to make this work we introduce one more communication layer. This layer consists of two major components:</p><ul><li>A connection broker that manages client connections</li><li>A message queue which is filled with messages from the broker and Mirth Connect then reads this queue for new messages</li></ul><p>Good news first: There exist well-known message queue software solutions and we don’t need to built a system on our own.</p><p>The bad news: We have to implement the TCP broker ourselves because that’s something that is not largely available.<br>(Okay, okay — from a programmer’s point of view it is not bad news because it’s fun to built, but from a managers perspective that has to secure highly sensible health data a battle-tested solution might be favored.)</p><p>So, if we add a TCP broker and a message queue (RabbitMQ in this case), our setup becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj8rViPK2yz6WHKLHMHH6w.jpeg" /><figcaption>One way to enable bidirectional communication</figcaption></figure><p>Now, we have an architecture that we can play around with. Let’s see how it can be set up, and how it works.</p><h3>The Proof-of-Concept Description</h3><p>For those that directly jumped to this section, let’s summarize what we encountered so far:</p><p>When a TCP client that can open only a single port for communication establishes a connection to a Mirth Connect channel that uses a connector of type <em>TCP Listener</em> as its source in <em>server mode</em>, this port is blocked on client-side for any further communication. Although, multiple clients can connect to the channel, for the clients it is only possible to send messages and receive responses through/from that specific channel.</p><p>When a different process wants to send data to one of the connected clients it is not possible. <br>Firstly, because the port is blocked by the already established connection. Secondly, because the clients are the ones that take action and establish connections, and it is not possible to connect client-to-client in a TCP context.</p><p>To overcome this limitation we use multiple communication layers.</p><h4>Tell me how it works</h4><blockquote>The current state is more like a proof-of-concept, requires some configuration and needs a certain setup, but eventually might be an interesting approach. It is definitely not production-ready, but can serve as a starting point.</blockquote><p>Before you read ahead, I suggest you take a look at the <a href="https://github.com/pixelreverb/mirth-connect-tcp-broker">GitHub repo</a>, or open it on a second screen to follow along.</p><p>In general the setup consits of four components:</p><ol><li>Mirth Connect — for message transformation</li><li>RabbitMQ — as message queue</li><li>TCP connection broker script — session management<br>(I used JavaScript here)</li><li>Redis — TCP session storage</li></ol><h4><strong>The Flow</strong></h4><p>To begin with we take a look on how a message travels through the communication chain:</p><ul><li>A client connects to the TCP server created by the broker script</li><li>Upon connection the broker script creates a session and stores it in the Redis database</li><li>Once the connection is established the client can send messages</li><li>RabbitMQ is configured with two queues — one for incoming and one for outgoing messages</li><li>When the borker forwards a messages to RabbitMQ’s inbound queue , it is enveloped with additional meta data like session id, client ip and client port</li><li>In Mirth Connect we configure two seprate channels to enable a communiction with RabbitMQ <br>(to replicate the setup in the last diagram above, we actually have to configure three channels)</li><li>One channel is polling the queue of incoming messages in a fixed interval</li><li>If the polling returns a new message, the channel is going to process it; filters and transformations are applied, then the message is forwarded to the target endpoint by the destination connector</li><li>The destination connector keeps the connection to the target endpoint open until it receives a response, which is routed to the second channel</li><li>The second channel is responsible for sending messages to the response queue configured in RabbitMQ; sort of a general interface to forward messages this way</li><li>But before the response is sent to the second channel, it is wrapped with the meta data from the incoming message; this information is only available in channel one and it is required to ensure that the correct client will receive it</li><li>The second channel fulfills its purpose and just writes the received data to the response queue in RabbitMQ</li><li>The broker script follows a similar pattern and listens for any new messages in the response queue</li><li>If there is one, it fetches the message and tries to get the correct socket connection identified by the meta data; it then writes the payload to it</li><li>The client receives a message on the same port it sent the data</li></ul><p>This is a rather detailed description of what is going, but I hope that everything is clear so far.</p><p>To quickly come back to the channels we need for the setup in the last diagram:</p><ul><li>Channel One — Constantly polling RabbitMQ’s queue for incoming messages</li><li>Channel Two — Sending data to RabbitMQ’s queue for response messages</li><li>Channel Three — Handling messages initiated through the target endpoint, forwarding it to Channel Two for delivery</li></ul><p>That’s the basic setup, although it has one major problem we didn’t address yet. Do you see it? — I will come back to it at the end of the article when we take a look at the requirements and improvements.</p><h4><strong>Setting it up</strong></h4><blockquote>To make it easier to follow along, I’m going to show important scripts below. But to not extend this article unecessarily, I’m not going to dive into too much detail on how to configure each software part itself.</blockquote><p>To make the setup as easy as possible it comes through a Docker compose file.</p><p>The Docker compose file takes care of most of the setup configuration.</p><h4>Required software</h4><p>Before setting this up make sure that you installed</p><ul><li>Docker and Docker Compose</li><li>Node.js and npm</li></ul><h4>Installing dependencies</h4><p>Once you checked out the repo, navigate to the folder tcp-broker and run</p><pre>npm install</pre><p>to install the required dependecies for the TCP broker script.</p><h4>Starting the containers</h4><p>Next you are ready to build the containers. On the first run use:</p><pre>docker compose up --build</pre><p>On following starts omit the -build flag.</p><p>If you want to stop the whole setup, use:</p><pre>docker compose stop</pre><blockquote>Don’t run docker compose down to stop the containers as it removes them. And in that case Mirth Connect is reset and starts anew without any configuration or channels.</blockquote><p>If everything went well you should see four running containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgB28IpCeTnwjOvbX8_O0Q.png" /><figcaption>A view of Docker Desktop</figcaption></figure><h4><strong>RabbitMQ</strong></h4><p>Once all containers are running, you can access RabbitMQ’s web interface at http://localhost:15672.</p><p>After a succesfull login (credentials are in the docker-compose.yml), select the <em>Queues and Streams</em> tab and create the two queues:</p><ul><li>msg_inbound</li><li>msg_response</li></ul><blockquote>Of course, you can name them like you want. Just remember to update the scripts accordingly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*la_YhQEhc5iLsZi69cgs6g.png" /><figcaption>RabbitMQ Queues</figcaption></figure><h4><strong>Mirth Connect</strong></h4><p>The Mirth Connect instance requires a little bit more setup to work with the above-mentioned workflow.</p><p>First, we need to have the AMQP client jar in place to be able to establish a connection to RabbitMQ. It needs to be placed in the <strong>`</strong>custom-lib<strong>`</strong> folder before the Mirth Connect container starts.</p><p>But don’t worry. This already done if you checked out the repository.</p><p><strong>Global Scripts</strong><br>To make RabbitMQ available in Mirth Connect accross channels, we need to define it in global scope. That is we want to initiate a connection to RabbitMQ when channels are deployed and closed when they are undeployed.</p><p>In Mirth Connect if you select Channels you get the option to select Edit Global Scripts .</p><p><strong>Global Scripts : Deploy</strong></p><pre>var ConnectionFactory = Packages.com.rabbitmq.client.ConnectionFactory;<br>var DefaultConsumer = Packages.com.rabbitmq.client.DefaultConsumer;<br>var Envelope = Packages.com.rabbitmq.client.Envelope;<br>var Channel = Packages.com.rabbitmq.client.Channel;<br>var DeliverCallback = Packages.com.rabbitmq.client.DeliverCallback;<br>var CancelCallback = Packages.com.rabbitmq.client.CancelCallback;<br>var LinkedBlockingQueue = Packages.java.util.concurrent.LinkedBlockingQueue;<br><br>// Create factory with auto-recovery enabled<br>var factory = new ConnectionFactory();<br>factory.setHost(&quot;rabbitmq&quot;);<br>factory.setUsername(&quot;mirth&quot;);<br>factory.setPassword(&quot;mirth&quot;);<br>factory.setAutomaticRecoveryEnabled(true);<br>factory.setNetworkRecoveryInterval(5000); // in ms<br><br>// Create shared connection and channel<br>var connection = factory.newConnection();<br>var channel = connection.createChannel();<br><br>// Declare queue (optional if already declared)<br>var queueName = &quot;msg_inbound&quot;;<br>channel.queueDeclare(queueName, true, false, false, null);<br><br>// Create a thread-safe queue to store incoming messages<br>var messageQueue = new LinkedBlockingQueue();<br><br>// Define the consumer using a DeliverCallback<br>var deliverCallback = new DeliverCallback({<br>  handle: function (consumerTag, delivery) {<br>    var message = new java.lang.String(delivery.getBody(), &quot;UTF-8&quot;);<br>    messageQueue.offer(message); // store in queue<br>   },<br>});<br><br>var cancelCallback = new CancelCallback({<br>  handle: function (consumerTag) {<br>    logger.warn(&quot;Consumer was cancelled: &quot; + consumerTag);<br>  },<br>});<br><br>// Start consuming (autoAck = true for simplicity; change to false if manual ack needed)<br>channel.basicConsume(queueName, true, deliverCallback, cancelCallback);<br><br>// Store objects globally<br>globalMap.put(&quot;rabbitConnection&quot;, connection);<br>globalMap.put(&quot;rabbitChannel&quot;, channel);<br>globalMap.put(&quot;rabbitQueue&quot;, messageQueue);</pre><p>We use a ConnectionFactory with auto-recovery because it might be that RabbitMQ is not available for some time. Maybe you need to restart the container, it crashed or something else. It could even be as simple as that the Mirth Connect container starts faster than RabbitMQ’s. Therefore, we need to take care of trying to reconnect.</p><p><strong>Global Scripts : Undeploy</strong></p><pre>// Close channel<br>try {<br>  var channel = globalMap.get(&quot;rabbitChannel&quot;);<br>  if (channel != null &amp;&amp; channel.isOpen()) {<br>    channel.close();<br>  }<br>} catch (e) {<br>  logger.error(&quot;Error closing RabbitMQ channel: &quot; + e);<br>}<br><br>// Close connection<br>try {<br>  var conn = globalMap.get(&quot;rabbitConnection&quot;);<br>  if (conn != null &amp;&amp; conn.isOpen()) {<br>    conn.close();<br>  }<br>} catch (e) {<br>  logger.error(&quot;Error closing RabbitMQ connection: &quot; + e);<br>}</pre><p><strong>Channel One : Handling Inbound Messages</strong><br>With the global scripts defined, we can configure the first channel. This channel will basically perform three tasks:</p><ol><li>Poll messageQueue for new messages (source)</li><li>Extract the payload from the message and store the meta data for later use using a transformer (source)</li><li>Send the payload to the target endpoint, await its response and process it in a transformer, then route to the second channel (destination)</li></ol><p>Pay a little attention to the script here because parts of it depend on how you named your channels.</p><p><strong><em>Source Connector</em></strong></p><p>Type: JavaScriptReader<br>Interval: 1 seconds<br>Script:</p><pre>var messageQueue = globalMap.get(&quot;rabbitQueue&quot;);<br><br>if (messageQueue != null) {<br>  var message = messageQueue.poll(); // non-blocking fetch<br>  <br>  if (message != null) {<br>    logger.info(&quot;Received from RabbitMQ: &quot; + message);<br>    return message;<br>  } else {<br>    return null; // No message available<br>  }<br><br>} else {<br>  logger.error(&quot;RabbitMQ message queue is not initialized.&quot;);<br>  return null;<br>}</pre><p><strong><em>Source Transformer</em></strong></p><p>Type: JavaScriptReader <br>Script:</p><pre>var _msg = JSON.parse(connectorMessage.getRawData());<br>var conn_id = _msg.connection_id;<br>var ip = _msg.client_ip;<br>var port = _msg.client_port;<br>var payload = _msg.payload;<br><br>logger.info(&quot;Reveiced [&quot; + conn_id + &quot;:&quot; + ip + &quot;:&quot; + port + &quot;] &quot; + payload);<br><br>channelMap.put(&quot;connection_id&quot;, conn_id);<br>channelMap.put(&quot;client_ip&quot;, ip);<br>channelMap.put(&quot;client_port&quot;, port);<br><br>// Return just the payload for TCP Sender<br>return payload;</pre><p><strong><em>Destination Connector</em></strong></p><p>Type: TCP Sender<strong><br></strong> Destination name: “TCP Sender” (<em>&gt;&gt; the script refers to the name</em>)<br>Mode: <em>Client<br></em>Validate Response: <em>No<br></em> Enter connection details.</p><p><strong><em>Destination Response Transformer</em></strong></p><p>Type: JavaScriptReader <br>Script:</p><pre>// wrap the response message with meta data previously stored <br>// in the channel map<br>var messageToSend = JSON.stringify({<br>  connection_id: $(&quot;connection_id&quot;),<br>  client_ip: $(&quot;client_ip&quot;),<br>  client_port: $(&quot;client_port&quot;),<br>  payload: msg,<br>});<br><br>// first argument is the Mirth Connect channel name<br>router.routeMessage(&quot;RabbitMQ Outbound&quot;, messageToSend);</pre><p><strong>Channel Two : Publishing Messages</strong><br>The second channels responsibility solely is to publish any received data to RabbitMQ’s response message queue.</p><p><strong>Source</strong></p><p>Type: Channel Reader <br>No more configuration needed.</p><p><strong>Destination</strong></p><p>Type: JavaScript Writer<br> Script:</p><pre>var messageJson = JSON.parse(connectorMessage.getRawData());<br><br>// Convert to Java string and bytes<br>var javaMessage = new java.lang.String(JSON.stringify(messageJson));<br>var messageBytes = javaMessage.getBytes(&quot;UTF-8&quot;);<br><br>// Get RabbitMQ channel from global context<br>var channel = globalMap.get(&quot;rabbitChannel&quot;);<br>var outQueue = &quot;msg_response&quot;;<br><br>// Declare queue (optional)<br>channel.queueDeclare(outQueue, true, false, false, null);<br><br>// Publish to queue<br>channel.basicPublish(&quot;&quot;, outQueue, null, messageBytes);<br>logger.info(&quot;Published response to RabbitMQ: &quot; + javaMessage);</pre><h4><strong>Test Scripts</strong></h4><p>The repository includes two JS scripts for local testing. There is a client script that connects to the TCP broker and server script that can serve as target endpoint.</p><p>To use them navigate to the directory and run</p><pre>npm install</pre><p>to install the dependencies.</p><p>After that you can start the client and the server script by executing</p><pre>npm run client<br>npm run server</pre><h3><strong>Final Thoughts</strong></h3><p>Welcome, it is quite a journey to make it until here. We are almost finished, but a few things still need to be mentioned.</p><h4><strong>Requirements to make it work</strong></h4><p>As you may have noticed, the overall setup feels a little fiddly. And I totally agree with you if you feel the same. The current concept makes a few assumptions that definitely need to be improved before running in production.</p><p>The current setup allows basically any channel to push messages into the “RabbitMQ Outbound” channel. And a crucial requirement is that the message is wrapped by an envelope with the meta data sent with the first incoming request of the client.</p><p>Even creating and testing Channel Three is quite cumbersome at the moment because:</p><ol><li>One has to connect a client to the broker and send a message.</li><li>Then the log output in Mirth Connect will show the envelope with the necessary meta data.</li><li>Now its possible to create a simple channel with a Channel Reader source connector and a JavaScript Writer destination connector.<br>The destination connector contains the same script as above to publish a message to <em>Channel Two</em>.</li></ol><p>Obviously, in this test case, the envelope has to be filled manually with the meta data — except for the message as this comes from the source connector.</p><p>If the message is published and the client still connected it should receive the mesage.</p><h4><strong>Things to improve</strong></h4><p>Of course, there are more things to improve. For example:</p><ul><li>To be able to retrieve the correct envelope data within Mirth Connect there needs to be a global mapping that maps the envelope data to some unique part of the message. Then any channel could potentially obtain the envelope data with the correct key.</li><li>If this global map exits, envelope data needs a lifetime because Mirth Connect will not know anything about the client. This is because RabbitMQ sits in between the TCP Broker and Mirth Connect.</li><li>If a message is published to RabbitMQ and the client is not connected anymore, the message is queued. If the client reconnects and gets the same session back, it might receive all queued messages at once. This can either be on purpose or messages need a sort of lifetime.</li><li>And the list goes on and on and on …</li></ul><h3>Conclusion</h3><p>This article showed a proof-of-concept on how to set up bidrectional communication with TCP clients that have a limited connectivity.</p><p>Even if you don’t want to use the approach, I hope the article was able to help you spark some ideas and driving your thoughts forward if you are confronted with a similar situation.</p><p>And still, if you faced the same situation already and know of a similar or even better approach — please, let us know. Everyone reading the article until here is most likely very interested in learning from your experience.</p><p>That said, I wish you all the best. Have a great day.<br>And we will see each other in the next article.</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ebd1537ef8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Shrinking Text Composable — Or: How to animate the font weight]]></title>
            <link>https://medium.com/@pixelreverb/a-shrinking-text-composable-or-how-to-animate-the-font-weight-b91a432e9565?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/b91a432e9565</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 16:04:39 GMT</pubDate>
            <atom:updated>2024-12-19T16:04:39.896Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Shrinking Text Composable — Or: How to animate the font weight</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FxxUbqIi7MY5W6WL" /><figcaption>Photo by <a href="https://unsplash.com/@loic?utm_source=medium&amp;utm_medium=referral">Djim Loic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever wanted to animate the font weight in Android using Jetpack Compose? — This post shows one way how to do it based on a simple countdown timer.</p><p>So, I was just refreshing my understanding on Jetpack Compose and came across a <a href="https://youtu.be/07ZdBCyh7sc?si=bTwCPeKjDgHwM-uq">video</a> (by Philipp Lackner) about how to implement an animated timer. Although, the animation of sliding digits looks fine and is well-known, I wanted to implement an animation I had seen some while ago — and that is the animation of the font weight.</p><p>If you struggle with the code below, I suggest you take a look at Phillipp’s video as the code is partially based on it, and he does a great job explaining it.</p><h3>The result</h3><p>Here you can see what the end result looks like — a nice and simple animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*BF8Slm9iMfpQ4pbuI0vmXw.gif" /><figcaption>Countdown animation</figcaption></figure><p>To make it easy to recreate the end result the post will be a simple step-by-step guide. Of course, you can just pick the parts you like if you are already working on a project. There are no extra dependencies used and you can basically just copy-paste the code and start to tweak it as you like.</p><blockquote>Note: For a better readability I’m going to omit the import statements.</blockquote><h3>Starting anew</h3><p>Let’s start with a new blank project. Open Android Studio and create a new project with an empty activity. As of now, Jetpack Compose should be set by default.</p><p>I named my project AnimatedCounter , hence the AnimatedCounterTheme.</p><p>After you removed all the boilerplate code, you should be left with a MainActivity.kt similar to</p><pre>class MainActivity : ComponentActivity() {  <br>    override fun onCreate(savedInstanceState: Bundle?) {  <br>        super.onCreate(savedInstanceState)  <br>        enableEdgeToEdge()  <br>        setContent {  <br>            AnimatedCounterTheme {  <br>              // your code goes here<br>            }        <br>        }   <br>    }  <br>}</pre><h3>Shrinking text composable</h3><p>We are going to hop directly to the interesting part — the Text composable with the animated font weight.</p><p>Within your project create a new file called ShrinkingText.kt with its content as</p><pre>@Composable  <br>fun ShrinkingText(modifier: Modifier = Modifier, text: String, baseStyle: TextStyle, duration: Int = 1000) {  <br>    val animatedFloat = remember { Animatable(1f) }  <br>  <br>    LaunchedEffect(key1 = animatedFloat) {  <br>        animatedFloat.animateTo(0f, tween(duration))  <br>    }  <br>  <br>    Text(  <br>        modifier = modifier,  <br>        text = text,  <br>        style = baseStyle.copy(  <br>            fontWeight = lerp(  <br>                start = FontWeight(100),  <br>                stop = FontWeight(1000),  <br>                fraction = animatedFloat.value  <br>            )  <br>        )  <br>    )  <br>}</pre><p>This composable takes</p><ul><li>modifier — to be able to modify the Text composable</li><li>text — the text that is going to be displayed</li><li>baseStyle — a TextStyle as base style of which we are animating the font weight</li><li>duration — the animation duration</li></ul><p>After composition LaunchedEffect is triggered and hence will start the animation right away. As the Animatable is initiated with 1f and animated to 0f in combination with the linear interpolation ( lerp(...) ) of the FontWeight, the current setting makes the font go from <strong>bold</strong> to <em>thin</em>. If you want it to animate in the other direction, just swap the values.</p><p>And there you go. You now have an animated composable. For the rest of this post, we are going to use it with a counter, but you can use it with any kind of text, of course.</p><h3>Let’s count</h3><p>The ShrinkingText composable on its own is already usable. But now, let us continue and integrate it into a counter.</p><p>To do so, create a new file called ShrinkingTextCounter.kt. The content is</p><pre>@Composable  <br>fun ShrinkingTextCounter(  <br>    modifier: Modifier = Modifier,  <br>    count: Int,  <br>    style: TextStyle = MaterialTheme.typography.bodyMedium,  <br>) {  <br>    var lastCount by remember { mutableIntStateOf(count) }  <br>  <br>    SideEffect {  <br>        lastCount = count  <br>    }  <br>  <br>    Row(modifier = modifier) {  <br>        val countString = count.toString()  <br>        val lastCountString = lastCount.toString()  <br>        for (i in countString.indices) {  <br>            val lastChar = lastCountString.getOrNull(i)  <br>            val newChar = countString[i]  <br>  <br>            val char = if (lastChar == newChar) {  <br>                lastCountString[i]  <br>            } else {  <br>                countString[i]  <br>            }  <br>  <br>            AnimatedContent(  <br>                targetState = char, label = &quot;shrink text&quot;  <br>            ) {  <br>                ShrinkingText(  <br>                    text = it.toString(),  <br>                    baseStyle = style,  <br>                    duration = 1000,  <br>                )  <br>            }  <br>        }  <br>    }  <br>}</pre><p>At this point I would like you to take a look at Phillipp’s <a href="https://youtu.be/07ZdBCyh7sc?si=7YK2VQHdBMg_ItpF">video</a> if the code above is not completely clear. In short, this composable creates separate composables for each digit of count. When count changes and a new digit/char is detected, the targetState changes a new ShrinkingText composable is created which — as we learned earlier — directly fires its animation in the current implementation.</p><p>This means that if we have a decreasing counter and we change from <strong>20</strong> to <strong>19 </strong>both digits (<em>1</em> and <em>9</em>) are animated where as changing from <strong>19</strong> to <strong>18 </strong>will only animate the <strong>8</strong>.</p><h3>Make it a timer</h3><p>Up to here we have a text composable and a counter composable. What is left is to integrate them into a a countdown timer. To do that create a new file named ShrinkingTextTimer.kt with the following content</p><pre>@Composable  <br>fun ShrinkingTextTimer(initialTime: Long, modifier: Modifier = Modifier) {  <br>    var currentTime by remember {  <br>        mutableLongStateOf(initialTime)  <br>    }  <br>  <br>    LaunchedEffect(key1 = currentTime) {  <br>        if (currentTime &gt; 0L) {  <br>            delay(1000L)  <br>            currentTime -= 1000L  <br>        }  <br>    }  <br>  <br>    ShrinkingTextCounter(<br>        count = (currentTime / 1000L).toInt(), <br>        style = MaterialTheme.typography.displayLarge<br>    )  <br>}</pre><p>The timer takes the initial time in milliseconds and then starts to count down in steps of one second.</p><h3>Wrap it up</h3><p>The final step left is to implement the ShrinkingTextTimer into the MainActivity. Let’s quickly do this by updating the code of MainActivity.kt to</p><pre>class MainActivity : ComponentActivity() {  <br>    override fun onCreate(savedInstanceState: Bundle?) {  <br>        super.onCreate(savedInstanceState)  <br>        enableEdgeToEdge()  <br>        setContent {  <br>            AnimatedCounterTheme {  <br>                Column(  <br>                    modifier = Modifier.fillMaxSize(),  <br>                    verticalArrangement = Arrangement.Center,  <br>                    horizontalAlignment = Alignment.CenterHorizontally  <br>                ) {  <br>                    ShrinkingTextTimer(initialTime = 25000L)  <br>                }  <br>            }        <br>        }   <br>    }  <br>}</pre><p>And that’s it. Now you can go on and play with it.</p><p>I hope you liked this short tutorial.</p><p>I’d appreciate a 👏. Follow me if you want to be notified about the next article.</p><p>I wish you a nice day and hope to see you soon.</p><p>Connect with me on:<br>• <a href="https://www.instagram.com/pixelreverb/">Instagram</a><br>• <a href="https://www.linkedin.com/in/christian-hansen-89917a86/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b91a432e9565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm Fundamentals — The Big-O-Notation]]></title>
            <link>https://medium.com/@pixelreverb/algorithm-fundamentals-the-big-o-notation-41fe896a23ff?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/41fe896a23ff</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 09:21:45 GMT</pubDate>
            <atom:updated>2024-10-28T09:21:45.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithm Fundamentals — The Big-O-Notation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bB08F6HG0l7CK7o8saLHWg.jpeg" /><figcaption>DALL-E’s interpretation of common Big-O-Classifications. That’s something.</figcaption></figure><p>Are you interested in Computer Science? If you are, it is very likely that you will come across the term Big-O-Notation one day or another, once you started with topics like data structures and algorithms. This article gives a brief overview of what this notation is all about. We are also going to learn how to apply it to an algorithm once we have the basics set. But let’s start from the beginning, shall we?</p><blockquote>There are quite a few articles about the Big-O-Notation out there providing different views - some of them older, some newer. I think it is nice when this topic pops up again from time to time within a feed. One can use it as a reminder that the Big-O-Notation exists, if it is not part of the daily work.</blockquote><h3>Contents</h3><p>To be honest, this article turned out longer than I initially thought. I considered to split it into multiple parts, but then you — as the reader — would have to remember which part is talking about which topic.</p><p>Therefore, I kept it all in a single article. Feel free to bookmark it, and return to it when you don’t have the time now to read it all at once. You can use the table of contents below to navigate quickly to the section where you left.</p><ul><li><a href="#0f2e">What is Big-O-Notation in Computer Science?</a></li><li><a href="#a06d">Key Uses of the Big-O-Notation</a></li><li><a href="#8c3b">Common Big-O-Classifications</a></li><li><a href="#712c">Why only the term of highest order?</a></li><li><a href="#4029">How to approach determination of Big-O?</a></li><li><a href="#863c">Example Walkthrough</a></li><li><a href="#cf95">Final Words</a></li><li><a href="#9077">Appendix</a></li></ul><p>As this is a longer article, before you read any further, take a cup of coffee or tea and make yourself comfortable for the next few minutes. <br>Take a sip, relax and enjoy.</p><h3>What is Big-O-Notation in Computer Science?</h3><p>The <em>Big-O-Notation</em> is a mathematical concept used in computer science to describe the performance or complexity of an algorithm, particularly in terms of its runtime or space requirements as the input size grows. It provides a high-level understanding of how an algorithm’s efficiency scales with increasing data, allowing developers to make informed decisions about which algorithm to use in a given situation.</p><h3><strong>Key Uses of the Big-O-Notation</strong></h3><p>You may already be doing it without even thinking about it. You are using the <em>Big-O-Notation</em> to describe different aspects that appear in a similar context to algorithms. Let me explain:</p><h4><strong>Time Complexity</strong></h4><p>Most likely you think about describing time complexity when describing an algorithm using the <em>Big-O-Notation</em>. That is one way to use it. What you are aiming for is to compare algorithms by their execution speed, right?</p><p>In this case, the <em>Big-O-Classification</em> describes how the execution time of an algorithm changes as the input size increases.</p><p><strong>Example:</strong> Sorting algorithms such as <strong>Bubble Sort</strong> have a time complexity of <strong>O(n²)</strong>, while more efficient algorithms like <strong>Merge Sort</strong> have a time complexity of <strong>O(n * log n)</strong>.</p><blockquote>Psst. If you want to take a deep-dive into the famous entry-level algorithm <strong>Bubble Sort</strong>, you can check my article about it <a href="https://medium.com/@pixelreverb/algorithm-fundamentals-a-deep-dive-into-bubble-sort-14e94f0aa123">here</a>.</blockquote><h4>Space Complexity</h4><p>The <em>Big-O-Notation</em> can also describe how much memory an algorithm needs as the input size grows.</p><p>For example, some algorithms may require extra space (e.g. when creating new arrays to keep track of temporary states), while others work in place and therefore require constant memory ( <strong>O(1)</strong> ).</p><h4>Growth Rate</h4><p>Despite describing different complexities, the Big-O-Notation represents the growth rate of a function. The growth rate ignores constant factors and lower-order terms, focusing only on the largest contributing factor as the input size approaches infinity.</p><p>If you, for example, analyze an algorithm and your conclusion is that it takes <strong>3n² + 2n + 4</strong> operations, its <em>Big-O-Classification</em> is <strong>O(n²)</strong> as <strong>n²</strong> dominates the growth.</p><h3>Common Big-O-Classifications</h3><p>Now that we have an understanding of what the Big-O-Notation describes, let’s take a look at some common classifications.</p><p>We are going to relate them to the execution time. But you can easily swap the word <em>time</em> for <em>space</em> if you want to relate the classification to the required space during the algorithms’ execution. Just keep in mind to pick a proper reference for the space complexity, e.g. growth of a heap or depth of recursive calls.<br>The order of the classifications below is from fast to slow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IG668L2rr1uKO9pfvoNKYg.jpeg" /><figcaption>N = Amount of operations, n = Input size | Source: <a href="https://en.wikipedia.org/wiki/Big_O_notation">Wikipedia</a></figcaption></figure><p><strong>O(1): Constant time</strong><br>The algorithm takes the same amount of time regardless of input size.</p><p><strong>O(log n): Logarithmic time</strong><br>The algorithm’s performance increases logarithmically as the input size grows.</p><p><strong>O(n): Linear time</strong><br>The time grows directly proportional to input size.</p><p><strong>O(n <em>⋅ </em>log n): Quasi-linear time</strong><br>Often seen in efficient sorting algorithms like Merge Sort and QuickSort.</p><p><strong>O(n²): Quadratic time</strong><br>The performance grows with the square of the input size, common in algorithms with nested loops.</p><p><strong>O(2ⁿ): Exponential time</strong><br>The algorithm’s runtime doubles with each addition to the input data, very slow for large inputs.</p><p><strong>O(n!): Factorial time</strong><br>Extremely slow, often associated with brute-force solutions to problems like the <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">Traveling Salesman Problem</a>.</p><h3>Why only the term of highest order?</h3><p>Previously, it is mentioned that the <em>Big-O-Notation</em> focuses on the term with the <strong>highest order</strong> when describing the growth rate. This is because, as the input size grows large, this term dominates the behavior of the algorithm’s runtime or space complexity. The lower-order terms and constant factors become negligible when compared to the most significant term.</p><h4>1. Growth Dominance</h4><p>As input size <strong>n</strong> increases, terms with higher powers of <strong>n</strong> grow much faster than terms with lower powers or constant terms.</p><p>For example, if you have an algorithm with a time complexity expressed as:</p><blockquote><strong><em>f(n) = 3n² + 5n + 10</em></strong></blockquote><p>As <strong>n</strong> becomes large, the <strong>n²</strong> term grows much faster than both the <strong>n</strong> term and the constant <strong>10</strong>. So, for large <strong>n</strong>, the <strong>n²</strong> term dominates the runtime, and the contributions of the lower-order terms (like <strong>n</strong> or constants) become insignificant.</p><p>Let’s look at a few values for this function:<br><strong>n = 1</strong></p><ul><li><strong><em>f(1) = 3(1²) + 5(1) + 10 = 18</em></strong></li><li><strong><em>f(1) = 3 + 5 + 10</em></strong></li></ul><p><strong>n = 10</strong></p><ul><li><strong><em>f(10) = 3(10²) + 5(10) + 10 = 360</em></strong></li><li><strong><em>f(10) = 300 + 50 +10 = 360</em></strong></li></ul><p><strong>n = 100</strong></p><ul><li><strong><em>f(100) = 3(100²) + 5(100) + 10 = 30510</em></strong></li><li><strong><em>f(100) = 30000 + 500 + 10 = 30510</em></strong></li></ul><p>As you can see: When <strong>n</strong> grows, the contribution of terms like <strong>5n</strong> or <strong>10 </strong>becomes negligible compared to <strong>3n²</strong>.</p><h4>2. Asymptotic Behavior</h4><p>The <em>Big-O-Notation</em> is primarily concerned with the <strong>asymptotic behavior</strong> of a function as <strong>n</strong> approaches infinity. Asymptotic analysis ignores constant factors and focuses only on how the function behaves in the long run.</p><p>For example, both functions <em>( 5n )</em> and <em>( 1000000n )</em> grow linearly, so both have the same Big O classification: <strong>O(n)</strong>, even though their actual running times are different for smaller input sizes.</p><h4>3. Simplicity</h4><p>When describing algorithms, we aim to simplify the analysis by focusing on the dominant factor. Ignoring lower-order terms and constants makes the comparison between different algorithms easier and clearer.</p><p>For instance, if we have two algorithms, one with a time complexity of <strong>O(n²)</strong> and another with <strong>O(n³)</strong>, we immediately understand that the second algorithm scales worse than the first, without getting bogged down in the details of the constants or lower-order terms.</p><p>In essence, focusing on the term with the highest order allows to succinctly and effectively describe the long-term efficiency and scalability of algorithms, making it easier to compare their performance at scale.</p><p>You are still here? Good job.<br>Maybe take a moment and look outside the window for a few seconds to relax your eyes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tvw6wnqaCVn7yChSsXg72A.jpeg" /><figcaption>Jeffrey Czum | <a href="https://www.pexels.com/de-de/foto/fensteransicht-des-meeres-wahrend-der-goldenen-stunde-2733955/">pexels.com</a></figcaption></figure><p>When you are ready, we continue.</p><h3>How to approach determination of Big-O?</h3><p>So, up to this point we learnt about what the <em>Big-O-Notation</em> is and which common classifications exist. In this section, we will take a look at how you want to approach the determination of such a classification.</p><p>Determining the <em>Big-O-Notation</em> of an algorithm involves analyzing the code or algorithm step-by-step to understand how the execution time or space requirements grow with increasing input size. Here are some steps for your orientation:</p><h4>1. Identify the Basic Operations</h4><p>First, identify the core operations or steps in your algorithm. These are the steps that contribute to the overall runtime (e.g. assignments, comparisons, arithmetic operations, etc.). Each basic operation generally takes <strong>O(1)</strong> time (constant time).</p><h4>2. Analyze Loops</h4><p><strong>Loops</strong> are key to understanding how the algorithm scales. They are usually where the growth of the algorithm’s complexity comes from.</p><p><strong>Single loops</strong>: If the loop runs <strong>n</strong> times (where <strong>n</strong> is the size of the input), the time complexity will be <strong>O(n)</strong>.</p><p><strong>Nested loops</strong>: If you have a loop inside another loop, the total complexity is the product of the iterations of the loops. For example, two nested loops, each running <strong>n</strong> times, result in <strong>O(n²)</strong>.</p><p><strong>Example</strong></p><pre>// outer loop<br>for (let i = 0; i &lt; n; i++) {<br>    // inner loop<br>    for (let j = 0; j &lt; n; j++) {<br>        // O(1) operation<br>    }<br>}</pre><p>The outer loop runs <strong>n</strong> times, and for each iteration, the inner loop also runs <strong>n</strong> times, resulting in <strong>O(n²)</strong> complexity.</p><p>When the nested loops iterate over different collections, the notation slightly changes because we now have to deal with two different sources.</p><pre>// outer loop<br>for (let i = 0; i &lt; n; i++) {<br>    // inner loop<br>    for (let j = 0; j &lt; m; j++) {<br>        // O(1) operation<br>    }<br>}</pre><p>In this case, the outer loop iterates <strong>n</strong> times, while the inner loop iterates <strong>m</strong> times. As the sizes of <strong>n</strong> and <strong>m</strong> can be equal or significantly different, the notation reflects it as <strong>O(n <em>⋅ </em>m)</strong>.</p><h4>3. Analyze Recursion</h4><p>The next step is to analyze recursion within the algorithm.</p><p>As a short refresher: Recursive functions are functions that call them themselves during processing until a base condition is met that marks the end of the recursion.</p><p>Here’s a famous example of a recursive algorithm:</p><pre>/** <br> * Calculates the Fibonacci sequence.<br> * 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...<br> */<br>function fibonacci(num) {<br>  if (num &lt;= 1) return 1;<br><br>  return fibonacci(num - 1) + fibonacci(num - 2);<br>}</pre><p>To analyze <strong>recursive algorithms</strong>, use a recurrence relation to express the complexity and then solve the relation.</p><p>Let’s take a look at <strong>Binary Search</strong>:<br>The <strong>Binary Search </strong>algorithm splits the input in half at each recursive step. This leads to a recurrence relation like:</p><ul><li><strong><em>T(n) = T(n / 2) + O(1)</em></strong></li></ul><p>Where <strong>T(n/2)</strong> is a split and <strong>O(1)</strong> is the base condition. The solution to this relation is <strong>O(log n)</strong>.</p><blockquote>I put a description of how to solve this equation into a small Appendix at the end of this article. Just in case you are curious. <a href="#9077">Jump to Appendix</a></blockquote><h4>4. Count the Dominant Operations</h4><p>Taking a look at the algorithm, focus on the part of the algorithm that has the most significant impact on performance.</p><p>For example, look at the most expensive loops or recursive calls. If the algorithm has several parts (e.g., different loops or operations), add their individual complexities. The overall complexity will be dominated by the one with the highest growth rate.</p><pre>for (let i = 0; i &lt; n; i++) {<br>    // O(1) operation <br>}<br><br>for (let i = 0; i &lt; n; i++) { // O(n)<br>    for (let j = 0; j &lt; m; j++) { // O(n²) total<br>        // O(1) operation<br>    }<br>}</pre><p>In this case, the first loop is <strong>O(n)</strong>, but the second nested loop is <strong>O(n²)</strong>. Since <strong>O(n²)</strong> dominates, the overall complexity is <strong>O(n²)</strong>.</p><h4>5. Ignore Constants and Lower-Order Terms</h4><p>Once you have analyzed loops, recursion, or other structures, simplify the result by dropping constants and lower-order terms like mentioned in the paragraphs above.</p><blockquote>If your algorithm’s complexity turns out to be something like <strong>O(2n² + 5n + 10)</strong>, simplify it to <strong>O(n²)</strong> since the <strong>n²</strong> term dominates as <strong>n</strong> grows large.</blockquote><h4>6. Handle Different Cases (Best, Worst, Average)</h4><p>Sometimes, the performance of an algorithm varies with the input:<br> <strong>Best case</strong>: The minimum time the algorithm takes.<br><strong>Worst case</strong>: The maximum time it takes (typically what <em>Big-O</em> refers to).<br><strong>Average case</strong>: The expected time for typical inputs.</p><p>For instance, in <strong>Quicksort</strong>, the best case is <strong>O(n * log n)</strong> (when the pivot splits the list evenly), but the worst case is <strong>O(n²)</strong> (when the pivot is always the largest or smallest element). For <em>Big-O</em>, we typically focus on the <strong>worst-case scenario</strong> unless otherwise specified.</p><h4>7. Look for Common Algorithmic Patterns</h4><p>Many common algorithms have well-known time complexities, for example:</p><ul><li><strong>Linear Search</strong>: O(n)</li><li><strong>Binary Search</strong>: O(log n)</li><li><strong>Merge Sort</strong>: O(n <strong><em>⋅ </em></strong>log n)</li><li><strong>Bubble Sort</strong>: O(n²)</li><li><strong>Hashing (with good hash functions)</strong>: O(1) on average for lookup</li></ul><p>If you recognize a similar pattern (or even use one of them) in your algorithm, you can often infer the <em>Big-O-Classification</em> from that.</p><h4>8. Analyze Space Complexity (Optional)</h4><p>Space complexity refers to how much memory the algorithm uses as the input size grows. During analysis you should focus on the size of any extra data structures (arrays, lists, etc.) created during execution.</p><p>For example: <strong>In-place algorithms</strong> generally have space complexity of <strong>O(1)</strong>. Algorithms that create extra data structures like arrays or hash maps will have space complexity proportional to the size of these structures.</p><p>Phew, another big chunk of information covered. <br>Need another cup of coffee? In the final part, we are going to apply what we learned so far.</p><h3>Example Walkthrough</h3><p>Now that we are equipped with the necessary tools and knowledge, let’s analyze an algorithm to determine its <em>Big-O-Classification</em>. But because we want to have some fun and super simple examples are less likely to occur outside of tutorials, we are going to take a look at a backtracking algorithm to solve Sudokus (the famous number puzzles).<br>At the end of this section there is also a Codepen that implements the algorithm below.</p><h4>The Algorithm</h4><p>Let’s take look a the full implementation of the <strong>Sudoku backtracking algorithm</strong> first, so we can refer to it later. I also prepared a <em>Codepen</em> running this algorithm; you can find it at the end of this section.</p><pre>/**<br> * Function to check if placing a number is valid <br> */<br>function isValid(board, row, col, num) {<br>  // Check if the number exists in the current row<br>  for (let i = 0; i &lt; 9; i++) {<br>    if (board[row][i] === num) return false;<br>  }<br><br>  // Check if the number exists in the current column<br>  for (let i = 0; i &lt; 9; i++) {<br>    if (board[i][col] === num) return false;<br>  }<br><br>  // Check if the number exists in the current 3x3 subgrid<br>  const startRow = Math.floor(row / 3) * 3;<br>  const startCol = Math.floor(col / 3) * 3;<br>  for (let i = 0; i &lt; 3; i++) {<br>    for (let j = 0; j &lt; 3; j++) {<br>      if (board[startRow + i][startCol + j] === num) return false;<br>    }<br>  }<br><br>  // If all checks pass, the number is valid<br>  return true;<br>}<br><br>/**<br> * Function to find an empty cell (denoted by 0)<br> */<br>function findEmpty(board) {<br>  for (let row = 0; row &lt; 9; row++) {<br>    for (let col = 0; col &lt; 9; col++) {<br>      if (board[row][col] === 0) {<br>        return [row, col]; // Return the row and column of the empty cell<br>      }<br>    }<br>  }<br>  return null; // No empty cells found, the board is complete<br>}<br><br>/** <br> * Backtracking function to solve the Sudoku puzzle<br> */<br>function solveSudoku(board) {<br>  const emptyPos = findEmpty(board);<br>  <br>  if (emptyPos === null) {<br>    return true; // Base case: No empty cells, solution found<br>  }<br>  <br>  const [row, col] = emptyPos;<br> <br>  // Try placing numbers 1 to 9<br>  for (let num = 1; num &lt;= 9; num++) {<br>    if (isValid(board, row, col, num)) {<br>      // Place the number on the board<br>      board[row][col] = num;<br><br>      // Recursively try to solve the rest of the board<br>      if (solveSudoku(board)) {<br>        return true;<br>      }<br><br>      // If the number doesn&#39;t lead to a solution, backtrack<br>      board[row][col] = 0;<br>    }<br>  }<br>  return false; // No solution found for this configuration<br>}<br><br>/** <br> * Function to print the board (for visualization) <br> */<br>function printBoard(board) {<br>  for (let row = 0; row &lt; 9; row++) {<br>    let line = &quot;&quot;;<br>    for (let col = 0; col &lt; 9; col++) {<br>      line += board[row][col] + &quot; &quot;;<br>    }<br>    console.log(line);<br>  }<br>}<br><br>// Example usage<br>const board = [<br>  [5, 3, 0, 0, 7, 0, 0, 0, 0],<br>  [6, 0, 0, 1, 9, 5, 0, 0, 0],<br>  [0, 9, 8, 0, 0, 0, 0, 6, 0],<br>  [8, 0, 0, 0, 6, 0, 0, 0, 3],<br>  [4, 0, 0, 8, 0, 3, 0, 0, 1],<br>  [7, 0, 0, 0, 2, 0, 0, 0, 6],<br>  [0, 6, 0, 0, 0, 0, 2, 8, 0],<br>  [0, 0, 0, 4, 1, 9, 0, 0, 5],<br>  [0, 0, 0, 0, 8, 0, 0, 7, 9]<br>];<br><br>console.log(&quot;Sudoku puzzle before solving:&quot;);<br>printBoard(board);<br><br>if (solveSudoku(board)) {<br>  console.log(&quot;\nSudoku puzzle solved:&quot;);<br>  printBoard(board);<br>} else {<br>  console.log(&quot;No solution exists for the given puzzle.&quot;);<br>}</pre><h4>Explanation:</h4><ul><li><strong>isValid(board, row, col, num)</strong>: Checks whether placing a number in the given cell violates any Sudoku rules (i.e., no duplicate numbers in the row, column, or 3x3 subgrid).</li><li><strong>findEmpty(board)</strong>: Finds the next empty cell (represented by 0 in the grid) to try placing numbers.</li><li><strong>solveSudoku(board)</strong>: The core backtracking function that recursively tries to solve the puzzle by filling each empty cell with a valid number. If a solution is found, it returns true; otherwise, it backtracks.</li><li><strong>printBoard(board)</strong>: A utility function to print the Sudoku board in a readable format.</li></ul><h4>Output of the example</h4><pre>&gt; Sudoku puzzle before solving:<br>&gt; 5 3 0 0 7 0 0 0 0 <br>&gt; 6 0 0 1 9 5 0 0 0 <br>&gt; 0 9 8 0 0 0 0 6 0 <br>&gt; 8 0 0 0 6 0 0 0 3 <br>&gt; 4 0 0 8 0 3 0 0 1<br>&gt; 7 0 0 0 2 0 0 0 6 <br>&gt; 0 6 0 0 0 0 2 8 0 <br>&gt; 0 0 0 4 1 9 0 0 5 <br>&gt; 0 0 0 0 8 0 0 7 9</pre><pre>&gt; Sudoku puzzle solved:<br>&gt; 5 3 4 6 7 8 9 1 2 <br>&gt; 6 7 2 1 9 5 3 4 8 <br>&gt; 1 9 8 3 4 2 5 6 7 <br>&gt; 8 5 9 7 6 1 4 2 3 <br>&gt; 4 2 6 8 5 3 7 9 1 <br>&gt; 7 1 3 9 2 4 8 5 6 <br>&gt; 9 6 1 5 3 7 2 8 4 <br>&gt; 2 8 7 4 1 9 6 3 5 <br>&gt; 3 4 5 2 8 6 1 7 9</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fpixelreverb%2Fembed%2Fpreview%2FMWNQoLX%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DMWNQoLX&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fpixelreverb%2Fpen%2FMWNQoLX&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FMWNQoLX-512.jpg%3Fversion%3D1730105064&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ba963630cb008e38b60e4a7ce317938/href">https://medium.com/media/7ba963630cb008e38b60e4a7ce317938/href</a></iframe><h4>Algorithm Analysis</h4><p>The <strong>Sudoku backtracking algorithm</strong> operates by recursively trying to place valid numbers (1–9) into the grid’s empty cells. It uses backtracking when a conflict arises. The complexity of this algorithm depends on how many recursive calls are made and how long it takes to check the validity of each number.</p><p><strong>1. Time Complexity Analysis</strong><br><strong><em>Recursive Structure</em></strong><br>The algorithm fills each empty cell by attempting to place numbers from 1 to 9 in that cell, backtracking whenever a number violates the Sudoku rules. Therefore, at each empty cell, the algorithm has <strong>9 possible choices</strong>.</p><p>If there are <strong>n empty cells</strong>, in the worst case, the algorithm might try 9 possibilities for every empty cell. This leads to the worst-case time complexity being approximately:</p><ul><li><strong><em>O( 9</em></strong>ⁿ <strong><em>)</em></strong></li></ul><p>Where <strong>n</strong> is the number of empty cells in the Sudoku puzzle.</p><p>In the worst case, the grid could be entirely empty (81 cells), so the time complexity becomes:</p><ul><li><strong><em>O( 9</em></strong>⁸¹<strong><em>) (extremely large)</em></strong></li></ul><p><strong><em>Checking Validity<br></em></strong>For each number placement, we check whether the number is valid in the current row, column, and 3x3 subgrid.</p><ol><li><strong>Row check</strong>: <em>O(9)</em> — since there are 9 cells in a row</li><li><strong>Column check</strong>: <em>O(9)</em> — since there are 9 cells in a column</li><li><strong>Subgrid check</strong>: <em>O(9)</em> — since there are 9 cells in a 3x3 subgrid</li></ol><p>Thus, checking whether a number is valid in a cell takes <strong>O(9)</strong>. And as we learned earlier in this article, we can generalize this expression so that <strong>O(9)</strong> becomes <strong>O(9) = O(1)</strong>. We can do this because the operation takes a constant time.</p><p>Therefore, checking the validity of a number is constant time ( <em>O(1)</em> ).</p><p><strong><em>Finding an empty cell</em></strong><br>Similar to <em>Checking Validity</em> finding the next empty cell also takes constant time —<em> O(81)</em>, in the worst case when all cells are filled — and can therefore also be expressed as <em>O(1)</em>.</p><p><strong><em>2. Space Complexity</em></strong><br>As the array that represents the Sudoku board is changed in-place, the space complexity of the algorithm is determined by the depth of the recursion tree, which corresponds to the number of recursive calls on the stack.</p><p>In the worst case, we may recurse up to <strong>n</strong> levels deep, where <strong>n</strong> is the number of empty cells. Since there can be at most <strong>81</strong> empty cells in the grid, the maximum recursion depth is 81.</p><p>Therefore, the space complexity is <strong>O(n)</strong>, where <strong>n</strong> is the number of empty cells. This is bounded by <strong>O(81)</strong>, so in practical terms, it’s <strong>O(1)</strong>.</p><h4>Summary</h4><ol><li><strong>Worst-Case Time Complexity</strong>: <em>O(</em><strong><em>9</em></strong>ⁿ<em>) </em>, where <strong>n</strong> is the number of empty cells. For a fully empty grid, this becomes <em>O(9</em>⁸¹<em>)</em> .</li><li><strong>Space Complexity</strong>: <em>O(n)</em>, where <strong>n</strong> is the number of empty cells. In practice, this is <strong>O(1)</strong>, since the number of empty cells is bounded by 81.</li></ol><blockquote>Practical Consideration: In practice, the Sudoku backtracking algorithm usually performs much better than the theoretical worst-case time complexity. <br>The Sudoku rules (constraints on rows, columns, and subgrids) significantly reduce the number of valid choices at each step, meaning that the algorithm typically solves puzzles in a reasonable amount of time, even though its theoretical worst case is exponential.</blockquote><h3>Final words</h3><p>If you made this far, congratulations. 🎉</p><p>That was quite a long article to read. And throughout you learned a lot (although not all yet) about the <em>Big-O-Notation</em>.</p><p>We covered:</p><ul><li>What the Big-O-Notation is and where it is originated</li><li>Which Big-O-Classifications are common in the world of algorithms</li><li>How to approach the analysis of an algorithm</li><li>And you even went through an analysis with an example algorithm</li></ul><p>I hope this article was informative and fun to read, but mostly that you gained something from it. I’d appreciate a 👏, but you don’t need to. Follow me if you want to be notified about the next article in this series.</p><p>I wish you a nice day and hope to see you at the next article.</p><p>Connect with me on:<br>• <a href="https://www.instagram.com/pixelreverb/">Instagram</a><br>• <a href="https://www.linkedin.com/in/christian-hansen-89917a86/">LinkedIn</a></p><blockquote>P.S.: For the eager ones, there’s still the Appendix below if you haven’t read that one yet :)</blockquote><h3>Appendix</h3><h4>Solving a recurrence relation</h4><p>As mentioned earlier in the section “Analyze Recursion”, below is a step-by-step explanation of <em>one way</em> to solve the recurrence relation for <br><strong><em>T(n) = T(n/2) + O(1)</em></strong> describing Binary Search.</p><p><strong>1. Expand the Recurrence (Unfolding)<br></strong>We start by expanding the recurrence step-by-step.</p><p>Initial recurrence:</p><ul><li><strong><em>T(n) = T(n/2) + O(1)</em></strong></li></ul><p>Substitute T(n/2) from the recurrence into itself:</p><ul><li><strong><em>T(n) = ( T(n/4) + O(1) ) + O(1)</em></strong></li><li><strong><em>T(n) = T(n/4) + O(1) + O(1)</em></strong></li></ul><p>Expand further:</p><ul><li><strong><em>T(n) = T(n/8) + O(1) + O(1) + O(1)</em></strong></li></ul><p>Which leads us to generalization after <strong>k</strong> expansions of:</p><ul><li><strong><em>T(n) = T(n/2 ⋅ k) + k ⋅ O(1)</em></strong></li></ul><p><strong>2. Base Case</strong><br>The recurrence reduces to a base case when <strong>n</strong> becomes small enough. Typically, the base case occurs when <strong>n=1</strong>.</p><p>For the base case <strong>T(1) = O(1)</strong>, we stop the recursion.</p><p>To find <strong>k</strong>, solve for when the problem size becomes <strong>1</strong>:</p><ul><li><strong><em>n/2 ⋅ k = 1</em></strong></li></ul><p>Solving for <strong>k</strong>:</p><ul><li><strong><em>k = log ⁡2(n)</em></strong></li></ul><p><strong>3. Substitute Base Case</strong><br>Now, substitute the base case <strong>T(1) = O(1)</strong> and <strong>k = log ⁡2(n)</strong> into the expanded recurrence:</p><ul><li><strong><em>T(n) = T(1) + log⁡ 2(n) ⋅ O(1)</em></strong></li><li><strong><em>T(n) = O(1) + log⁡ 2(n) ⋅ O(1)</em></strong></li></ul><p><strong>4. Simplify</strong><br>The last step is to simplify the expression which results in the time complexity of the recurrence <strong>T(n) = T(n/2) + O(1)</strong> as:</p><ul><li><strong><em>T(n) = O(log⁡ n)</em></strong></li></ul><p>Back to the section where the solution was referenced: <a href="#dbc6">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41fe896a23ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithm Fundamentals — A Deep-Dive into Bubble Sort]]></title>
            <link>https://medium.com/@pixelreverb/algorithm-fundamentals-a-deep-dive-into-bubble-sort-14e94f0aa123?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e94f0aa123</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 08:53:17 GMT</pubDate>
            <atom:updated>2024-10-02T07:54:49.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>Algorithm Fundamentals — A Deep-Dive into Bubble Sort</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4zir2iP7iQYxEgSB" /><figcaption>Photo by <a href="https://unsplash.com/@kidcircus?utm_source=medium&amp;utm_medium=referral">Kid Circus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When starting with algorithms <strong>Bubble Sort</strong> is probably the first one you stumble upon. Bubble Sort is <em>the</em> algorithm that is used to introduce everybody into this topic. It is easy to understand and apply. In this article we will take a look at this famous sorting algorithm and even check how it can be optimized to squeeze out just a bit more performance.</p><p>There is a <a href="#bc9f">Codepen</a> at the end to showcase the optimizations that are discussed throughout this article.</p><blockquote>General note regarding this article series: Please, keep in mind that the implementations shown are focused on understanding and not performance. In case you want to reuse some parts, please, don’t blindly copy-paste stuff, but also think about improvements.</blockquote><p>Enough introduction. Let’s go.</p><h3>Contents</h3><p>Below is a list of the major sections in this article:</p><ul><li><a href="#6d18">Description</a></li><li><a href="#2e83">Use cases</a></li><li><a href="#6751">Performance</a></li><li><a href="#16e1">Implementation Example</a></li><li><a href="#3e1a">Optimisation</a></li><li><a href="#2adb">Summary</a></li><li><a href="#bc9f">Codepen</a></li></ul><h3>Description</h3><p>The <strong>Bubble Sort</strong> algorithm is one of the simplest sorting algorithms. In essence, it repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process continues until the list is sorted. Think of the elements as “bubbling up” to the top of the list as you sort, hence the name <strong>Bubble Sort</strong>. Of course, elements can also “bubble down” or “drown” to the bottom of the list. It just depends on how you define the swap condition.</p><p>Here’s a breakdown of how it works for the greater element to “bubble up”:</p><p><strong>Steps</strong></p><ol><li><strong>Start at the beginning</strong> of the list.</li><li><strong>Compare the first two elements</strong>. If the first is greater than the second, swap them.</li><li>Move to the next pair of adjacent elements and repeat the comparison and swap if needed.</li><li>Continue this process for the entire list. At the end of the first pass, the largest element will “bubble up” to its correct position (the last position in the list).</li><li><strong>Repeat the process </strong>for the rest of the list, ignoring the last element (since it’s already in the correct place. 🤫 This is already an optimization step we investigate later).</li><li>Continue the passes until no swaps are needed in a pass, meaning the list is sorted.</li></ol><p><strong>Example<br></strong>Consider this unsorted list of numbers: [5,3,8,4,2]</p><ol><li>First pass:<br>• Compare 5 and 3: swap → [3,5,8,4,2]<br>• Compare 5 and 8: no swap → [3,5,8,4,2]<br>• Compare 8 and 4: swap → [3,5,4,8,2]<br>• Compare 8 and 2: swap → [3,5,4,2,8]<br>• Now, the largest element 8 is in its correct position.</li><li>Second pass:<br>• Compare 3 and 5 no swap → [3,5,4,2,8]<br>• Compare 5 and 4: swap → [3,4,5,2,8]<br>• Compare 5 and 2: swap → [3,4,2,5,8]<br>• Now, 5 is in its correct position.</li><li>Third pass:<br>• Compare 3 and 4: no swap → [3,4,2,5,8]<br>• Compare 4 and 2: swap → [3,2,4,5,8]<br>• Now, 4 is in its correct position.</li><li>Fourth pass:<br>• Compare 3 and 2: swap → [2,3,4,5,8]<br>• Now the list is sorted.</li></ol><h3>Use cases</h3><p>While <strong>Bubble Sort</strong> is rarely used in practical, performance-critical applications due to its inefficiency compared to other sorting algorithms, there are a few scenarios where it might be useful or appropriate:</p><h3>1. Educational Purposes</h3><p><strong>Bubble Sort</strong> is often used to teach the fundamentals of sorting algorithms (as we do right now in this article 😊) and concepts such as nested loops, algorithm complexity, and step-by-step swapping. Its simplicity makes it an ideal introduction to sorting algorithms for beginners.</p><h3>2. Small Data Sets</h3><p>For small lists (let’s say fewer than 10–20 items), the performance difference between Bubble Sort and more advanced algorithms is negligible. Its simplicity and ease of implementation can make it an acceptable choice in such cases.</p><p>A quick test can reveal the benefits: Just compare the performance of <strong>Bubble Sort</strong> with a built-in sorting function (usually in the form of someDataStructure.sort()). Built-in sorting functions most likely use Quick Sort under the hood (because its fast 🏎️), but maybe you don’t need it in your use case.</p><h3>3. Data that is Almost Sorted</h3><p><strong>Bubble Sort</strong> performs better when the input data is nearly sorted, especially with slight modifications like <strong>Optimized Bubble Sort</strong> (see optimizations section below), where you track if any swaps were made during a pass. If no swaps were made, the list is already sorted, and you can stop early.<br>This makes it useful for applications where data is often “almost” sorted and requires occasional minor adjustments.</p><h3>Performance</h3><p>As most of you probably know, the <strong>Big-O-Notation</strong> is used to classify algorithms. The notation is borrowed from the field of mathematics and used in computer science to define the complexity of an algorithm in a more general way. <br>If, for example, an algorithm’s performance can be defined as <em>2n² + 2n + 1</em> the classification will be <em>O(n</em>²<em>)</em>, only keep the highest order. This approach somewhat disguises what the actual performance of the algorithm is going to be. Hence, having a bit more insight knowledge about an algorithm you want to use doesn’t hurt.</p><blockquote>A more detailed article about this topic is planned and I will link it here, once it is ready 📝</blockquote><p>Okay, so here’s the classification for <strong>Bubble Sort</strong>:</p><h3>Time Complexity:</h3><ul><li><strong>Best case</strong> (already sorted list): O(n) — only one pass with no swaps.</li><li><strong>Worst and average case</strong>: O(n²) — as there are nested loops, one to go through the list and another to repeat passes.</li></ul><blockquote>Gather information about the data you are processing (if you can). Then you are able to consider a best case (sorted), a worst case (completely shuffled) and — most importantly — an average case (partially shuffled, which is very likely to appear).</blockquote><h3>Space Complexity</h3><p><strong>Bubble Sort</strong> is an in-place sorting algorithm. Meaning that it does not need additional space during processing. Well, it needs additional space for a placeholder while swapping elements, but it does not build up another data structure (like Heap Sort) before performing the actual sorting.</p><h3>Implementation Example</h3><p>Here is an implementation example in JavaScript:</p><pre>function bubbleSort(arr) {<br>    let n = arr.length;<br><br>    // Outer loop to control the number of passes<br>    for (let i = 0; i &lt; n - 1; i++) {<br><br>        // Inner loop to compare adjacent elements<br>        for (let j = 0; j &lt; n - 1 - i; j++) {<br><br>            // Swap if the current element is greater than the next element<br>            if (arr[j] &gt; arr[j + 1]) {<br>                <br>                // Swap the elements<br>                let temp = arr[j];<br>                arr[j] = arr[j + 1];<br>                arr[j + 1] = temp;<br>            }<br>        }<br>    }<br>    return arr; // Return the sorted array<br>}<br><br>// Example usage:<br>let array = [5, 3, 8, 4, 2];<br>console.log(&quot;Unsorted array:&quot;, array);<br><br>let sortedArray = bubbleSort(array);<br>console.log(&quot;Sorted array:&quot;, sortedArray);<br><br>// Output:<br>// Unsorted array: [5, 3, 8, 4, 2]<br>// Sorted array: [2, 3, 4, 5, 8]</pre><blockquote>Note: Returning the sorted array is not really necessary as the input array is passed by reference and the array itself is manipulated. But then again, you don’t know how someone passes the array to the function …</blockquote><p><strong>How it works:</strong></p><ol><li>The outer loop controls the number of passes needed through the array. It runs n - 1 times, where n is the length of the array.</li><li>The inner loop compares each element with its adjacent element and swaps them if they are in the wrong order.</li><li>The inner loop decreases in range after each outer loop iteration ( n - 1 - i ), as the largest elements “bubble up” to the end of the array.</li></ol><h3>Optimization</h3><p><strong>Bubble Sort</strong> can be optimized to improve its efficiency, particularly in cases where the input data is nearly sorted. The basic Bubble Sort algorithm can be modified in several ways to make it faster while keeping its core structure intact. Below are a few common optimizations:</p><h3>1. Reducing the Inner Loop Range</h3><p>After each pass, the largest element “bubbles up” to its correct position. So, after each pass, the range of the inner loop can be reduced, as the last elements are already sorted and don’t need to be compared again.</p><p>This is already demonstrated in the implementation example above where the inner loop runs n - 1 - i times, reducing the number of comparisons in each subsequent pass.</p><h3>2. Stop If No Swaps Were Made</h3><p>In many cases, the list may become sorted before all passes are complete. If no swaps were made during a pass, the list is already sorted, and the algorithm can stop early. This reduces the number of unnecessary passes through the array.</p><p><strong>Optimized Code Example (with early termination)</strong></p><pre>function bubbleSort(arr) {<br>    let n = arr.length;<br>    let swapped;<br><br>    // Outer loop for passes<br>    for (let i = 0; i &lt; n - 1; i++) {<br>        swapped = false;  // Track if any swaps were made in this pass<br>        <br>        // Inner loop for comparison and swapping<br>        for (let j = 0; j &lt; n - 1 - i; j++) {<br>            if (arr[j] &gt; arr[j + 1]) {<br>                // Swap elements if they are in the wrong order<br>                let temp = arr[j];<br>                arr[j] = arr[j + 1];<br>                arr[j + 1] = temp;<br>                <br>                swapped = true;  // A swap was made<br>            }<br>        }<br><br>        // If no swaps were made during the pass, the array is sorted<br>        if (!swapped) {<br>            break;<br>        }<br>    }<br><br>    return arr;  // Return the sorted array<br>}</pre><p><strong>Explanation</strong></p><ul><li>The swapped variable tracks whether any elements were swapped during a pass.</li><li>If no swaps occur, the algorithm knows the array is already sorted, and it can break out of the loop early, saving unnecessary passes.</li></ul><h3>3. Bi-Directional (Cocktail Shaker Sort)</h3><p>Bubble Sort can be improved further by sorting in both directions. In this variation, also known as <strong>Cocktail Shaker Sort</strong> or <strong>Bidirectional Bubble Sort</strong>, the algorithm moves in both directions — left to right and then right to left — on alternate passes. This helps to move both small and large elements toward their final positions more efficiently.</p><p><strong>Bi-Directional Bubble Sort Example</strong></p><pre>function cocktailShakerSort(arr) {<br>    let n = arr.length;<br>    let swapped = true;<br>    let start = 0;<br>    let end = n - 1;<br><br>    while (swapped) {<br>        swapped = false;<br><br>        // Forward pass: move larger elements to the end<br>        for (let i = start; i &lt; end; i++) {<br>            if (arr[i] &gt; arr[i + 1]) {<br>                let temp = arr[i];<br>                arr[i] = arr[i + 1];<br>                arr[i + 1] = temp;<br>                swapped = true;<br>            }<br>        }<br><br>        // If no swaps, the array is sorted<br>        if (!swapped) {<br>            break;<br>        }<br><br>        // Otherwise, reset the swapped flag for the backward pass<br>        swapped = false;<br><br>        // Reduce the range of the array to be checked<br>        end--;<br><br>        // Backward pass: move smaller elements to the front<br>        for (let i = end - 1; i &gt;= start; i--) {<br>            if (arr[i] &gt; arr[i + 1]) {<br>                let temp = arr[i];<br>                arr[i] = arr[i + 1];<br>                arr[i + 1] = temp;<br>                swapped = true;<br>            }<br>        }<br><br>        // Increase the start position for the next forward pass<br>        start++;<br>    }<br><br>    return arr;<br>}<br><br>// Example usage<br>let array = [5, 3, 8, 4, 2];<br>console.log(&quot;Sorted array:&quot;, cocktailShakerSort(array));</pre><p><strong>Explanation</strong></p><ul><li>This approach sorts in both directions in each pass: first from left to right, and then from right to left. This helps reduce the number of iterations for lists where smaller elements are at the end of the list and need to move toward the front.</li><li>It tends to perform better than standard Bubble Sort, especially when dealing with a few misplaced elements.</li></ul><h3>Summary</h3><ul><li><strong>Bubble Sort</strong> is a fundamental algorithm — maybe not because of its efficiency but its educational value.</li><li>The <strong>basic optimization</strong> (early termination when no swaps are made) greatly improves performance for nearly sorted data.</li><li>The <strong>bidirectional version</strong> (Cocktail Shaker Sort) helps to balance the movement of both large and small elements, making it more efficient than the traditional Bubble Sort.</li><li>While these optimizations can improve Bubble Sort, for larger datasets or more demanding performance requirements, other algorithms like Quick Sort or Merge Sort are still preferred.</li></ul><h3>Codepen</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fpixelreverb%2Fembed%2Fpreview%2FExqxPmJ%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DExqxPmJ&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fpixelreverb%2Fpen%2FExqxPmJ&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FExqxPmJ-512.jpg%3Fversion%3D1727424036&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/30fd475587d4c52d0ed99853e7e2f7be/href">https://medium.com/media/30fd475587d4c52d0ed99853e7e2f7be/href</a></iframe><p>That’s it.</p><p>I hope you enjoyed the article. If you did, please 👏, I’d appreciate that. Follow me if you want to be notified about the next article in this series. And if you know somebody just starting with algorithms, feel free to pass them a link to this article.</p><p>Connect with me on:<br>• <a href="https://www.instagram.com/pixelreverb/">Instagram</a><br>• <a href="https://www.linkedin.com/in/christian-hansen-89917a86/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e94f0aa123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a terminal application with ink + React + Typescript — An introduction]]></title>
            <link>https://medium.com/@pixelreverb/creating-a-terminal-application-with-ink-react-typescript-an-introduction-da49f3c012a8?source=rss-bd1cfa505d44------2</link>
            <guid isPermaLink="false">https://medium.com/p/da49f3c012a8</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Christian Hansen]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 13:46:38 GMT</pubDate>
            <atom:updated>2024-08-21T18:03:09.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a terminal application with ink + React + Typescript — An introduction</h3><p>If you ever wondered how to easily start creating a terminal application, this article is for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0lHj06iyfNKLk30Tkyf0g.jpeg" /></figure><h3>Intro</h3><p>As developers we spend quite some time on the terminal. Be it to just execute a few commands from time to time, or to actually use it as one of your main tools to work with. No matter your profession and time you spent with the terminal, I guess we can agree that it always feels good, gives us a feeling of satisfaction, to use a well-crafted terminal application. And if you are tempted to try to create one of those apps, but don’t know where to start, read on.</p><p>This article guides you through the steps to setup a new <a href="https://github.com/vadimdemedes/ink">ink</a> project using <a href="https://react.dev/">React</a> and <a href="https://www.typescriptlang.org/">Typescript</a>. We will develop a simple layout with a basic navigation. Just enough to get you within the flow.</p><p>This undertaking shall be as accessible as possible. If you already have a decent amount of development experience using React, adding functionality you are used to work with in your React projects is up to you. Just keep in mind that the packages you want to use have to be compatible with Node.js, as this the environment the application will be executed in.</p><p>If you directly want to checkout the code — here you go: <a href="https://github.com/pixelreverb/ink-app-template">GitHub</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeZh8xVTUWMAtp6aIfSIpw.png" /></figure><h3>What do I use this tech-stack for?</h3><p>Currently, I implement a terminal application that allows me to follow realtime updates of a certain entity made in a <a href="https://www.postgresql.org/">PostgreSQL</a> database. The terminal app connects via a websocket to a small server application (written in <a href="https://kotlinlang.org/">Kotlin</a> with <a href="https://ktor.io/">Ktor</a>) which listens for data events that are published using PostgreSQL’s <a href="https://www.postgresql.org/docs/current/sql-notify.html">notify/listen</a> feature.</p><h3>Prerequisites</h3><p>A basic understanding of HTML, CSS and JavaScript should be fine. Some experience with React to be comfortable with component development can also come in handy. And you should know how to navigate within the terminal. (But as we are going to build a terminal application, I think the latter point is given.)</p><h4>Choose your editor</h4><p>In general, it is up to you which editor you want to use. While preparing this article I will stick with <a href="https://code.visualstudio.com/">VS Code</a>.</p><h3>Setup</h3><h4>Install Node.js</h4><p>Ok, first things first. As the foundation we need Node.js and npm to be installed. To do so, please visit the official Node.js website and choose your favorite way to install it: <a href="https://nodejs.org/en/download/package-manager">https://nodejs.org/en/download/package-manager</a></p><p>When the installation is done, you should be able to request the versions for node and npm with a similar output like below:</p><p><strong>Node</strong></p><pre>node -v<br>&gt; v22.5.1</pre><p><strong>npm</strong></p><pre>npm - version<br>&gt; 10.8.2</pre><h4>Create a new ink project</h4><p>Now that we can use npm, we are ready to set up a new ink project.</p><p>First, we initiate a new project. If you haven’t yet opened the terminal — now is the time. Once the terminal is open, navigate to your favorite folder for software projects and execute:</p><pre>npx create-ink-app - typescript my-ink-app</pre><p>You can omit the — typescript flag if you want to continue with the Javascript version.</p><p>This command creates a new ink project for you. And yes, we use npx here, it is not a typo. npx is a CLI tool that comes bundled within npm and basically provides an easier way to run executables based on Node.js — create-ink-app in this case.</p><p>When the setup is done you can change into the project directory.</p><pre>cd my-ink-app</pre><p>Also you can now open the project directory in your favorite editor or IDE if you haven’t already.</p><p>The directory structure of the initial project looks like this</p><pre>my-ink-app/<br> | → dist/<br> | → node_modules/<br> | → source/<br> .editorconfig<br> .gitattributes<br> .gitignore<br> .prettierignore<br> package-lock.json<br> package.json<br> readme.md<br> test.tsx<br> tsconfig.json</pre><p>When you build the project using npm run build the output is placed in the dist folder. <br>To start your application, you then want to run node dist/cli.js from the root directory, or change into the dist directory and run node cli.js respectively.</p><h4>Upgrading ink</h4><blockquote>When creating a new ink project using the command above it is — at the time of this writing — not installed with the latest release.</blockquote><p>We fix this by opening the package.json and updating the ink dependency from <strong>4.1.0</strong> to <strong>5.0.1</strong>. Save the file and run the command</p><pre>npm i</pre><p>to update the dependency.</p><p>Now, we could start with the implementation right away. But first let us preconfigure the project a bit. We will add some useful packages that we are going to need later on and improve the project configuration.</p><h4>Code formatting with prettier</h4><p>I like to have <a href="https://prettier.io/">prettier</a> setup for my projects for consistent code style. Here is the general approach:</p><p>1. Install the package<br>2. Search for the plugin<br>3. Setup the configuration</p><p>Related to VS Code the steps are like the following (should be similar for other editors and IDEs):</p><p><strong>Installing the package</strong><br>Add prettier to your project:</p><pre>npm i prettier -D</pre><p><strong>Installing the plugin</strong><br>In VS Code go to Extensions. Search for Prettier — Code formatter and install it. Now you open the VS Code settings and search for formatter to set your default formatter to — you guessed it — prettier.<br>For other IDEs and editors this step is similar.</p><p><strong>Setup the configuration</strong><br>In the root directory, create a new file called .prettierrc (yes, starting with a dot).<br>Within this file you can add rules in JSON format that are applied when prettier formats your code. In VS Code you get auto-completion when the plugin is installed.<br>If you need some inspiration: My set of rules related to projects that use React and Typescript usually looks like this:</p><pre>{<br> &quot;printWidth&quot;: 140,<br> &quot;tabWidth&quot;: 4,<br> &quot;useTabs&quot;: false,<br> &quot;semi&quot;: false,<br> &quot;singleQuote&quot;: true,<br> &quot;trailingComma&quot;: &quot;all&quot;,<br> &quot;bracketSpacing&quot;: true,<br> &quot;jsxBracketSameLine&quot;: true,<br> &quot;singleAttributePerLine&quot;: true,<br> &quot;jsxSingleQuote&quot;: true<br>}</pre><p>But in the end, its totally up to you how you want your formatting rules.</p><h4>Adding ink related packages</h4><p>This setup will make use of a few ink components. Let’s add them with the following command:</p><pre>npm i ink-select-input ink-gradient ink-big-text</pre><ul><li>ink-select-input provides us with a selectable list; which we are going to use to build a simple navigation</li><li>ink-big-text allows us to create headlines and ink-gradient allows us to make them nice</li></ul><h4>Adding more packages</h4><p>At the moment the setup is good enough to start. We introduce some additional packages on our way. It is easier to see their purpose within the right context.</p><p>Finally, let’s get started.</p><h3>The current app state</h3><p>Let’s start simple and just run the application as it is right now.</p><pre>npm run build &amp;&amp; node dist/cli.js</pre><p>This gives an output of</p><pre>&gt; Hello, Stranger</pre><p>You could pass a value via the name flag if you want:</p><pre>node dist/cli.js - name=Joe<br>&gt; Hello, Joe</pre><p>Ok, so thats the current state of the basic application. Let’s begin to change it.</p><h3>Call hierarchy</h3><p>First, we take a quick glance at the call hierarchy. Within the dist folder, the entry point for our application is the cli.js which invokes app.js.</p><p>We want to start building our app within the source directory.</p><h4>Code clean-up</h4><p>Let’s clean-up the code because we don’t need some of it for now. You can remove the following portions or just comment them out if you feel that you might want to use them later.</p><p>We want to remove the name parameter from the App component and the props definition. Within the cli.tsx remove the name parameter from the App component and the flag definition.</p><p>The applications entry point then remains as</p><p><strong>cli.tsx</strong></p><pre>#!/usr/bin/env node<br>import React from &#39;react&#39;;<br>import {render} from &#39;ink&#39;;<br>import App from &#39;./app.js&#39;;<br>render(&lt;App /&gt;);</pre><p><strong>app.tsx</strong></p><pre>import React from &#39;react&#39;;<br>import {Text} from &#39;ink&#39;;<br>export default function App() {<br> return (&lt;Text&gt;Hello&lt;/Text&gt;)<br>}</pre><p>That’s a pretty clean place to start.</p><h4>Create a template with a sidebar</h4><p>Open app.tsx. For the sake of simplicity, we will stay within this file. Fell yourself free to move the components into their own files as they grow in complexity.</p><blockquote>To not make this article longer than necessary, I’m not deeply explaining the styling options. Please, take a look at the documentation in the <a href="https://github.com/vadimdemedes/ink">ink</a> repository if you want to know more about the possibilities.</blockquote><blockquote>One remark about the dimensions though. If you define the width by a number it means <strong>spaces</strong>, while defining a height it means <strong>rows</strong>. Thus, a size of height={10} width={10} does not create a square, but a thin long rectangle.</blockquote><p>Let us begin by creating three components<br>- MainLayout— A wrapper for the application to act as parent layout<br>- SideBar — A sidebar<br>- Content — The main content area</p><pre>function MainLayout({children}: PropsWithChildren) {<br>  return &lt;Box&gt;{children}&lt;/Box&gt;;<br>}<br><br>function SideBar() {<br>  return (<br>    &lt;Box borderStyle={&#39;single&#39;} width={40}&gt;<br>      &lt;Text&gt;I&#39;m a sidebar&lt;/Text&gt;<br>    &lt;/Box&gt;<br>  );<br>}<br><br>function Content() {<br>  return (<br>    &lt;Box width={&#39;100%&#39;} borderStyle={&#39;single&#39;}&gt;<br>      &lt;Text&gt;Im&#39; the content area&lt;/Text&gt;<br>    &lt;/Box&gt;<br>  );<br>}</pre><p>and arrange them within the App component like</p><pre>export default function App() {<br>  return (<br>    &lt;MainLayout&gt;<br>      &lt;SideBar /&gt;<br>      &lt;Content /&gt;<br>    &lt;/MainLayout&gt;<br>  );<br>}</pre><p>Now, you can run</p><pre>npm run build &amp;&amp; node dist/cli.js</pre><p>from the root directory to see what we have so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46sogXXu_uHu80uMcaZ4jw.png" /></figure><h4>Make it fullscreen</h4><p>The next step is to make it fullscreen because we want to build an application. If you just want to print content in the terminal based on a layout. You don’t need to add the following dependency.</p><p>To be able to show the application in fullscreen (the size of the terminal window), we use the package <a href="https://www.npmjs.com/package/fullscreen-ink">fullscreen-ink</a>.</p><p>Go ahead and install it:</p><pre>npm i fullscreen-ink</pre><p>Then open the cli.tsx and adjust the render call like so</p><pre>//render(&lt;App /&gt;);<br>withFullScreen(&lt;App /&gt;).start();</pre><p>This change will make the app use the entire screen size <strong>and</strong> keep it running.</p><p>Change to the app.tsx file and update the components’ heights:</p><pre>function SideBar() {<br> {…}<br> &lt;Box height={&#39;100%&#39;} …&gt;<br> …<br> &lt;/Box&gt;<br> {…}<br>}<br>function Content() {<br> {…}<br> &lt;Box height={&#39;100%&#39;} …&gt;<br> …<br> &lt;/Box&gt;<br> {…}<br>}</pre><p>Go ahead and try again</p><pre>npm run build &amp;&amp; node dist/cli.js</pre><p>Keep in mind that you now need to press Ctrl + C to close the app.</p><p>And what you think? Cool, right? Just a few lines and a basic layout is set up. Next, we are going to add a navigation.</p><h3>Basic Navigation</h3><p>The navigation we are going to add will be quite simple in its logic. Just a simple callback that receives an event. And based on that event we decide which content to show.</p><h4>Adding pages</h4><p>Refactor the Content component and duplicate it like below. These two additional components represent our different contents we would like to show based on the selected navigation point. We also use the ink components we installed at the beginning to create a simple fancy layout (just because we can).</p><p><strong>app.tsx</strong></p><pre>{…}<br><br>function ContentPaneOne() {<br>  &lt;Box<br>    borderStyle={&#39;single&#39;}<br>    height={&#39;100%&#39;}<br>    width={&#39;100%&#39;}<br>    flexDirection={&#39;column&#39;}<br>    paddingLeft={4}<br>    paddingRight={4}<br>  &gt;<br>    &lt;Gradient name={&#39;retro&#39;}&gt;<br>      &lt;BigText text={&#39;Pane 1&#39;} /&gt;<br>    &lt;/Gradient&gt;<br>    &lt;Text&gt;I&#39;m the first content area&lt;/Text&gt;<br>  &lt;/Box&gt;<br>}<br><br>function ContentPaneTwo() {<br>  &lt;Box<br>    borderStyle={&#39;single&#39;}<br>    height={&#39;100%&#39;}<br>    width={&#39;100%&#39;}<br>    flexDirection={&#39;column&#39;}<br>    paddingLeft={4}<br>    paddingRight={4}<br>  &gt;<br>    &lt;Gradient name={&#39;rainbow&#39;}&gt;<br>      &lt;BigText text={&#39;Pane 2&#39;} /&gt;<br>    &lt;/Gradient&gt;<br>    &lt;Text&gt;I&#39;m the second content area&lt;/Text&gt;<br>  &lt;/Box&gt;<br>}</pre><h4>Adding the navigation</h4><p>For the navigation part we keep it simple. We define navigation items in the App component and pass them to the SideBar component. The SideBar then renders the navigation menu based on the given items. We also add a callback function to the SideBar so that the App can be informed whenever a new item is selected. Based on the selection we change which content component is rendered.</p><h4>SideBar</h4><p>As we use Typescript in this tutorial, we need to define a type from time to time when we pass objects.</p><p><strong>app.tsx </strong>— SideBar</p><pre>type SideBarProps = {<br>  navItems: Array&lt;Item&lt;string&gt;&gt;;<br>  onSelect: (item: Item&lt;string&gt;) =&gt; void;<br>};<br><br>function SideBar({navItems, onSelect}: SideBarProps) {<br>  return (<br>    &lt;Box<br>      borderStyle={&#39;single&#39;}<br>      height={&#39;100%&#39;}<br>      width={40}<br>      paddingTop={1}<br>      paddingBottom={1}<br>      paddingLeft={2}<br>      paddingRight={2}<br>    &gt;<br>      &lt;SelectInput items={navItems} onSelect={onSelect} /&gt;<br>    &lt;/Box&gt;<br>  );<br>}</pre><blockquote>To import Item properly, please, use import {Item} from ‘../node_modules/ink-select-input/build/SelectInput.js’;. <br>It is currently not accessible as exported type. Maybe this is not necessary with a future update of the ink-select-input package.</blockquote><h4>Navigation</h4><p>Next, let’s define the menu items.</p><pre>const navItems: Item&lt;string&gt;[] = [<br>  { label: &#39;Pane 1&#39;, value: &#39;pane_one&#39; },<br>  { label: &#39;Pane 2&#39;, value: &#39;pane_two&#39; },<br>  { label: &#39;Exit&#39;, value: &#39;exit&#39; },<br>]<br><br>export default function App() {<br>  …<br>}</pre><p>As we only need to define the navigation items once, we can declare them outside the App component.</p><p>Then we define the callback that is invoke when an item has been selected and pass it together with the array to the SideBar component. In this step, we directly take care of the navigation selection.</p><pre>export default function App() {<br>  const [currentNavItem, setCUrrentNavItem] = useState(navItems[0]);<br>  const {exit} = useApp();<br>   <br>  const onNavItemSlected = (item: Item&lt;string&gt;) =&gt; {<br>    if (item.value === &#39;exit&#39;) {<br>      exit();<br>    } else {<br>      setCUrrentNavItem(item);<br>    }<br>  };<br><br>  return (<br>    &lt;MainLayout&gt;<br>      &lt;SideBar navItems={navItems} onSelect={onNavItemSlected} /&gt;<br>      {currentNavItem?.value === &#39;pane_one&#39; &amp;&amp; &lt;ContentPaneOne /&gt;}<br>      {currentNavItem?.value === &#39;pane_two&#39; &amp;&amp; &lt;ContentPaneTwo /&gt;}<br>    &lt;/MainLayout&gt;<br>  );<br>}</pre><p>The exit function is part of the fullscreen-ink package and exits the application. Basically, the same as pressing Ctrl + C.</p><p>Ok, so once more try it out</p><pre>npm run build &amp;&amp; node dist/cli.js</pre><p>And, we are done! :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeZh8xVTUWMAtp6aIfSIpw.png" /></figure><p>Phew, quite a few steps to create a template. I hope you had fun and that this article inspired you to start building awesome terminal applications.</p><p>I appreciate when this post gets your like.<br>Let me know if you want a follow-up on this topic.<br>And if you want to connect, find me on:</p><p>&gt; <a href="https://www.instagram.com/pixelreverb/">Instagram</a><br>&gt; <a href="https://www.linkedin.com/in/christian-hansen-89917a86/">LinkedIn</a></p><p>Have a nice day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da49f3c012a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>