<?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 Stephen Siapno on Medium]]></title>
        <description><![CDATA[Stories by Stephen Siapno on Medium]]></description>
        <link>https://medium.com/@setoxsiapno?source=rss-65e22711389e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zI1SzbPP4uSjTXo3C-LtBw.jpeg</url>
            <title>Stories by Stephen Siapno on Medium</title>
            <link>https://medium.com/@setoxsiapno?source=rss-65e22711389e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 07:04:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@setoxsiapno/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[Boosting Android Development with OpenAI Codex: First Impressions]]></title>
            <link>https://proandroiddev.com/boosting-android-development-with-openai-codex-first-impressions-4ec6e8dcb83a?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec6e8dcb83a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[codice]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 11:42:38 GMT</pubDate>
            <atom:updated>2025-06-08T11:51:22.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*7rP4Th0Lk0ftx9uPafA7SA.png" /></figure><p>OpenAI recently introduced a <strong>software engineering AI agent</strong> that can handle multiple development tasks in parallel, making it a powerful tool for boosting productivity.</p><p>You can use it to fix bugs, review code, do refactors, and fix pieces of code in response to user feedback.</p><p>The real strength of this tool is about <strong>offloading</strong> or <strong>delegating</strong> repetitive tasks, so you can focus your time and energy on more important and thoughtful parts of development.</p><p>You can check more information in the link below:</p><p><a href="https://openai.com/index/introducing-codex/">https://openai.com/index/introducing-codex/</a></p><p>Since it became available to <strong>ChatGPT Plus</strong> users last <strong>June 3*</strong>, we decided to try it out for <strong>Android development</strong> and share our first impressions.</p><h3>Prerequisites</h3><p>To be able to use codex, you need the following:</p><ul><li>A <strong>ChatGPT Plus</strong> subscription (to access the AI coding agent)</li><li>A <strong>GitHub account</strong></li><li>An <strong>existing Android project</strong> where you can experiment with suggestions or code generation.</li></ul><h3>Setting Up</h3><p>To access Codex, you just need an active <strong>ChatGPT Plus</strong> subscription. Go to <a href="https://chatgpt.com/">chatgpt.com</a> and look for <strong>Codex</strong> in the sidebar panel.</p><p>Setting it up is pretty straightforward. You can follow the step-by-step instructions provided by Codex, or check out the <a href="https://platform.openai.com/docs/codex/overview">official documentation</a> for more details.</p><p>One important requirement: you’ll need a <strong>GitHub account</strong> and a <strong>repository</strong> that Codex can access to interact with your code.</p><h3>Creating and Running a Task</h3><p>Once Codex is set up, the typical workflow starts by creating a <strong>task</strong>. You can do this in two ways: using <strong>Ask mode</strong> or <strong>Code mode</strong>.</p><p><strong>Ask mode</strong> is helpful when you’re trying to understand unfamiliar code or explore how something works. It works like a regular conversation with ChatGPT, guiding you through the codebase.</p><p><strong>Code mode</strong> is for giving direct instructions. For example, you might ask Codex to write unit tests for a specific file or refactor a function.</p><p>After Codex completes the task, it shows a <strong>diff view</strong> so you can review the changes. It also runs checks using the cloud environment that was configured during setup. This allows it to validate the changes automatically.</p><p>If you’re happy with the result, you can create a <strong>pull request</strong> to your GitHub repository right from the Codex interface.</p><h3>First Impressions</h3><h4>1. Handling Multiple Tasks in Parallel</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*7rP4Th0Lk0ftx9uPafA7SA.png" /><figcaption>Codex running multiple tasks in Parallel</figcaption></figure><p>One of the first things I noticed was how convenient it is to prompt multiple tasks and simply wait for the results.</p><p>For example, I asked Codex to generate a README.md file for each module and to create specific unit tests per file.</p><p>I intentionally broke these into smaller tasks to avoid having one large diff. This approach worked well and made the process more manageable.</p><p>Normally, doing these kinds of tasks would take a lot of mental energy. Delegating them to Codex and having them done in parallel felt like a big productivity boost.</p><h4>2. Environment Limitations for Android</h4><p>Codex works well for small changes, but I ran into limitations when trying to run or test Android-specific code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*5flXbejnBiW9eEr0_TyvTQ.png" /></figure><p>I attempted to set up a custom environment script in the settings, but I wasn’t able to get it working properly for Android at this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*RZOC1N4fSmtDbhwNh6tBdQ.png" /><figcaption>Codex Environment Settings</figcaption></figure><p>This wasn’t a major issue for me since I already have a GitHub Action in place to confirm the changes. It builds the project, runs tests, and applies formatting using Spotless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*Pzyxi92HXuV31VI4FAEVPw.png" /></figure><p>Still, it would be great if Codex eventually supports Android environments more smoothly in the future.</p><h4>3. Commit Base and Rebase Concerns</h4><p>Another limitation I noticed is that when you start a task, Codex locks in the latest commit as the base. If your branch receives new commits afterward, there’s no way to rebase the task from within Codex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*k2a0pe0keaCbn7PM45J8_Q.png" /></figure><p>I tried asking it to rebase, but that didn’t work.</p><p>The only option was to either create a new task or rebase locally after the pull request was created.</p><p>It’s a bit inconvenient, but considering how much time Codex already saves, manually rebasing isn’t a big problem for now.</p><h4>4. Incomplete Code and CI Checks</h4><p>There were a few times when the generated code was incomplete or slightly off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*0TXKanxOeRM2T_Jty7Disw.png" /><figcaption>No package name when creating a file. I wasn’t able to catch the problem.</figcaption></figure><p>This is where having a CI setup is incredibly helpful.</p><p>My GitHub Action checks whether the project builds, passes tests, and is properly formatted.</p><p>This allows me to catch and fix issues right after Codex opens a pull request, making the workflow more dependable even when the output isn’t perfect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4p0Ou5HLy8DzmsJJ3OhtA.png" /><figcaption>Github Action in Action</figcaption></figure><h4>5. Fixing Code After Pull Request</h4><p>You can still update code through Codex even after the pull request is created, which is nice.</p><p>However, the same rebase limitation applies. If the base branch changes, you’ll still need to rebase it locally.</p><p>In some cases, it’s faster to just fix the code yourself instead of trying to instruct Codex to do it.</p><h4>6. Overall Productivity</h4><p>Overall, I felt more productive and efficient using Codex. I was able to complete tasks overnight that would have required hours of focused effort if done manually.</p><p>Offloading the routine work let me focus more on reviewing and validating code. Because of that, having a strong CI pipeline becomes even more important.</p><p>It acts as your safety net when collaborating with the AI agent and helps ensure everything works as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlIe07Y5JhZGH0rxM-z8Iw.png" /><figcaption>Created 26 Pull Request using codex</figcaption></figure><h3>Conclusion</h3><p>Overall, I think Codex is a great addition to my development workflow. While it’s still early and there are clear limitations, I completely understand that it’s a new tool and has room to grow. Despite that, the experience so far has been impressive, and I’m genuinely excited about how much it can improve my productivity moving forward.</p><p>As someone who already uses ChatGPT and GitHub for version control, having Codex integrated into that setup makes everything feel seamless and convenient. There are a few rough edges, like the lack of Android environment support and the inability to rebase tasks directly, but there are workarounds that make it manageable. What matters more is that it’s already saving me time and mental effort on repetitive tasks.</p><p>For me, <strong>Codex</strong> is a game changer. It’s the kind of AI tool that fits naturally into my workflow and helps me focus on higher-level decisions instead of getting stuck. There are so many AI tools popping up today, but it’s important not to get overwhelmed. The key is to try tools that genuinely add value, and for me, Codex does exactly that.</p><p>If you’re trying Codex for the first time, I recommend starting with small and clear tasks like:</p><ul><li>Creating a README.md file per module</li><li>Generating JavaDoc for each class or file</li><li>Writing unit tests per file or feature</li><li>Creating module or feature templates</li></ul><p>It also helps to structure your project clearly, so Codex can better understand it and isolate each task properly.</p><p>You can check out my sample repo where I used Codex:</p><p><a href="https://github.com/TheSetox/ConversionApp">GitHub - TheSetox/ConversionApp: ConversionApp is a currency exchange application that allows users to convert between currencies using up-to-date exchange rates. It syncs rates from a remote API, applies commissions based on specific rules, and keeps track of user balances - all in real-time.</a></p><p>Feel free to leave a star if you find it helpful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec6e8dcb83a" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/boosting-android-development-with-openai-codex-first-impressions-4ec6e8dcb83a">Boosting Android Development with OpenAI Codex: First Impressions</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Kotlin Multiplatform: A Visual Guide Part 2 (Multi-Module)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@setoxsiapno/exploring-kotlin-multiplatform-a-visual-guide-part-2-multi-module-d1a34c883c8e?source=rss-65e22711389e------2"><img src="https://cdn-images-1.medium.com/max/2600/0*DbjPT_ryzVUCpB1e" width="3400"></a></p><p class="medium-feed-snippet">Structuring Code for Scalability and Flexibility Across Platforms</p><p class="medium-feed-link"><a href="https://medium.com/@setoxsiapno/exploring-kotlin-multiplatform-a-visual-guide-part-2-multi-module-d1a34c883c8e?source=rss-65e22711389e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@setoxsiapno/exploring-kotlin-multiplatform-a-visual-guide-part-2-multi-module-d1a34c883c8e?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a34c883c8e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 00:23:32 GMT</pubDate>
            <atom:updated>2024-10-03T00:23:32.930Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Every Android Developer Should Leverage the Kotlin Multiplatform Ecosystem]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@setoxsiapno/every-android-developer-should-leverage-the-kotlin-multiplatform-ecosystem-dd836f262e86?source=rss-65e22711389e------2"><img src="https://cdn-images-1.medium.com/max/1024/1*qSW1i6dIvcul9PkeRCrkPA.jpeg" width="1024"></a></p><p class="medium-feed-snippet">From Android to Everywhere: The Power of Kotlin Multiplatform</p><p class="medium-feed-link"><a href="https://medium.com/@setoxsiapno/every-android-developer-should-leverage-the-kotlin-multiplatform-ecosystem-dd836f262e86?source=rss-65e22711389e------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@setoxsiapno/every-android-developer-should-leverage-the-kotlin-multiplatform-ecosystem-dd836f262e86?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd836f262e86</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 00:14:48 GMT</pubDate>
            <atom:updated>2024-09-27T00:15:45.297Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Exploring Kotlin Multiplatform: A Visual Guide]]></title>
            <link>https://proandroiddev.com/exploring-kotlin-multiplatform-a-visual-guide-734b85132d68?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/734b85132d68</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 01:59:53 GMT</pubDate>
            <atom:updated>2024-10-03T00:26:00.396Z</atom:updated>
            <content:encoded><![CDATA[<h4>Visualizing the Future of Code Sharing Across Platforms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVsyg1g218UFvDP-cQ2vxA.png" /></figure><p><strong>Kotlin Multiplatform</strong> is one of my favorite tools right now.</p><p>This year, I’ve been exploring it more deeply and have created a few projects to take full advantage of what it has to offer.</p><p>Although setting it up can sometimes be challenging, once you have everything configured, the benefits are truly rewarding.</p><p>One of the best features of Kotlin Multiplatform is its <strong>flexibility </strong>and how seamlessly it integrates into existing projects.</p><p>Unlike other cross-platform tools that often require a complete rewrite or drastic changes, <strong>Kotlin Multiplatform</strong> allows you to incrementally adopt shared code across platforms while still retaining full control over platform-specific implementations.</p><p>Since I’ve been working with it and trying out <a href="http://excalidraw.com/">Excalidraw</a>, I was having fun and putting together some diagrams to illustrate how Kotlin Multiplatform can be integrated into various architectures.</p><p>These diagrams serve as my reference, and I hope they’ll be helpful to you as well.</p><h3>Why Kotlin Multiplatform?</h3><p>Kotlin Multiplatform (KMP) allows you to share core logic between multiple platforms like Android, iOS, and even the web or desktop, while still keeping full access to platform-specific APIs when needed.</p><p>What makes it stand out from other cross-platform solutions is its <strong>adaptability</strong>.</p><p>You don’t have to replace your existing architecture — instead, you can integrate KMP into your current project in a modular fashion, choosing which layers you want to share and which ones to keep platform-specific.</p><h3>Integrating Kotlin Multiplatform and Other Development Strategies</h3><h4>1. Normal Approach</h4><p>In a traditional setup, iOS and Android applications are developed separately, with no shared code between the platforms.</p><p>This approach can lead to duplicated effort as each platform requires its own UI, business logic, and data handling implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hIX-2luUbuR9pF1_HAGnQ.png" /></figure><h4>2–1. Kotlin Multiplatform and Native UI</h4><p>The first step toward a multiplatform approach is to keep the native UI separate while sharing the core logic.</p><p>In this case, Kotlin Multiplatform is applied to the business and data logic, but the UI is still developed natively for iOS and Android.</p><p>This allows for shared logic without disrupting platform-specific UI features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YptZ7bqObXlN8gqWRcfswg.png" /></figure><h4>2–2. Kotlin Multiplatform and Compose Multiplatform</h4><p>If you want to take it a step further, you can use <strong>Compose Multiplatform</strong> to unify your UI across platforms.</p><p>This approach allows you to share UI components between Android and iOS, providing a consistent design while reusing the same code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RKGMEkunY6iGd-7Ni0fXg.png" /></figure><p>Compose Multiplatform is particularly exciting because it simplifies the process of developing cross-platform UIs, making it easier to maintain consistency across your app’s look and feel.</p><p><strong>You still have the option to apply platform-specific tweaks where needed.</strong></p><h4>3. UI and Data Layer Separation: A Structured Approach</h4><p>One of the key benefits of <strong>Kotlin Multiplatform</strong> is its ability to fit into an <strong>existing architecture</strong>.</p><p>This diagram shows how a typical project can be layered into UI and Data Layers. Even <strong>without </strong>Kotlin Multiplatform, this structure helps in decoupling the different parts of the project, making it easier to update or refactor specific areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDSSaVgd1t8c3CcVU25VAw.png" /></figure><h4>4. Kotlin Multiplatform in the Data Layer</h4><p>Here, Kotlin Multiplatform is introduced into the <strong>Data Layer</strong>, enabling shared code for data handling across platforms.</p><p>With this approach, the Data Layer can be implemented once in Kotlin and reused across both iOS and Android, reducing duplication and keeping data-related logic consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eTxTryNedIe6at-Nqe9rtg.png" /></figure><h4>5. Kotlin Multiplatform in the Presentation Layer</h4><p>Moving further up the architecture stack, this diagram shows how Kotlin Multiplatform can be applied to the <strong>Presentation Layer</strong>, which includes both UI components and the logic that manages data presentation (e.g., ViewModels).</p><p>By sharing the Presentation Layer, you ensure that the way data is presented is uniform across platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOEDLWGUO7GlWOup4gXccg.png" /></figure><h4>6. Compose Multiplatform</h4><p>For cases where you want to share only the UI components, Kotlin Multiplatform can be applied using <strong>Compose Multiplatform</strong>.</p><p>This allows you to create and reuse UI code across platforms while keeping the business logic and data handling platform specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htY2JZXYGsRn-tFWQdbMVQ.png" /></figure><h4>7. Kotlin Multiplatform in both Presentation and Data Layer</h4><p>In this approach, Kotlin Multiplatform is applied to both the <strong>Presentation Layer</strong> (UI and ViewModel logic) and the <strong>Data Layer</strong>.</p><p>This allows for significant code reuse, covering both the business logic and the data-handling mechanisms, while the UI is also shared through Compose Multiplatform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66-MRTl2gZLa2tU_UxnT5g.png" /></figure><h3>Final Thoughts</h3><p>Kotlin Multiplatform is not just a tool for new projects; it’s a highly adaptable solution that can integrate into existing applications. By applying it layer by layer, you can take advantage of code sharing while maintaining the flexibility to customize platform-specific features where necessary.</p><p>For me, working with KMP has been a game-changer, and I’m excited to see how it evolves in the coming years. If you’re considering adopting Kotlin Multiplatform, start small — perhaps with the Data Layer or Domain Layer — and build from there. The flexibility, reusability, and incremental adoption model make it a powerful addition to any native mobile development project.</p><p>I’ve uploaded these diagrams, along with a few additional visual guides not included in this article, to my GitHub for reference and for fun.</p><p>Feel free to check them out <a href="https://github.com/TheSetox/kmp-sample-diagrams">here</a>, and if you find them useful, I’d appreciate it if you could give the repository a star!</p><p>Update: <strong>The second part, which dives into adding Kotlin Multiplatform across multiple modules, is now available as a member-only story.</strong> Check it out <a href="https://medium.com/@setoxsiapno/exploring-kotlin-multiplatform-a-visual-guide-part-2-multi-module-d1a34c883c8e">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734b85132d68" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/exploring-kotlin-multiplatform-a-visual-guide-734b85132d68">Exploring Kotlin Multiplatform: A Visual Guide</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Ways to Achieve Function Composition in Kotlin]]></title>
            <link>https://proandroiddev.com/different-ways-to-achieve-function-composition-in-kotlin-c99257341e26?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99257341e26</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 14:11:46 GMT</pubDate>
            <atom:updated>2023-09-01T04:49:06.971Z</atom:updated>
            <content:encoded><![CDATA[<h4>FUN [CTIONAL] PROGRAMMING SERIES</h4><h4>Function Composition Strategies: 8 Chess-Like Moves to Enhance Your Kotlin Skills with Function Composition</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oKste3ObGWuoUeXE" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Function composition is a powerful concept in programming where you combine multiple functions to create a new function.”</blockquote><p>Have you ever thought about programming as a bit like playing chess, where every choice you make can lead to either a win or a loss? Well, in the world of coding, function composition is the special technique that lets you blend simple actions together, kind of like how chess pieces come together in a master plan.</p><p>Now, picture yourself as a clever chess player in the world of coding with Kotlin. Kotlin offers you a bunch of nifty tools that are a bit like chess tactics — you can mix and match them to create your own coding strategies. In this article, we’re going to explore eight ways to combine functions in Kotlin. It’s a bit like learning different chess strategies, but for coding. These techniques give you various options, depending on how you like to approach your code. So, let’s dive right in and discover how you can juggle functions in Kotlin to make your code even smarter.</p><h3>Technique 1: Sequential Composition</h3><p><strong>What is it?</strong><br>This technique calls each function one after the other in a sequence. It’s like following steps in a recipe.</p><p><strong>Pros:</strong></p><ul><li>Simple and easy to understand.</li><li>Clear step-by-step execution.</li></ul><p><strong>Cons:</strong></p><ul><li>May become verbose with many functions.</li><li>Limited flexibility for complex compositions.</li></ul><p><strong><em>Example:</em></strong></p><pre>fun sayHelloToEveryone() {<br>    hello1()<br>    hello2()<br>    hello3()<br>    hello4()<br>    hello5()<br>}</pre><h3>Technique 2: Nested Function Invocation</h3><p><strong>What is it?</strong><br>Nested function invocation calls one function within another, creating a chain of function calls. It’s like opening a series of nested boxes.</p><p><strong>Pros:</strong></p><ul><li>Allows flexibility in composing functions.</li><li>Useful for creating complex workflows.</li></ul><p><strong>Cons:</strong></p><ul><li>Can become hard to read with deep nesting.</li><li>Doesn’t promote reusability.</li></ul><p><strong><em>Example:</em></strong></p><pre>fun sayHelloToEveryone2() {<br>    hello1(<br>        hello2(<br>            hello3(<br>                hello4(<br>                    hello5()<br>                )<br>            )<br>        )<br>    )<br>}</pre><h3>Technique 3: Declarative Nested Function Invocation</h3><p><strong>What is it?</strong><br>This approach combines nested function invocation with clear, declarative style. It’s like telling a story with a series of function calls.</p><p><strong>Pros:</strong></p><ul><li>Enhances readability and maintainability.</li><li>Supports a more expressive coding style.</li></ul><p><strong>Cons:</strong></p><ul><li>Still subject to deep nesting issues.</li><li>May require additional code for reusability.</li></ul><p><strong><em>Example:</em></strong></p><pre>fun sayHelloToEveryone3(): Int {<br>    val hello1 = hello1()<br>    val hello2 = hello2(hello1)<br>    val hello3 = hello3(hello2)<br>    val hello4 = hello4(hello3)<br>    return hello5(hello4)<br>}</pre><h3>Technique 4: Fluent Interface Style or Function Chaining</h3><p><strong>What is it?</strong><br>Fluent interface style allows functions to be chained together using a dot notation. It’s like a conveyor belt where each station performs a specific task.</p><p><strong>Pros:</strong></p><ul><li>Promotes a clean and fluent coding style.</li><li>Reduces nesting and enhances readability.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires additional code to support chaining.</li><li>May not work well for complex compositions.</li></ul><p><strong><em>Example:</em></strong></p><pre>fun sayHelloToEveryone4() {<br>    hello1()<br>        .hello2()<br>        .hello3()<br>        .hello4()<br>        .hello5()<br>}</pre><h3>Technique 5: Domain-Specific Language (DSL)</h3><p><strong>What is it?</strong><br>A DSL is a specialized language for a particular domain or problem. It allows you to create functions that read like a domain-specific language, enhancing expressiveness.</p><p><strong>Pros:</strong></p><ul><li>Enhances readability by creating a custom, domain-specific syntax.</li><li>Simplifies complex tasks in specific domains.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires designing and implementing a DSL.</li><li>May not be suitable for all projects.</li></ul><p><strong><em>Example:</em></strong></p><pre>// DSL creation<br>fun sayHello(init: HelloDSL.() -&gt; Unit): HelloDSL {<br>    val helloDSL = HelloDSL()<br>    helloDSL.init()<br>    return helloDSL<br>}<br><br><br>// DSL usage<br>fun main() {<br>    sayHello {<br>        hello1()<br>        hello2()<br>        hello3()<br>        hello4()<br>        hello5()<br>    }<br>}</pre><h3>Technique 6: Nested Higher-Order Function Invocation</h3><p><strong>What is it?</strong><br>Similar to nested function invocation, but with higher-order functions. It’s like passing functions as arguments to other functions within a chain.</p><p><strong>Pros:</strong></p><ul><li>Enables complex behavior composition.</li><li>Supports asynchronous or parallel execution.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires a solid understanding of higher-order functions.</li><li>Can lead to complex code when overused.</li></ul><p><strong><em>Example:</em></strong></p><pre>// Example creation of high order function<br>fun hello1(runFunction: () -&gt; Unit) {<br>    runFunction()<br>}<br><br>// Usage<br>fun sayHelloToEveryone5() {<br>    hello1 {<br>        hello2 {<br>            hello3 {<br>                hello4 {<br>                    hello5()<br>                }<br>            }<br>        }<br>    }<br>}</pre><h3>Technique 7: Function Composition Operators</h3><p><strong>What is it?</strong><br>Function composition operators like compose and andThen combine functions to create new functions. It&#39;s like building more advanced machinery from basic tools.</p><p><strong>Pros:</strong></p><ul><li>Promotes code reusability and readability.</li><li>Offers a clear and concise way to express function composition.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires familiarity with the operator syntax.</li><li>Limited to linear composition; may not handle complex branching well.</li></ul><p><strong><em>Example:</em></strong></p><pre>val composedHello = hello1 andThen hello2 andThen hello3<br>composedHello()</pre><h3>Technique 8: Using a List of Functions</h3><p><strong>What is it?</strong><br>Using a list of functions involves storing functions in a list and then iterating through the list to execute them. It’s like having a playlist of functions.</p><p><strong>Pros:</strong></p><ul><li>Allows dynamic selection and execution of functions.</li><li>Simplifies the management of multiple functions.</li></ul><p><strong>Cons:</strong></p><ul><li>Limited to predefined functions in the list.</li><li>May introduce overhead when maintaining a large list.</li></ul><p><strong><em>Example:</em></strong></p><pre>val helloFunctions = listOf(hello1, hello2, hello3, hello4, hello5)<br><br>fun sayHelloToEveryone6() {<br>    for (sayHello in helloFunctions) {<br>        sayHello()<br>    }<br>}</pre><h3>Ending Remarks</h3><p>In conclusion, achieving function composition in Kotlin is a bit like mastering different chess strategies. Depending on the complexity of your code and the expressiveness you need, you can choose from these eight techniques. Each has its own advantages and disadvantages, so it’s important to pick the one that suits your coding style and project requirements.</p><p>Just as a skilled chess player can adapt their strategy to any game, a proficient Kotlin coder can use these techniques to craft elegant and efficient code. So go ahead, experiment with these methods, and elevate your coding game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*naNtkFQgC6zyvaW5" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99257341e26" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/different-ways-to-achieve-function-composition-in-kotlin-c99257341e26">Different Ways to Achieve Function Composition in Kotlin</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extension Function: Extending Existing Power]]></title>
            <link>https://blog.stackademic.com/extension-function-extending-existing-power-90a3a1499dae?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a3a1499dae</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 00:08:12 GMT</pubDate>
            <atom:updated>2023-09-01T07:05:03.496Z</atom:updated>
            <content:encoded><![CDATA[<h4>FUN [CTIONAL] PROGRAMMING SERIES</h4><h4>Powering Up Your Code like an Extension Cord</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_PbFsLclfePiVw65" /><figcaption>Photo by <a href="https://unsplash.com/@david_thielen?utm_source=medium&amp;utm_medium=referral">David Thielen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>From time to time, I casually explore the job market. I find it best to apply when I’m not in a desperate job-seeking situation because it allows me to make logical decisions rather than hasty ones driven by urgency. Desperation can lead to dissatisfaction and accepting subpar offers. Having savings can provide some cushion, but what if you don’t?</p><p>The purpose of applying, besides finding opportunities, is self-assessment and learning from interviews. It’s a chance to understand your worth and gain insights from interviewers. Sometimes these experiences provide valuable lessons, while other times they don’t. Handling multiple interviews can also becomes a skill at this point.</p><p>But why am I sharing this? Well, recently, I applied to a particularly interesting company. Despite a somewhat lengthy process, it was enjoyable. Perhaps it was because it was my first time interacting with someone from another country, or maybe I simply enjoyed the conversation.</p><p>What caught my attention was the technical interview. The interviewer asked me about Kotlin concepts, which was fascinating since it was my first time discussing Kotlin concepts in an interview. While I anticipated this given the company’s focus, the question still caught me off guard. It was a basic Kotlin concept question, but it resonated with me.</p><p>I won’t delve into the entire Q&amp;A, but I’d like to focus on the topic of Extension Functions.</p><p><strong>“What is an extension function?” </strong>You might think it’s an easy question, and I described it as such, even providing usage examples. However, the next question left me puzzled, <strong>“Is that the only usage?”</strong> It was such a fundamental question, yet I couldn’t answer it confidently.</p><p>After the technical interview, instead of feeling disappointed by my answers, I felt excited. What excited me was the quest to learn more about kotlin concepts.</p><p>I realized I needed to revisit the basics and gain a deeper understanding. Now, it makes more sense to me. In the past, I would read about a concept and move on, thinking, <strong>“As long as I can use it, it doesn’t matter.”</strong> But now, some topics resonate more deeply with me. It’s more <strong>fulfilling</strong>.</p><p>My wish is for you to experience this <strong>sense of fulfillment</strong> too. While some of you may be experts, revisiting the basics can sometimes lead to “aha” moments you didn’t anticipate.</p><p>However, I understand it might seem counterproductive. That’s why it’s not just about revisiting the basics and rereading documentation.</p><p>To maximize productivity, we need to ask ourselves the right questions that align with our specific goals. I’m here to help with that. I’ll pose some questions and share my knowledge in the hope that they’ll be the ones you’re seeking, saving you from more extensive research.</p><h3>Extension Function is like an Extension Cord?</h3><p>Extension function is a way to add new functionality to an existing class without modifying its source code. You can think of it as “extending” the capabilities of a class.</p><p>Let’s now demonstrate some basic syntax for creating and using an Extension Function.</p><pre>// Create an Extension Function<br>fun String.customPrint() {<br>    println(&quot;Custom Print: $this&quot;)<br>}<br><br>// Basic Usage<br>val myString = &quot;Hello, World!&quot;<br>myString.customPrint() // This will print: &quot;Custom Print: Hello, World!&quot;</pre><h4>To gain a better understanding of extension functions, let’s craft an analogy.</h4><p>Imagine you’re in a room with a power outlet on one wall, and you need to plug in a device that’s just out of reach. What do you do? You grab an extension cord. That extension cord bridges the gap between your device and the power source, giving you the extra length you need to make things work.</p><p>In the world of programming, extension functions play a similar role. They’re like the extension cord of the coding universe. Just as an extension cord provides that extra reach for your devices, extension functions provide the flexibility to connect new functionality to existing classes or types. This means you can make your code reach further, accomplishing tasks that were once out of reach with standard libraries or classes. It’s like having a magic tool that lets you add new capabilities to familiar objects, making your code more versatile and adaptable.</p><h3>Examples Beyond Data Types and Android</h3><p>Creating an Extension Function isn’t confined to merely adding it as a regular function. Extension Functions, being functions themselves, offer the flexibility to manipulate and pass them around as they are first-class citizens in Kotlin.</p><p>Example syntax:</p><pre>// Extension function in the parameter<br>fun getPower(start: Power.() -&gt; Unit) {<br>  val power = Power()<br>  power.start()<br>}<br><br>// Extension function in a variable<br>val power : Power.() -&gt; String = this.getTitle() // You can remove `this`.<br><br>// Extension function when defining typealias<br>typealias Electricity = Power.() -&gt; String</pre><p>These are basic examples, and you can explore their versatility by using them in various contexts since they are functions.</p><p>The benefits of Extension Functions are truly remarkable. To gain a deeper understanding of them, let’s create more examples.</p><p>Before we dive into that, let’s talk about the examples provided by other developers. If you check other articles, you’ll notice that Extension Functions are commonly used with various data types, often crafted as utility classes, and frequently applied to extend Android-specific classes.</p><p>Extension functions are not limited to specific data types or Android-related tasks; their potential extends far beyond. Here are a few examples to illustrate their versatility:</p><ul><li><strong>Domain-Specific Extensions</strong>: You can create extension functions to add domain-specific methods to classes. For example, if you’re working on a financial application, you can extend the Money class with methods for currency conversion or financial calculations.</li></ul><pre>data class Book(val title: String, val author: String)<br><br>// Extension function to print book details<br>fun Book.printDetails() {<br>    println(&quot;Title: $title, Author: $author&quot;)<br>}<br><br>// Usage<br>val book = Book(&quot;Kotlin in Action&quot;, &quot;Dmitry Jemerov&quot;)<br>book.printDetails()</pre><ul><li><strong>Code Organization</strong>: Extension functions help keep your code organized by grouping related functionality with the types they operate on. This can make your codebase more maintainable and easier to navigate.</li></ul><pre>// Extension function to find the average of a list of integers<br>fun List&lt;Int&gt;.findAverage(): Double {<br>    return if (isEmpty()) 0.0 else sum() / size.toDouble()<br>}<br><br>// Usage<br>val numbers = listOf(10, 20, 30, 40, 50)<br>val average = numbers.findAverage()<br>println(&quot;Average: $average&quot;)</pre><ul><li><strong>DSL (Domain-Specific Language) Creation</strong>: Extensions are often used to create internal DSLs that allow you to define domain-specific languages for your applications. This can make your code more readable and expressive. An example is the use of extension functions to build HTML or XML documents.</li></ul><pre>// DSL for defining simple HTML elements<br>class HTML {<br>    private val elements = mutableListOf&lt;String&gt;()<br><br>    fun p(content: String) {<br>        elements.add(&quot;&lt;p&gt;$content&lt;/p&gt;&quot;)<br>    }<br><br>    fun h1(content: String) {<br>        elements.add(&quot;&lt;h1&gt;$content&lt;/h1&gt;&quot;)<br>    }<br><br>    fun build(): String {<br>        return elements.joinToString(&quot;\n&quot;)<br>    }<br>}<br><br>// Extension function for HTML DSL<br>fun html(init: HTML.() -&gt; Unit): String {<br>    val html = HTML()<br>    html.init()<br>    return html.build()<br>}<br><br>// Usage<br>val page = html {<br>    h1(&quot;Welcome to My Page&quot;)<br>    p(&quot;This is a sample page.&quot;)<br>}<br>println(page)</pre><ul><li><strong>Testing</strong>: Extensions are helpful in writing more readable test code. You can create extensions to testing frameworks to add custom assertions or simplify test setup.</li></ul><pre>// Extension function for testing assertions<br>fun &lt;T&gt; T.shouldBeEqualTo(expected: T) {<br>    if (this != expected) {<br>        throw AssertionError(&quot;$this is not equal to $expected&quot;)<br>    }<br>}</pre><ul><li><strong>Cleaner API Design</strong>: Extension functions can be used to create cleaner and more fluent APIs. For example, you can extend classes related to database access to provide a higher-level API for common database operations.</li></ul><pre>// Extension function for filtering unique elements in a list<br>fun &lt;T&gt; List&lt;T&gt;.filterUnique(): List&lt;T&gt; {<br>    val uniqueSet = mutableSetOf&lt;T&gt;()<br>    val result = mutableListOf&lt;T&gt;()<br>    for (item in this) {<br>        if (uniqueSet.add(item)) {<br>            result.add(item)<br>        }<br>    }<br>    return result<br>}<br><br>// Usage<br>val numbers = listOf(1, 2, 2, 3, 4, 4, 5)<br>val uniqueNumbers = numbers.filterUnique()<br>println(&quot;Unique Numbers: $uniqueNumbers&quot;)</pre><p>These are just a few basic examples of how you can apply Extension Functions. I encourage you to explore further and discover the versatility and power of Extension Functions for yourself.</p><h4>Trivia:</h4><blockquote>“Did you know that Extension Functions are a fundamental building block of Jetpack Compose? Without them, the elegant and concise Compose syntax that we love wouldn’t be possible!”</blockquote><h3>Reflecting on Extension Function</h3><p>Extension Function is really powerful. Much like an extension cord that brings power where needed, infuse versatility and extensibility into Kotlin. They empower us to augment existing classes with new functionalities, ensuring our code remains organized and our classes focused on their core responsibilities.</p><h4>Benefits of Extension Functions:</h4><ol><li><strong>Readability and Conciseness</strong>: Extension Functions enable code that reads like plain English. They can turn complex operations into one-liners, making our code more concise and comprehensible.</li><li><strong>Cleaner Code</strong>: By organizing related functions as extensions, we keep our classes focused and reduce clutter, leading to cleaner and more maintainable code.</li><li><strong>Functional Programming</strong>: Kotlin’s Extension Functions embrace functional programming principles, promoting immutability and ease of testing.</li><li><strong>Domain-Specific Languages</strong>: They allow us to create domain-specific languages within Kotlin, tailoring the language to our specific needs.</li></ol><h4>Debunking Misconceptions:</h4><ol><li><strong>Not Limited to Specific Types</strong>: While Extension Functions are often associated with extending common data types, they can be applied to user-defined classes, third-party libraries, and even non-data types, offering a wide range of possibilities.</li><li><strong>They Violate Encapsulation</strong>: Contrary to this belief, Extension Functions adhere to encapsulation principles. They don’t access private members and can’t violate the class’s integrity.</li><li><strong>Not Just Like Static Methods</strong>: Unlike static methods, Extension Functions are dispatched statically. They’re resolved at compile time based on the declared type, not at runtime like traditional polymorphism.</li><li><strong>Not Only for Standard Library Classes</strong>: Extension Functions can enhance any class, including user-defined ones. They’re not exclusive to standard library classes.</li><li><strong>They Are Slower</strong>: Extension Functions introduce minimal runtime overhead. The Kotlin compiler optimizes them effectively, ensuring they don’t significantly impact performance.</li></ol><p>In conclusion, Extension Functions are more than just a syntactic sugar; they are a <strong>catalyst</strong> for writing <em>clean</em>, <em>expressive</em>, and<em> highly readable code</em>. Much like an extension cord brings power to distant corners, Extension Functions extend the capabilities of Kotlin.</p><blockquote><strong><em>Embrace them, explore their potential, and let them enhance your coding experience.</em></strong></blockquote><p>If you haven’t already, I’ve started a new series, and this article is part of it. If you’re interested in learning more about what future articles might be in this series, I recommend checking out my initial story where I discussed launching the series.</p><p><a href="https://medium.com/@setoxsiapno/starting-the-fun-a-fun-ctional-programming-series-484a0472fd2c">Starting the Fun — A Fun[ctional] Programming Series</a></p><p><em>Thank you for reading until the end. Please consider following the writer and this publication. Visit </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a3a1499dae" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/extension-function-extending-existing-power-90a3a1499dae">Extension Function: Extending Existing Power</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Igniting High-Order Thinking: Empowering Code with High-Order Functions]]></title>
            <link>https://proandroiddev.com/igniting-high-order-thinking-empowering-code-with-high-order-functions-493fcc994de3?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/493fcc994de3</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 14:53:16 GMT</pubDate>
            <atom:updated>2023-08-17T14:53:16.696Z</atom:updated>
            <content:encoded><![CDATA[<h4>FUN [CTIONAL] PROGRAMMING SERIES</h4><h4>Unlocking Code Potential: Embracing High-Order Functions for Creative Thinking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-XgF4lFg2H0ITt7J" /><figcaption>Photo by <a href="https://unsplash.com/@8moments?utm_source=medium&amp;utm_medium=referral">Simon Berger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wondered why we call it a <strong>“High-Order Function”</strong> in programming? The name sounds fancy, but there’s a reason behind it. To understand, let’s step into the world of math and logic.</p><p>In math, <strong>“order”</strong> means how complicated or organized something is. A <strong>“first-order” </strong>thing is basic, like simple math. A “<strong>second-order”</strong> thing involves more complex stuff. Now, in programming, <strong>“high-order”</strong> is a similar idea. It means something is more advanced and can do tricky things.</p><p>In languages like Kotlin, a high-order function is smart — it can use other functions as tools. This helps us write code that’s short, flexible, and can do many things. But wait, what’s this got to do with <strong>“high-order thinking”</strong>?</p><p>Well, high-order thinking is a brain skill. It’s about thinking deeper and smarter. It’s not just facts — it’s putting ideas together, solving puzzles, and making new stuff from old stuff. Just like high-order functions work with other functions, high-order thinking helps us solve big, complex problems.</p><p>Now, why do we care about all this? Because the world is getting trickier. Technology grows fast, and problems are harder. High-order thinking helps us face these challenges. It’s like having a super brain that can understand tough things and find cool solutions.</p><p>So, when we explore high-order functions in Kotlin, let’s see beyond the fancy name. Think about how <strong>“high-order” </strong>means complex and smart. Just like high-order functions make coding cool, high-order thinking makes our brains super. Together, they help us do amazing things we never thought possible.</p><h3>Exploring High-Order Functions and High-Order Thinking</h3><p>Before we explore, let us define what is high-order functions and high-order thinking.</p><p><strong>High-Order Function</strong>: A high-order function is a special type of function that can accept other functions as arguments or return them as results. In simpler terms, it’s a function that can work with other functions, treating them like any other data.</p><p><strong>High-Order Thinking</strong>: On the thinking side, high-order thinking refers to a way of approaching problems that involves breaking them down into smaller parts, analyzing relationships between these parts, and creatively assembling them to find solutions. It’s a structured and adaptable way of problem-solving that helps handle complex challenges effectively.</p><p>Combining high-order functions and high-order thinking means using functions that can manipulate other functions, while also thinking in a strategic and structured manner to solve intricate problems.</p><h4>Combining high-order functions and high-order thinking offers several benefits:</h4><p><strong>Organized Code</strong>: High-order functions help you create self-contained code units, making your codebase well-organized and easier to manage.</p><p><strong>Flexibility</strong>: Your code becomes dynamic and adaptable as you can swap functions in and out to handle different situations.</p><p><strong>Reduced Repetitio</strong>n: High-order functions eliminate redundancy by encapsulating common tasks, leading to a more concise and maintainable codebase.</p><p><strong>Clearer Intent</strong>: Your code becomes more expressive and easier to understand, as high-order functions allow you to focus on the core logic.</p><p><strong>Solving Complex Problems</strong>: Just as high-order thinking simplifies complex problems, high-order functions break down intricate code scenarios into manageable components. This combination empowers you to tackle intricate programming challenges with a structured and efficient approach, resulting in cleaner, more efficient, and robust code.</p><h3>But, how do we create a High-Order Function?</h3><p>Here’s a simple step-by-step guide on how to create a high-order function:</p><p>Step 1: Define the Higher-Order Function</p><pre>fun calculateTotal(<br>    prices: List&lt;Double&gt;, <br>    calculator: (List&lt;Double&gt;) -&gt; Double<br>): Double {<br>    return calculator(prices)<br>}</pre><p>Step 2: Create a Lambda Expression for Calculation</p><pre>val sumCalculator: (List&lt;Double&gt;) -&gt; Double = { prices -&gt;<br>    prices.sum()<br>}</pre><p>Step 3: Call the Higher-Order Function</p><pre>val prices = listOf(12.99, 8.75, 24.50, 10.0)<br>val totalAmount = calculateTotal(prices, sumCalculator)<br>println(&quot;Total amount: \$${totalAmount}&quot;)</pre><p>In this example, we’ve defined a higher-order function calculateTotal that takes a list of prices and a lambda expression calculator as parameters. The lambda expression defines an operation that takes a list of doubles and returns their sum.</p><p>We then create a lambda expression named sumCalculator that calculates the sum of prices in the list.</p><p>Finally, we call the calculateTotal function, passing in the prices list and the sumCalculator lambda as the calculator parameter. The function returns the total amount of the prices, which is then printed to the console.</p><p>This guide demonstrates how to create a high-order function that abstracts the calculation of the total amount using different calculation strategies, represented by lambda expressions. You can easily switch out the calculator parameter with other lambda expressions to perform different types of calculations on the price list.</p><h3>Practical Use Cases: Elevating Code with High-Order Functions</h3><ul><li><strong>Input Validation: Hiding Conditions — </strong>High-order functions can encapsulate input validation, abstracting away complex conditions and promoting code reusability.</li></ul><pre>fun validateInput(<br>    input: String, <br>    validation: (String) -&gt; Boolean<br>): Boolean {<br>    return validation(input)<br>}<br><br>// Example Usage<br>val userInput = &quot;HighOrder123&quot;<br>val isValid = validateInput(userInput) {<br>    it.length &gt;= 8 &amp;&amp; it.any { it.isDigit() }<br>}</pre><ul><li><strong>Data Filtering: Simplifying Filtering Logic — </strong>High-order functions simplify data filtering, reducing explicit loop statements and focusing on specific conditions.</li></ul><pre>val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)<br><br>// Example Usage<br>val evenNumbers = numbers.filter { it % 2 == 0 }</pre><ul><li><strong>Event Handling: Managing Dynamic Actions </strong>— High-order functions enable dynamic event handling, allowing addition and execution of various actions without complex branching.</li></ul><pre>class EventManager {<br>    private val eventActions = mutableListOf&lt;() -&gt; Unit&gt;()<br>    <br>    fun addAction(action: () -&gt; Unit) {<br>        eventActions.add(action)<br>    }<br>    <br>    fun startEvent() {<br>        eventActions.forEach { it() }<br>    }<br>}<br><br>// Example Usage<br>val royalEvent = EventManager()<br>royalEvent.addAction { println(&quot;Announcing Arrival of Royalty&quot;) }<br>royalEvent.addAction { println(&quot;Unveiling The Grand Banner&quot;) }<br>royalEvent.addAction { println(&quot;Feasting and Celebrations&quot;) }<br>royalEvent.startEvent()</pre><ul><li><strong>Data Transformation: Custom Mapping Logic — </strong>High-order functions simplify data transformation, abstracting mapping details and improving code clarity.</li></ul><pre>data class Product(val name: String, val price: Double)<br><br>val products = listOf(<br>    Product(&quot;Sword&quot;, 150.0), <br>    Product(&quot;Shield&quot;, 80.0), <br>    Product(&quot;Potion&quot;, 20.0)<br>)<br><br>// Example Usage<br>val discountedProducts = products.map { <br>    it.copy(price = it.price * 0.8) <br>}</pre><ul><li><strong>Asynchronous Operations: Handling Callbacks — </strong>High-order functions aid in managing asynchronous operations, encapsulating callback logic for better readability.</li></ul><pre>fun fetchDataFromServer(onDataReceived: (String) -&gt; Unit) {<br>    // Simulating server response<br>    val data = &quot;Data from the server&quot;<br>    onDataReceived(data)<br>}<br><br>// Example Usage<br>fetchDataFromServer { data -&gt; println(&quot;Received data: $data&quot;) }</pre><ul><li><strong>Dynamic Dispatch: Command Pattern — </strong>High-order functions facilitate dynamic dispatch, allowing the creation of flexible command-based systems.</li></ul><pre>interface Command {<br>    fun execute()<br>}<br><br>class RoyalCommand(private val action: () -&gt; Unit) : Command {<br>    override fun execute() {<br>        println(&quot;Royal Commander: Execute command!&quot;)<br>        action()<br>    }<br>}<br><br>// Example Usage<br>val royalOrders = listOf(<br>    RoyalCommand { println(&quot;Knight: Charge!&quot;) },<br>    RoyalCommand { println(&quot;Mage: Cast Spell!&quot;) },<br>    RoyalCommand { println(&quot;Archer: Ready Aim Fire!&quot;) }<br>)<br><br>royalOrders.forEach { it.execute() }</pre><h3>Take away</h3><p>In the world of programming, innovation is driven by the ability to think creatively and apply existing tools in new and dynamic ways. High-order functions, like versatile tools in a craftsman’s workshop, empower us to harness the full potential of our code. Just as high-order thinking enables us to approach complex problems with flexibility and ingenuity, high-order functions equip us with the means to build more elegant, adaptable, and efficient solutions.</p><p>By incorporating high-order functions into our development toolkit, we unlock a realm of possibilities:</p><ol><li><strong>Abstraction and Modularity:</strong> High-order functions abstract complex operations, enabling us to focus on the core logic and intentions of our code. This modularity enhances code readability, simplifies debugging, and promotes reusability.</li><li><strong>Reduced Code Duplication:</strong> Encapsulating common patterns within high-order functions eliminates redundant code. This not only streamlines the development process but also minimizes the potential for errors.</li><li><strong>Enhanced Flexibility</strong>: High-order functions facilitate dynamic behavior by allowing us to pass functions as arguments or return functions as results. This empowers us to adapt our code to different scenarios and requirements effortlessly.</li><li><strong>Clearer Intent</strong>: By utilizing high-order functions, we express the purpose of our code more explicitly. Function names reflect the intended behavior, making the code self-documenting and easier to comprehend.</li><li><strong>Improved Testing and Debugging</strong>: High-order functions contribute to more focused unit testing. Each function can be tested independently, leading to a more comprehensive and effective testing process.</li><li><strong>Efficient Problem Solving</strong>: High-order functions break down complex problems into manageable components, mirroring the approach of high-order thinking. This modular structure simplifies development and encourages more creative solutions.</li><li><strong>Code Evolution</strong>: As our applications evolve, high-order functions make adapting and extending existing codebases smoother and less error-prone. New functionality can be added without disrupting the established code structure.</li></ol><p>In essence, the utilization of high-order functions aligns with the principles of high-order thinking, enabling us to approach our code with adaptability, clarity, and creativity. As we’ve seen in our exploration, high-order functions are not just tools; they are a mindset shift that empowers us to create more elegant and powerful software solutions. By fostering this practice, we not only elevate our code but also elevate ourselves as thoughtful and innovative programmers, ready to tackle the challenges of the ever-evolving digital landscape. So, as we embark on our coding journeys, let us embrace high-order functions as our allies, equipping us to craft code that is not only functional but also beautifully designed and deeply insightful.</p><blockquote>“Thinking like a king in a castle, high-order thinking constructs a crown of clarity, adorned with the gems of creativity and innovation. Just as a kingdom flourishes under a wise ruler, our code thrives when shaped by the majestic principles of high-order functions.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*buRQ2j681w_M_NWz" /><figcaption>Photo by <a href="https://unsplash.com/@gvantsajavakhishvili?utm_source=medium&amp;utm_medium=referral">Gvantsa Javakhishvili</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493fcc994de3" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/igniting-high-order-thinking-empowering-code-with-high-order-functions-493fcc994de3">Igniting High-Order Thinking: Empowering Code with High-Order Functions</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starting the Fun — A Fun[ctional] Programming Series]]></title>
            <link>https://medium.com/@setoxsiapno/starting-the-fun-a-fun-ctional-programming-series-484a0472fd2c?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/484a0472fd2c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 03:47:02 GMT</pubDate>
            <atom:updated>2023-08-17T06:45:47.911Z</atom:updated>
            <content:encoded><![CDATA[<h4>FUN [CTIONAL] PROGRAMMING SERIES</h4><h3>Starting the Fun — A Fun[ctional] Programming Series</h3><h4>Embarking on a Joyful Journey Through Functional Programming in Kotlin</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lqDper07EmwoEbUX" /><figcaption>Photo by <a href="https://unsplash.com/@edoronila?utm_source=medium&amp;utm_medium=referral">Esperanza Doronila</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’m excited to introduce a new series alongside the Fluent and Fun Clean Architecture journey — the Fun Programming Series.</p><p>This series is geared towards enhancing our comprehension of the fundamental principles that make Functional Programming in Kotlin an enjoyable experience.</p><p>Throughout this series, we’ll incorporate relatable analogies into the discussion, making it easier to grasp complex concepts.</p><p>However, if you’re searching for an exhaustive, step-by-step implementation guide for various Functional Programming concepts, you might want to explore other resources.</p><p>Instead, this series aims to simplify concepts and facilitate my own learning process, while offering you a clearer grasp of these ideas in straightforward terms.</p><p>For more in-depth practical guides, consider the official Kotlin website and resources like “Functional Programming in Kotlin” books.</p><h3>Here’s a sneak peek of the exciting topics that you can look forward to in the Fun Programming Series</h3><ol><li><strong>High-Order Function Unveiled</strong>: We’ve already explored the world of high-order functions and high-order thinking, setting the stage for our journey.</li><li><strong>The Power of Extension Functions</strong>: Discover how extension functions can make your code more elegant and adaptable.</li><li><strong>Mastering Function Composition</strong>: Dive into the art of combining functions to create more complex and versatile operations.</li><li><strong>Nesting Functions for Efficiency:</strong> Learn how to nest functions to improve code organization and readability.</li><li><strong>Lambda Expressions Demystified</strong>: Unravel the mystery behind lambda expressions and their role in simplifying your code.</li><li><strong>Understanding Pure Functions</strong>: Explore the concept of pure functions and their impact on predictability and reliability.</li><li><strong>First-Class Functions in Action</strong>: Delve into first-class functions and how they empower you to treat functions as values.</li><li><strong>The Beauty of Generic Types</strong>: Demystify generic types and see how they enhance the flexibility and reusability of your code.</li><li><strong>Design Patterns with Functional Programming</strong>: Uncover how functional programming principles can breathe new life into classic design patterns.</li><li><strong>DSL Magic in Kotlin</strong>: Witness the wizardry of Domain-Specific Languages and how they streamline complex operations into simple, expressive code.</li><li><strong>Function Chaining Unleashed</strong>: Explore the art of chaining functions together for a concise and fluid coding experience.</li><li><strong>Function-First Development Philosophy</strong>: Embrace the mindset of function-first development and its impact on crafting robust and maintainable codebases.</li><li><strong>Destructuring Declarations Made Easy</strong>: Dive into the world of destructuring declarations and how they simplify data manipulation and extraction.</li></ol><p>I’m excited to share a glimpse of what’s coming up in this series. My goal is to bring you a new story every week, running alongside the Fluent and Fun Clean Architecture Series. Writing has become a hobby I’m eager to enhance and develop.</p><p>Good news: The High-Order Function story is on its way to ProAndroidDev for approval. Stay tuned for updates, and if it’s not accepted, don’t worry — we’ll still share it after we get feedback from ProAndroidDev.</p><p>But there’s more to come. Our journey is about to get even more practical. Once we’ve covered all the basics, we’ll roll up our sleeves and put our new knowledge to work in real scenarios, using tools like the Android SDK and try to replace it and use Functional Programming.</p><p>These upcoming stories are like practice sessions, helping us build up our skills and confidence in applying functional programming concepts. Think of it as building muscle memory for your brain, getting you ready to think and implement like a pro using these new techniques.</p><p>And don’t worry, they’re not meant to replace what you already know about the SDK. It’s all about the learning experience and getting to know more about Functional Programming.</p><p>Your support and engagement are crucial as we embark on this hands-on phase of our journey. Let’s have some insightful discussions and grow together!</p><blockquote>“Step by step, like building a castle, we’ll strengthen our programming skills, one story at a time.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FRuspZ7bPnk7kIKJ" /><figcaption>Photo by <a href="https://unsplash.com/@phammi?utm_source=medium&amp;utm_medium=referral">MI PHAM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=484a0472fd2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recreating UseCase: Embracing a Fluent and Fun Approach (2023)]]></title>
            <link>https://proandroiddev.com/recreating-usecase-embracing-a-fluent-and-fun-approach-2023-71e9aad43d89?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/71e9aad43d89</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 01:46:28 GMT</pubDate>
            <atom:updated>2023-08-17T06:41:13.996Z</atom:updated>
            <content:encoded><![CDATA[<h4>FLUENT AND FUN CLEAN ARCHITECTURE SERIES</h4><h4>Unleashing the Power of Functional Thinking and Modularity in Usecase Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v5vJGMPeQx7FzcYb" /><figcaption>Photo by <a href="https://unsplash.com/@alexkondratiev?utm_source=medium&amp;utm_medium=referral">Alex Kondratiev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now, let’s delve deeper into the process of making our use cases more fluent and enjoyable. In our previous <a href="https://medium.com/proandroiddev/transforming-usecase-embracing-fluent-and-functional-approach-2023-eba69d2117d6">article</a>, we discussed why we’re taking this approach, so we’ll skip rehashing that and focus on the practical steps.</p><p>Before we begin, let’s clarify our main goal and the criteria for achieving a truly fluent and enjoyable use case. To illustrate, let’s revisit the desired end result.</p><pre>OrderUseCase.kt<br><br>fun OrderRepository.placeOrder() {<br>    whenUserLoggedIn {<br>        whenCartNotEmpty {<br>            withSufficientFunds {<br>                updateProductStock()<br>                clearCart()<br>            }<br>        }<br>    }<br>}</pre><p>Based on this desired outcome, there are specific criteria we need to meet:</p><ol><li><strong>Function-First Development</strong>: Start by creating functions before building classes in the use case. Treat functions as key elements in Kotlin programming.</li><li><strong>Pure Functions</strong>: Strive to create pure functions, meaning they don’t get affected by side effects. This ensures reliability and predictability in how functions behave.</li><li><strong>Utilize High-Order Functions</strong>: Leverage high-order functions to enhance the capabilities of your functions and enable more flexible and dynamic behavior.</li><li><strong>Function Composition</strong>: Combine functions to craft new functions. This helps build more complex behavior from simpler building blocks.</li></ol><p>In essence, these criteria revolve around Functional Programming. To embrace this approach, we need to shift our mindset, focusing on creating use cases centered on functions before introducing other concepts like classes.</p><h3>Exploring the Process of Recreating a Use Case</h3><p>Before we delve into the exploration, let’s provide some additional context about what an OrderRepository is. In this context, an OrderRepository is like a blueprint or a set of rules. It’s not a complete piece of code itself, but rather a guide for creating the code.</p><pre>interface OrderRepository {<br>    fun isLoggedIn(): Boolean<br>    <br>    fun getCart(): List&lt;Order&gt;<br>    <br>    fun hasEnoughFunds(price: Double): Boolean<br>    <br>    fun updateProductStock(order: Order)<br>    <br>    fun clearCart()<br><br>    fun getTotalPrice(): Double<br><br>    fun getConfirmedOrderDetails(): ConfirmedOrderDetails()<br>}</pre><p>We will now start on giving simple example to illustrate the concept and understand how it applies to real-world situations. Let’s start to shift our focus towards how I organized and reconstructed the use case within the framework of Fluent and Fun Clean Architecture.</p><p>After delving into functional programming, I began to investigate ways to enhance my use case. I initiated the code below, which shares similarities with my second article on Fluent and Fun Clean Architecture.</p><pre>fun placeOrderUseCase(orderRepository: OrderRepository) {<br>    if (orderRepository.isLoggedIn()) {<br>        val cart = orderRepository.getCart()<br>        if (cart.isNotEmpty()) {<br>            if (orderRepository.hasEnoughFunds(getTotalPrice())) {<br>                orderRepository.updateProductStock()<br>                orderRepository.clearCart()<br>            } else {<br>                throw InsufficientFundsException(<br>                    &quot;Not enough funds in the wallet.&quot;<br>                )<br>            }<br>        } else {<br>            throw EmptyCartException(&quot;The cart is empty.&quot;)<br>        }<br>    } else {<br>        throw NotLoggedInException(&quot;User is not logged in.&quot;)<br>    }<br>}</pre><p>This already meets our criteria, but the code contains three layers of nested if-else conditions. While the code is clear, it could be more readable.</p><p>To enhance simplicity, we can wrap these conditional statements. How can we achieve this?</p><h4>Take advantage of High-order function and Lamda Expressions</h4><p>Let’s gradually transition the code. We’ll begin with isLoggedIn. To encapsulate the condition, we’ll leverage high-order functions.</p><pre>fun placeOrderUseCase(orderRepository: OrderRepository) {<br>    executeWhenUserLoggedIn(orderRepository) {<br>        val cart = orderRepository.getCart()<br>        if (cart.isNotEmpty()) {<br>            if (orderRepository.hasEnoughFunds(getTotalPrice())) {<br>                orderRepository.updateProductStock()<br>                orderRepository.clearCart()<br>            } else {<br>                throw InsufficientFundsException(<br>                    &quot;Not enough funds in the wallet.&quot;<br>                )<br>            }<br>        } else {<br>            throw EmptyCartException(&quot;The cart is empty.&quot;)<br>        }<br>    }<br>}<br><br>private fun executeWhenUserLoggedIn(<br>    orderRepository: OrderRepository,<br>    executeFunction: () -&gt; Unit<br>) {<br>    if (orderRepository.isLoggedIn()) executeFunction()<br>    else throw NotLoggedInException(&quot;User is not logged in.&quot;)<br>}</pre><p>The executeWhenUserLoggedIn function takes two parameters: orderRepository and executeFunction. The executeFunction parameter is a higher-order function that accepts a lambda expression with no input parameters and no return value (represented as () -&gt; Unit).</p><p>Here’s how the code works:</p><ol><li>The placeOrderUseCase function is called with the orderRepository parameter.</li><li>Inside placeOrderUseCase, the executeWhenUserLoggedIn function is invoked with the orderRepository parameter and a lambda expression as the executeFunction.</li><li>The executeWhenUserLoggedIn function checks if the user is logged in using the orderRepository.isLoggedIn() function. If the user is logged in, it executes the provided executeFunction.</li><li>In this case, the executeFunction is the lambda expression defined in the placeOrderUseCase function. This lambda expression contains the logic to place an order if the user is logged in and the cart is not empty. If any conditions are not met, appropriate exceptions are thrown.</li></ol><p>In summary, the code uses a higher-order function (executeWhenUserLoggedIn) and a trailing lambda expression to ensure that the order placement logic is executed only when the user is logged in. This approach helps make the code more modular and readable by separating the authentication logic from the specific use case logic.</p><h4>That’s the initial condition. Now, let’s move on to the next one, which deals with the cart.</h4><pre>fun placeOrderUseCase(orderRepository: OrderRepository) {<br>    executeWhenUserLoggedIn(orderRepository) {<br>        executeWhenCartNotEmpty(orderRepository) {<br>            if (orderRepository.hasEnoughFunds(getTotalPrice())) {<br>                orderRepository.updateProductStock()<br>                orderRepository.clearCart()<br>            } else {<br>                throw InsufficientFundsException(<br>                    &quot;Not enough funds in the wallet.&quot;<br>                )<br>            }<br>        }<br>    }<br>}<br><br>private fun executeWhenCartNotEmpty(<br>    orderRepository: OrderRepository,<br>    executeFunction: () -&gt; Unit<br>) {<br>    val cart = orderRepository.getCart()<br>    if (cart.isNotEmpty()) executeFunction()<br>    else throw EmptyCartException(&quot;The cart is empty.&quot;)<br>}</pre><p>The purpose of executeWhenCartNotEmpty is to encapsulate the common logic of checking if the cart is empty before performing an action. By using this function, we can ensure that the action is only executed when the cart is not empty, and we avoid duplicating the same cart-empty check in different parts of the code.</p><p>In the context of the placeOrderUseCase function, we&#39;re using the executeWhenCartNotEmpty function to ensure that the order placement logic is only executed when the cart is not empty. This approach promotes code reusability, readability, and modularity, as each step of the process is encapsulated in its own function, making the code easier to understand and maintain.</p><h4>Following that, we can now move forward to the final condition, which verifies whether the user has sufficient funds to complete the order.</h4><pre>fun placeOrderUseCase(orderRepository: OrderRepository) {<br>    executeWhenUserLoggedIn(orderRepository) {<br>        executeWhenCartNotEmpty(orderRepository) {<br>            executeWithSufficientFunds(orderRepository) {<br>                orderRepository.updateProductStock()<br>                orderRepository.clearCart()<br>            }<br>        }<br>    }<br>}<br><br>private fun executeWithSufficientFunds(<br>    orderRepository: OrderRepository,<br>    executeFunction: () -&gt; Unit<br>) {<br>    val totalPrice = getTotalPrice()<br>    if (orderRepository.hasEnoughFunds(totalPrice))<br>        executeFunction()<br>    else throw InsufficientFundsException(<br>        &quot;Not enough funds in the wallet.&quot;<br>    )<br>}</pre><p>The code is taking the shape we’re aiming for in a use case. However, readability remains a concern as we repeatedly use the OrderRepository.</p><p>To address this, we introduce a new concept: Extension Functions. These functions let us call a function on an object without needing to explicitly mention the receiver or use the &#39;this&#39; keyword. This will further enhance the clarity of our code.</p><h3>Empowering UseCases with Extension Functions</h3><p>Kotlin’s extension functions offer a way to expand the capabilities of existing classes. By employing extension functions, we can refine our order placement logic, resulting in a streamlined and well-organized arrangement. The following code demonstrates how extension functions can significantly improve the clarity and modularity of our use case implementation. This enhancement leads to a more polished and efficient codebase.</p><p>Now, let’s implement these principles in the <strong>private</strong> methods we’ve established. The code will adopt the following structure:</p><pre>fun placeOrderUseCase(orderRepository: OrderRepository) {<br>    orderRepository.run {<br>        executeWhenUserLoggedIn {<br>            executeWhenCartNotEmpty {<br>                executeWithSufficientFunds {<br>                    updateProductStock()<br>                    clearCart()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>private fun OrderRepository.executeWhenUserLoggedIn(<br>    executeFunction: () -&gt; Unit<br>) {<br>    if (isLoggedIn()) executeFunction()<br>    else throw NotLoggedInException(&quot;User is not logged in.&quot;)<br>}<br><br>private fun OrderRepository.executeWhenCartNotEmpty(<br>    executeFunction: () -&gt; Unit<br>) {<br>    val cart = getCart()<br>    if (cart.isNotEmpty()) executeFunction()<br>    else throw EmptyCartException(&quot;The cart is empty.&quot;)<br>}<br><br>private fun OrderRepository.executeWithSufficientFunds(<br>    executeFunction: () -&gt; Unit<br>) {<br>    val totalPrice = getTotalPrice()<br>    if (hasEnoughFunds(totalPrice))<br>        executeFunction()<br>    else throw InsufficientFundsException(<br>        &quot;Not enough funds in the wallet.&quot;<br>    )<br>}</pre><p>The changes we made help us better understand what’s needed for placing an order. However, having OrderRepository.run inside the placeOrder might not fit perfectly. To improve this, we can also turn PlaceOrder into an extension function. To do this, let’s update the code like this:</p><pre>OrderUseCase.kt<br><br>fun OrderRepository.placeOrderUseCase() {<br>    executeWhenUserLoggedIn {<br>        executeWhenCartNotEmpty {<br>            executeWithSufficientFunds {<br>                updateProductStock()<br>                clearCart()<br>            }<br>        }<br>    }<br>}</pre><p>This now looked like the end result that we are expecting. We just need to refactor the function names to clean it up so that it is aligned in our end result. So overall the OrderUseCase file looks like this:</p><pre>OrderUseCase.kt<br><br>// Main UseCase for placing an order.<br>fun OrderRepository.placeOrder() {<br>    whenUserLoggedIn {<br>        whenCartNotEmpty {<br>            withSufficientFunds {<br>                updateProductStock()<br>                clearCart()<br>            }<br>        }<br>    }<br>}<br><br>private fun OrderRepository.whenUserLoggedIn(executeFunction: () -&gt; Unit) {<br>    if (isLoggedIn()) executeFunction()<br>    else throw NotLoggedInException(&quot;User is not logged in.&quot;)<br>}<br><br>private fun OrderRepository.whenCartNotEmpty(executeFunction: () -&gt; Unit) {<br>    val cart = getCart()<br>    if (cart.isNotEmpty()) executeFunction()<br>    else throw EmptyCartException(&quot;The cart is empty.&quot;)<br>}<br><br>private fun OrderRepository.withSufficientFunds(<br>    executeFunction: () -&gt; Unit<br>) {<br>    val totalPrice = getTotalPrice()<br>    if (hasEnoughFunds(totalPrice)) executeFunction()<br>    else throw InsufficientFundsException(<br>     &quot;Not enough funds in the wallet.&quot;<br>    )<br>}</pre><p>This now looks great. This is aligned with our criteria to achieve fluent and fun clean architecture. We have taken advantage of high-order functions, trailing lambda, function composition and extension function.</p><h4>But you may wonder, isn’t it more straightforward and short to use the nested conditional statement instead of this?</h4><p>Using straightforward nested conditionals is okay for simple tasks, but it can become messy as your program gets bigger. It may lead to repeating code, testing problems, and trouble handling errors consistently.</p><p>However, there’s a better way:</p><p>By using higher-order functions, you can already see what placeOrder is doing. It makes your code more organized and reusable. By breaking down the order process into smaller functions like whenUserLoggedIn, whenCartNotEmpty, and withSufficientFunds, you gain benefits like:</p><ul><li><strong>Modularity</strong>: Each function handles a specific check, making your code easier to manage.</li><li><strong>Reusability</strong>: You can use these functions in different parts of your app, reducing repetition.</li><li><strong>Readability</strong>: Named functions give a clear overview of the order process.</li><li><strong>Error Handling</strong>: Errors are managed centrally, leading to consistent error messages.</li><li><strong>Testing</strong>: Testing becomes simpler and more effective.</li></ul><p>In short, while simple nested conditionals work for small things, using higher-order functions offers a cleaner and more flexible solution. It keeps your code neat, encourages reuse, and ensures better quality, especially as your app grows.</p><h3>Experiment Time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dKzJTR3EQmlHaBG6" /><figcaption>Photo by <a href="https://unsplash.com/@talhahassan116?utm_source=medium&amp;utm_medium=referral">Talha Hassan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s put our setup to the test by adding a new request. Imagine that now, along with placing the order, we also need to make sure the order is confirmed and then proceed with the transaction.</p><p>To make this happen, we’re going to break down the order process into three main steps: <em>checkout</em>, <em>confirm order</em>, and <em>execute the transaction</em>. This helps us keep things organized and easy to manage.</p><p>Here’s how the code will look with these changes:</p><pre>fun OrderRepository.doCheckout() {<br>    whenUserLoggedIn {<br>        whenCartNotEmpty { <br>            println(&quot;Can proceed to next step&quot;) <br>        }<br>    }<br>}<br><br>fun OrderRepository.confirmOrder() {<br>    whenUserLoggedIn {<br>        whenCartNotEmpty {<br>            getConfirmedOrderDetails()<br>        }<br>    }<br>}<br><br>fun OrderRepository.finishOrderTransaction() {<br>    whenUserLoggedIn {<br>        whenCartNotEmpty {<br>            withSufficientFunds {<br>                updateProductStock()<br>                clearCart()<br>            }<br>        }<br>    }<br>}</pre><p>The way we’ve organized these functions helps us see the order process more clearly. You might notice we do similar checks, like if a user is logged in or if the cart is empty, in different steps. This may seem like repeating ourselves, but it’s actually quite helpful.</p><p>Here’s why it’s a good thing:</p><p><strong>Easy to Understand</strong>: Breaking down the order process into different functions, such as doCheckout, confirmOrder, and doOrderTransaction, makes it easier to see what&#39;s happening. Even if you&#39;re not familiar with the nitty-gritty details, you can follow the main steps.</p><p><strong>Simple to Change</strong>: Each step has its own function, which makes it simpler to change or add new things without messing up the rest of the code. This makes sure we don’t accidentally cause problems somewhere else.</p><p><strong>Works in Different Situations:</strong> This approach is like building with Lego blocks. If we need to add or change something, it’s like putting in a new Lego piece. The names of the functions also tell us what’s going on, which helps when we’re working together with others or coming back to the code later.</p><p>In a real situation, we might not need to do the same checks every time. For example, in confirmOrder and doOrderTransaction, we could skip some of the checks we did before. But the code we&#39;ve got here is like a practice run to show how the pieces fit together.</p><p>In summary, the seemingly repeated patterns serve a <strong><em>purpose</em></strong> and offer significant benefits in terms of organization, clarity, and future maintainability of the code. While you might not always need all the checks in every step, the design’s flexibility accommodates real-world variations.</p><h3>Wrapping Up: Navigating the Road Ahead</h3><p>As we draw this exploration to a close, we’ve embarked on a meaningful journey toward enhancing our architectural approach. We’ve delved into the realm of <em>fluent and fun clean architecture, unraveling the power of high-order functions, extension functions, and functional composition</em>. This path has illuminated a clearer understanding of how to structure use cases and bring modularity to the forefront.</p><p>Our architectural journey has taken a significant turn thanks to valuable feedback. Initially, we placed extension functions within the repository, but we’ve learned the value of keeping domain logic in the domain layer itself. This change makes things clearer, separates responsibilities, and avoids confusion.</p><p>However, our journey continues with many paths ahead and unanswered questions. How do we put these refined use cases into practice? How do we handle dependencies gracefully? Also, we didn’t touch on using the <strong>Result</strong> construct in our earlier discussion. Don’t worry, we’ll address all of this in the upcoming chapters of our architectural story.</p><p>But our exploration doesn’t end here. Our <strong><em>next article</em></strong> will dive into <strong><em>testing methods</em></strong> to confirm our architectural choices. Plus, we’re excited to showcase a real project that brings together all the concepts we’ve explored. Remember, this series is an ongoing adventure, and your insights and feedback shape our shared knowledge.</p><p>Before we wrap up, a big thank you for your interest and feedback. Your thoughts are like gems on our path of learning and progress. As we move ahead, let’s remember:</p><blockquote>“Any intelligent fool can make things bigger and more complex….. It takes a touch of genius — and a lot of courage to move in the opposite direction.” — Albert Einstein</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A4dYqRsKjOvALvzD" /><figcaption>Photo by <a href="https://unsplash.com/@slidebean?utm_source=medium&amp;utm_medium=referral">Slidebean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71e9aad43d89" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/recreating-usecase-embracing-a-fluent-and-fun-approach-2023-71e9aad43d89">Recreating UseCase: Embracing a Fluent and Fun Approach (2023)</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring a Software Engineer’s Mind]]></title>
            <link>https://medium.com/@setoxsiapno/exploring-a-software-engineers-mind-240c9f9bea34?source=rss-65e22711389e------2</link>
            <guid isPermaLink="false">https://medium.com/p/240c9f9bea34</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[journaling]]></category>
            <category><![CDATA[life-lessons]]></category>
            <category><![CDATA[self-awareness]]></category>
            <dc:creator><![CDATA[Stephen Siapno]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 04:30:30 GMT</pubDate>
            <atom:updated>2023-08-04T07:27:14.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cvA8JBEhr6Co4uzT" /><figcaption>Photo by <a href="https://unsplash.com/@intricateexplorer?utm_source=medium&amp;utm_medium=referral">Intricate Explorer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>“Explore — travel in or through (an unfamiliar country or area) in order to learn about or familiarize oneself with it.”</blockquote><p>Software Engineering is like embarking on a daring expedition or exploring an unfamiliar place with unpredictable condition.</p><p>It is an adventure not meant for everyone, as many may find the journey difficult, tiring and intimidating. It is also very scary to explore something that you don’t know.</p><p>I wouldn’t blame them, who would want to explore unfamiliar places? Just thinking about it makes me uncomfortable.</p><p>Yet, for those who dare to take on the challenges. — a thrilling, long and adventurous journey awaits.</p><p>Like any explorer setting foot on unfamiliar ground, software engineers begin their quest with excitement and anticipation. When starting a new project, with every line of code written and each problem solved, the allure of the journey attracts them further and further.</p><p>But you will encounter problems and challenges in your journey. Like <strong>Mud</strong>, a very dirty and sticky situation. This situation is like exploring a messy codebase or even a tightly coupled situation. Even experience explorer will have a hard time on walking this path. This can slow you down, requires you a lot of effort and can make you mad because all of that dirty code.</p><p>Mud is the least of your worries. You will also encounter <strong>unpredictable weather.</strong> Rain or shine, it will definetly take you by surprise. Like an ever-changing requirements and demands in your projects.</p><p>That is only nature.</p><p>The nature of work you will be working on.</p><p>The beginning of a journey as I might say.</p><p>But as night comes, a very cold and dark night. Exploring the wilderness at night is nerve-racking. You will never know what will happen in a legacy code and untested solution. There might be different kinds of insects, mosquitos, worms or any bugs I might say?</p><p>Night time is also for predators to prey. It might be waiting or it might aggressively attack you. One thing for sure, there is a predator lurking.</p><p>I will leave it to your imagination who will be those in your life and what might happen if you let them.</p><p>But to give you some tip, they will show if you overstay in your journey or you become too much comfortable.</p><p>A journey that is tiring indeed. When you get tired, you need to get some rest or you can also eat or drink if you are hungry or thirsty. That is part of the journey.</p><p>But be careful on how you manage your sleep and supplies.</p><p>Remember, taking care of yourself is crucial. Adequate knowledge and rest are your supplies for the long haul. But beware, taking shortcuts or neglecting your well-being is a risky move that might backfire later.</p><p>But with all of this problem and challenges you will face, the greatest battle you’ll face is within <strong>yourself</strong>.</p><p>Your doubt will always whispers,</p><p>“Am I good enough?”</p><p>“What if I can’t finish it?”</p><p>“There is someone much better than me.”</p><p>“I’m stupid.”</p><p>“I can’t do this.”</p><p>“What if I just stop this?”</p><p>A very challenging journey indeed.</p><p>If you let it control you, it will truly drag you down the hill.</p><p>This story offers a glimpse into the mind of one Software Engineer’s journey. Every Software Engineer faces unique challenges and experiences, just like exploring various terrains and weather conditions. I can’t represent all Software Engineers, but this is my personal journey.</p><p>This brief account provides insight into the thoughts and perspectives that a Software Engineer may encounter, allowing you to understand their world better.</p><p>Starting with awareness is a great approach to navigate your journey as a Software Engineer. Being mindful of your thoughts and mental state allows you to gain better clarity and understanding of your challenges and goals.</p><p>Similar to decluttering physical spaces, decluttering your mind can help you focus on what truly matters. Prioritize important thoughts and tasks, and let go of distractions or unnecessary worries.</p><p>For example, I started writing as my new hobby. Despite not considering myself a skilled writer, this practice has helped me create a new hobby and declutter my mind by jotting down my thoughts. Writing doesn’t require making it public; I simply put my thoughts in my notes. The important thing is that I am channeling and organizing my thoughts through writing.</p><p>You can also turn to coding as a way to declutter your thoughts if your ideas revolve around coding projects. It’s essential to remember that the goal isn’t perfection or completeness; it’s about expressing and organizing your thoughts. Embrace the process and enjoy the act of creating, whether it’s writing, coding, or any other form of expression. By decluttering your mind and channeling your thoughts into tangible projects, you’ll find a sense of clarity and accomplishment along your journey as a Software Engineer.</p><p>Remember, the journey of a Software Engineer is an ongoing process of growth and discovery. Embrace each step, be kind to yourself, and continue exploring the ever-evolving world of software engineering.</p><h3>End</h3><p>Follow me on my Journey as a Software Engineer.</p><p><a href="https://medium.com/@setoxsiapno">Stephen Siapno - Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240c9f9bea34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>