<?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[Arpalar Tech - Medium]]></title>
        <description><![CDATA[အာပလာ့စွမ်းအားဖြင့် ပြည်ထွန်းကားစေရမည် - Medium]]></description>
        <link>https://medium.com/arpalar-tech?source=rss----6d53a7e11b53---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Arpalar Tech - Medium</title>
            <link>https://medium.com/arpalar-tech?source=rss----6d53a7e11b53---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:32:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/arpalar-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ Genie: Bringing AI Power Into Your Terminal — No Cloud, No Subscriptions]]></title>
            <link>https://medium.com/arpalar-tech/genie-bringing-ai-power-into-your-terminal-no-cloud-no-subscriptions-7e903d385234?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/7e903d385234</guid>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 13:26:13 GMT</pubDate>
            <atom:updated>2025-11-07T13:40:21.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧞 Genie: Bringing AI Power Into Your Terminal — No Cloud, No Subscriptions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWe599umSm8SIrtTs66c2w.png" /></figure><p>Most junior developers feel intimidated by the Linux terminal. Commands look cryptic, flags confusing, and one typo can break things.What if your terminal could act like a friendly AI genie — guiding you, completing commands safely, and warning you before you do something dangerous?</p><p>That’s what this project does.<br> <strong>Genie 🧞</strong> is an AI-powered command-completion assistant that runs right inside your terminal — no cloud, no monthly subscription, completely offline on your own machine.</p><p>Genie listens to what you’re typing and offers a smart, safe completion when you press a hotkey (like Ctrl+G in Zsh).</p><ul><li><strong>🧠 Suggests completions</strong> for partial commands (e.g. you type ls - → Genie offers ls -lh --color=auto)</li><li><strong>⚠️ Warns about dangerous commands</strong> such as rm -rf, dd, or mkfs</li><li><strong>🪄 Explains why it’s risky</strong> — in natural language, right inside your terminal</li><li><strong>🏠 Runs locally</strong> using an open-source LLM via <a href="https://ollama.ai/">Ollama</a> — so your data never leaves your laptop</li></ul><p>No API keys, no OpenAI subscriptions, no latency from cloud calls.</p><ul><li><strong>You type a partial command</strong><br> Genie watches your input buffer.</li><li><strong>Press your AI key</strong> (e.g., Ctrl + G)<br> The Zsh widget runs a small Python wrapper called ai_complete.py.</li><li><strong>Genie queries a local model</strong> (like qwen2.5-coder:7b through Ollama’s HTTP API).<br> The model predicts a completion string.</li><li><strong>Genie analyzes it</strong> with safety filters:</li><li>Regex patterns detect dangerous Linux operations (rm -rf, dd if=, curl | sh, etc.)</li><li>If safe → it auto-completes the command in your terminal.</li><li>If risky → it blocks the suggestion and prints a colorized warning card with an explanation.</li></ul><h3>Code Breakdown</h3><p>The magic lives in ~/.local/bin/ai_complete.py.</p><pre>#!/usr/bin/env python3<br># -*- coding: utf-8 -*-<br>&quot;&quot;&quot;<br>ai_complete.py — Genie 🧞 : AI-powered shell completion with safety &amp; style.<br><br>Usage:<br>  ai_complete.py &quot;&lt;partial-buffer&gt;&quot;<br>  ai_complete.py &quot;&lt;partial-buffer&gt;&quot; --reveal-danger<br><br>Behavior:<br>  - Uses a local LLM (HTTP endpoint) to suggest ONE shell command completion.<br>  - Detects dangerous patterns (rm -rf, dd, mkfs, curl|sh, etc).<br>  - If safe: prints the suggested command only (for your widget to insert).<br>  - If dangerous: blocks it and shows a modern, colored Genie safety card.<br>  - If dangerous + --reveal-danger: shows command + explanations with a heavy warning.<br>&quot;&quot;&quot;<br><br>import sys<br>import json<br>import re<br>import subprocess<br>import random<br>from typing import Tuple, List<br><br># =========================<br># CONFIG<br># =========================<br><br>HOST = &quot;http://localhost:11434&quot;       # Local LLM endpoint (e.g. Ollama)<br>MODEL = &quot;qwen2.5-coder:7b&quot;            # Model name<br>AI_NAME = &quot;Genie 🧞&quot;                  # Terminal AI name (no trailing ♂️)<br><br># ANSI colors<br>RED = &quot;\033[1;31m&quot;<br>YELLOW = &quot;\033[1;33m&quot;<br>CYAN = &quot;\033[1;36m&quot;<br>RESET = &quot;\033[0m&quot;<br>BOLD = &quot;\033[1m&quot;<br>DIM = &quot;\033[2m&quot;<br><br># =========================<br># BLACKLIST (danger patterns)<br># =========================<br><br>BLACKLIST = [<br>    r&#39;\brm\s+-rf\b&#39;,<br>    r&#39;\bsudo\s+rm\b&#39;,<br>    r&#39;\bdd\b\s+if=&#39;,<br>    r&#39;\bmkfs(\.\w+)?\b&#39;,<br>    r&#39;\b:?\(\)\s*\{\s*:\|\s*&amp;\s*;\s*\}\s*;\s*&#39;,  # fork bomb<br>    r&#39;curl\s+[^|]*\|\s*sh&#39;,<br>    r&#39;wget\s+[^|]*\|\s*sh&#39;,<br>    r&#39;\bshutdown\b&#39;,<br>    r&#39;\breboot\b&#39;,<br>    r&#39;\bpoweroff\b&#39;,<br>    r&#39;\bchmod\s+[^ ]+\s+/\b&#39;,<br>    r&#39;\bchown\s+-R\s+\w+\s+/\b&#39;,<br>    r&#39;\bmount\b\s+.*\s+/\b&#39;,<br>]<br><br>EXPLANATIONS = {<br>    &#39;rm -rf&#39;: &quot;Recursively deletes files without confirmation — easy to wipe critical data.&quot;,<br>    &#39;sudo rm&#39;: &quot;Runs deletion as root — bypasses protections and can destroy the system.&quot;,<br>    &#39;dd&#39;: &quot;Raw disk operations — a wrong target can irreversibly overwrite disks.&quot;,<br>    &#39;mkfs&#39;: &quot;(Re)formats a device/partition — destroys existing data.&quot;,<br>    &#39;curl|sh&#39;: &quot;Executes remote code directly — common malware / supply-chain risk.&quot;,<br>    &#39;fork bomb&#39;: &quot;Spawns endless processes — can freeze/crash the machine.&quot;,<br>    &#39;shutdown/reboot&#39;: &quot;Interrupts running services and work unexpectedly.&quot;,<br>    &#39;chmod / or chown /&#39;: &quot;Global permission/ownership changes at root can break your OS.&quot;,<br>}<br><br># =========================<br># HELPERS<br># =========================<br><br>def is_dangerous(text: str) -&gt; Tuple[bool, List[str]]:<br>    lowered = text.lower()<br>    labels: List[str] = []<br>    for pat in BLACKLIST:<br>        if re.search(pat, lowered):<br>            if &#39;sudo&#39; in pat:<br>                labels.append(&#39;sudo rm&#39;)<br>            elif &#39;rm&#39; in pat:<br>                labels.append(&#39;rm -rf&#39;)<br>            elif &#39;dd&#39; in pat:<br>                labels.append(&#39;dd&#39;)<br>            elif &#39;mkfs&#39; in pat:<br>                labels.append(&#39;mkfs&#39;)<br>            elif &#39;curl&#39; in pat or &#39;wget&#39; in pat:<br>                labels.append(&#39;curl|sh&#39;)<br>            elif &#39;fork&#39; in pat:<br>                labels.append(&#39;fork bomb&#39;)<br>            elif &#39;shutdown&#39; in pat or &#39;reboot&#39; in pat or &#39;poweroff&#39; in pat:<br>                labels.append(&#39;shutdown/reboot&#39;)<br>            elif &#39;chmod&#39; in pat or &#39;chown&#39; in pat:<br>                labels.append(&#39;chmod / or chown /&#39;)<br>            else:<br>                labels.append(&#39;dangerous-pattern&#39;)<br>    return (len(labels) &gt; 0, list(dict.fromkeys(labels)))<br><br><br>def explain_matches(labels: List[str]) -&gt; str:<br>    return &quot;\n&quot;.join(<br>        f&quot;- {label}: {EXPLANATIONS.get(label, &#39;Potentially destructive operation.&#39;)}&quot;<br>        for label in labels<br>    )<br><br><br>def call_llm(payload: dict) -&gt; str:<br>    &quot;&quot;&quot;<br>    Minimal HTTP client using curl. Expects: { &quot;response&quot;: &quot;...&quot; }.<br>    Adjust if your local endpoint differs.<br>    &quot;&quot;&quot;<br>    try:<br>        proc = subprocess.run(<br>            [<br>                &quot;curl&quot;, &quot;-sS&quot;,<br>                f&quot;{HOST}/api/generate&quot;,<br>                &quot;-H&quot;, &quot;Content-Type: application/json&quot;,<br>                &quot;-d&quot;, json.dumps(payload),<br>            ],<br>            capture_output=True,<br>            text=True,<br>            timeout=10,<br>        )<br>        if proc.returncode != 0:<br>            return &quot;&quot;<br>        data = json.loads(proc.stdout)<br>        return (data.get(&quot;response&quot;) or &quot;&quot;).strip()<br>    except Exception:<br>        return &quot;&quot;<br><br><br>def query_model(partial: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Ask Genie to complete the shell command safely.<br>    &quot;&quot;&quot;<br>    system = (<br>        f&quot;You are {AI_NAME}, a friendly, safety-conscious AI living inside the terminal. &quot;<br>        &quot;The user types partial shell commands; you suggest ONE safe completion. &quot;<br>        &quot;Rules: respond with exactly one shell command, no markdown, no prose. &quot;<br>        &quot;Avoid destructive patterns: rm -rf, sudo rm on critical paths, dd to devices, mkfs, &quot;<br>        &quot;piping remote scripts into sh, fork bombs, or similar. Prefer --help, -i, or harmless paths.&quot;<br>    )<br>    prompt = f&quot;Partial command:\n{partial}\n\nReturn only ONE completed safe shell command as a single line:&quot;<br>    payload = {&quot;model&quot;: MODEL, &quot;system&quot;: system, &quot;prompt&quot;: prompt, &quot;stream&quot;: False}<br><br>    resp = call_llm(payload)<br>    if not resp:<br>        return &quot;&quot;<br>    for line in resp.splitlines():<br>        line = line.strip()<br>        if line:<br>            return line<br>    return &quot;&quot;<br><br><br>def llm_safety_warning(labels: List[str]) -&gt; str:<br>    label_text = &quot;, &quot;.join(labels) if labels else &quot;dangerous command&quot;<br>    system = (<br>        f&quot;You are {AI_NAME}, an in-terminal safety assistant. &quot;<br>        &quot;Write ONE short, clear, modern warning about why this kind of command is risky, &quot;<br>        &quot;and suggest safer habits (like using --help, interactive flags, or backups). &quot;<br>        &quot;Do not output raw destructive commands.&quot;<br>    )<br>    prompt = f&quot;Dangerous elements: {label_text}. Return ONE sentence warning.&quot;<br>    payload = {&quot;model&quot;: MODEL, &quot;system&quot;: system, &quot;prompt&quot;: prompt, &quot;stream&quot;: False}<br>    resp = call_llm(payload)<br>    return &quot; &quot;.join(resp.splitlines()).strip() if resp else &quot;&quot;<br><br><br># =========================<br># MAIN<br># =========================<br><br>def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;&quot;, end=&quot;&quot;)<br>        return<br><br>    partial = sys.argv[1]<br>    reveal_flag = &quot;--reveal-danger&quot; in sys.argv[2:]<br><br>    suggestion = query_model(partial).strip()<br>    if not suggestion:<br>        print(&quot;&quot;, end=&quot;&quot;)<br>        return<br><br>    dangerous, labels = is_dangerous(suggestion)<br><br>    if dangerous:<br>        warning = llm_safety_warning(labels) or (<br>            &quot;This looks risky for your system. Double-check targets, use interactive flags, and keep backups.&quot;<br>        )<br><br>        icons = [&quot;⚠️&quot;, &quot;🚨&quot;, &quot;🧠&quot;, &quot;🛑&quot;]<br>        icon = random.choice(icons)<br>        divider = f&quot;{DIM}{&#39;-&#39; * 60}{RESET}&quot;<br>        footer = (<br>            f&quot;{DIM}Use &#39;--reveal-danger&#39; only if you fully understand the impact. ~ {AI_NAME}{RESET}&quot;<br>        )<br><br>        if reveal_flag:<br>            header = (<br>                f&quot;{RED}{BOLD}{icon} [{AI_NAME} SAFETY]{RESET} &quot;<br>                f&quot;{YELLOW}Dangerous completion revealed for review!{RESET}&quot;<br>            )<br>            details = explain_matches(labels)<br>            print(<br>                f&quot;\n{divider}\n&quot;<br>                f&quot;{header}\n&quot;<br>                f&quot;{CYAN}💡 Explanation:{RESET}\n{details}\n&quot;<br>                f&quot;{BOLD}Command (DO NOT RUN UNLESS YOU KNOW EXACTLY WHAT IT DOES):{RESET}\n&quot;<br>                f&quot;{suggestion}\n&quot;<br>                f&quot;{footer}\n{divider}\n&quot;<br>            )<br>        else:<br>            header = (<br>                f&quot;{RED}{BOLD}{icon} [{AI_NAME} SAFETY]{RESET} &quot;<br>                f&quot;{YELLOW}Blocked a risky command suggestion!{RESET}&quot;<br>            )<br>            tip = f&quot;{CYAN}💡 {warning}{RESET}&quot;<br>            print(<br>                f&quot;\n{divider}\n&quot;<br>                f&quot;{header}\n&quot;<br>                f&quot;{tip}\n&quot;<br>                f&quot;{footer}\n&quot;<br>                f&quot;{divider}\n&quot;<br>            )<br>        return<br><br>    # Safe suggestion<br>    print(suggestion)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Here’s what it does:</p><pre>AI_NAME = &quot;Genie 🧞&quot;<br>HOST = &quot;http://localhost:11434&quot;<br>MODEL = &quot;qwen2.5-coder:7b&quot;<br><br># Detects dangerous patterns<br>BLACKLIST = [r&#39;\brm\s+-rf\b&#39;, r&#39;\bdd\b\s+if=&#39;, r&#39;curl\s+[^|]*\|\s*sh&#39;]<br><br># Calls your local model<br>subprocess.run([&quot;curl&quot;, &quot;-sS&quot;, f&quot;{HOST}/api/generate&quot;, ...])<br><br># Outputs pretty, colored warnings for unsafe commands<br>print(f&quot;{RED}{BOLD}⚠️ [Genie 🧞 SAFETY]{RESET} Blocked a risky command!&quot;)</pre><p>Then in Zsh, you bind it:</p><pre>_ai_complete_widget() {<br>  local suggestion<br>  suggestion=$(ai-complete &quot;$BUFFER&quot; 2&gt;/dev/null)<br>  print -r -- &quot;\n$suggestion\n&quot;<br>  zle redisplay<br>}<br>zle -N _ai_complete_widget<br>bindkey &#39;^G&#39; _ai_complete_widget</pre><p>Now, pressing <strong>Ctrl+G</strong> triggers Genie.</p><h3>Why Run It Locally?</h3><p>Cloud-based AI terminals (like Warp or Fig) are amazing but require:</p><ul><li>Internet connection</li><li>Paid subscriptions or API keys</li><li>Sending snippets of your shell history to remote servers</li></ul><p>Running Genie locally with Ollama means:</p><ul><li><strong>Zero cost after setup</strong></li><li><strong>Full privacy</strong> — commands never leave your machine</li><li><strong>Faster responses</strong> after the model is loaded</li><li><strong>Customization</strong>: you can tweak the model, tone, or safety filters anytime.</li></ul><p><strong>Getting Started (Step-by-Step)</strong></p><p><strong>1.Install Ollama</strong></p><pre>curl -fsSL https://ollama.com/install.sh | sh</pre><p><strong>2.Run a local model</strong></p><pre>ollama pull qwen2.5-coder:7b</pre><p><strong>3.Save </strong><strong>ai_complete.py to </strong>~/.local/bin/ai_complete.py and make it executable:</p><pre>chmod +x ~/.local/bin/ai_complete.py</pre><p><strong>4. Add the Zsh keybinding</strong><br>Append this to your ~/.zshrc:</p><pre>zle -N _ai_complete_widget<br>bindkey &#39;^G&#39; _ai_complete_widget</pre><p><strong>5.Reload</strong></p><pre>source ~/.zshrc</pre><p>6.<strong> Try it , before you try press G</strong></p><pre>$ sudo rm -rf /<br>------------------------------------------------------------<br>⚠️ [Genie 🧞 SAFETY] Blocked a risky command suggestion!<br>💡 Deleting recursively with sudo may destroy system files. Use interactive flags or double-check paths.<br>Use &#39;--reveal-danger&#39; only if you fully understand the impact. ~ Genie 🧞<br>------------------------------------------------------------</pre><p>Genie literally stops you from self-destructing your file system. It’s like having a mentor watching over your shoulder, politely yelling, “Don’t you dare, my friend.”</p><p>Learning Linux as a junior dev can be daunting. Genie bridges that gap:<br>you get AI guidance <strong>without surrendering privacy or paying monthly fees</strong>.</p><p>It’s not just autocomplete — it’s <em>confidence</em>.<br>Genie makes the command line a little less scary, and a lot more magical.</p><p>The future of development tools isn’t just cloud-powered — it’s <em>developer-empowered</em>.With open-source local AI models, anyone can bring intelligent automation to their terminal.</p><p>Next time someone asks you about your setup, you can smile and say:</p><blockquote><em>“I’ve got a Genie in my terminal.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e903d385234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/genie-bringing-ai-power-into-your-terminal-no-cloud-no-subscriptions-7e903d385234">🧞 Genie: Bringing AI Power Into Your Terminal — No Cloud, No Subscriptions</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating Code Smells: Unveiling Issues and Crafting Solutions in Projects]]></title>
            <link>https://medium.com/arpalar-tech/navigating-code-smells-unveiling-issues-and-crafting-solutions-in-projects-b9449d1a4e16?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/b9449d1a4e16</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 19:25:10 GMT</pubDate>
            <atom:updated>2023-08-30T19:25:11.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*4CSwWAxy9Fo8MdrHGwB1Hw.jpeg" /></figure><p>Code smells are the subtle indicators of deeper issues within a codebase that, if left unchecked, can lead to decreased maintainability, increased complexity, and potential bugs.</p><p>In Kotlin projects, recognizing and addressing these code smells is paramount for producing clean, efficient, and maintainable code. This article explores some common code smells, their implications, and strategies for rectifying them to enhance the quality of Kotlin projects.</p><p><strong>Understanding What is Code Smells:</strong> Code smells are patterns in code that hint at potential design or implementation problems. They don’t necessarily equate to bugs but rather indicate areas that might benefit from refactoring.</p><p>Some prevalent code smells include long functions, duplicated code, large classes, primitive obsession, and inappropriate comments. Identifying these smells requires vigilance and a keen understanding of good software design principles.</p><p><strong>Long Functions:</strong> Long functions, often dubbed the “God functions,” perform too many tasks within a single block. This not only hampers readability but also makes maintenance a daunting task. Breaking down such functions into smaller, more focused units not only improves readability but also enhances reusability and maintainability.</p><pre>//Incorrect Example - Long Function for Wine Order: Code Smell<br>fun placeWineOrder(customer: Customer, items: List&lt;WineItem&gt;) {<br>    // Validate customer<br>    if (customer.name.isEmpty() || customer.age &lt; 18) {<br>        throw IllegalArgumentException(&quot;Invalid customer.&quot;)<br>    }<br>    <br>    // Calculate total price<br>    var totalPrice = 0.0<br>    for (item in items) {<br>        if (item.quantity &lt;= 0) {<br>            throw IllegalArgumentException(&quot;Invalid item quantity.&quot;)<br>        }<br>        totalPrice += item.price * item.quantity<br>    }<br>    <br>    // Apply discount<br>    if (totalPrice &gt; 200) {<br>        totalPrice *= 0.9<br>    }<br>    <br>    // Generate order details<br>    val orderDetails = StringBuilder()<br>    orderDetails.append(&quot;Order for ${customer.name}\n&quot;)<br>    for (item in items) {<br>        orderDetails.append(&quot;${item.quantity} x ${item.name}: $${item.price * item.quantity}\n&quot;)<br>    }<br>    orderDetails.append(&quot;Total price: $totalPrice&quot;)<br>    <br>    // Send order confirmation<br>    EmailService.sendEmail(customer.email, &quot;Order Confirmation&quot;, orderDetails.toString())<br>    <br>    // Update inventory<br>    for (item in items) {<br>        Inventory.updateQuantity(item, -item.quantity)<br>    }<br>    <br>    // Update customer points<br>    customer.points += (totalPrice / 10).toInt()<br>    Database.updateCustomer(customer)<br>}</pre><pre><br>//Correct Refactor - Breaking Down the Function for Wine Order<br>fun placeWineOrder(customer: Customer, items: List&lt;WineItem&gt;) {<br>    validateCustomer(customer)<br>    val totalPrice = calculateTotalPrice(items)<br>    applyDiscount(totalPrice)<br>    val orderDetails = generateOrderDetails(customer, items, totalPrice)<br>    sendOrderConfirmation(customer, orderDetails)<br>    updateInventory(items)<br>    updateCustomerPoints(customer, totalPrice)<br>}<br><br>fun validateCustomer(customer: Customer) {<br>    if (customer.name.isEmpty() || customer.age &lt; 18) {<br>        throw IllegalArgumentException(&quot;Invalid customer.&quot;)<br>    }<br>}<br><br>fun calculateTotalPrice(items: List&lt;WineItem&gt;): Double {<br>    return items.sumByDouble { it.price * it.quantity }<br>}<br><br>fun applyDiscount(totalPrice: Double) {<br>    if (totalPrice &gt; 200) {<br>        totalPrice *= 0.9<br>    }<br>}<br><br>fun generateOrderDetails(customer: Customer, items: List&lt;WineItem&gt;, totalPrice: Double): String {<br>    val orderDetails = StringBuilder()<br>    orderDetails.append(&quot;Order for ${customer.name}\n&quot;)<br>    for (item in items) {<br>        orderDetails.append(&quot;${item.quantity} x ${item.name}: $${item.price * item.quantity}\n&quot;)<br>    }<br>    orderDetails.append(&quot;Total price: $totalPrice&quot;)<br>    return orderDetails.toString()<br>}<br><br>fun sendOrderConfirmation(customer: Customer, orderDetails: String) {<br>    EmailService.sendEmail(customer.email, &quot;Order Confirmation&quot;, orderDetails)<br>}<br><br>fun updateInventory(items: List&lt;WineItem&gt;) {<br>    for (item in items) {<br>        Inventory.updateQuantity(item, -item.quantity)<br>    }<br>}<br><br>fun updateCustomerPoints(customer: Customer, totalPrice: Double) {<br>    customer.points += (totalPrice / 10).toInt()<br>    Database.updateCustomer(customer)<br>}</pre><p><strong>Duplicated Code:</strong> Duplicated code is a telltale sign of missed opportunities for abstraction and code reuse. These repeated blocks of code can lead to inconsistencies and errors when changes are required. Extracting common functionality into separate functions or classes promotes consistency, reduces the chances of errors, and eases maintenance efforts.</p><pre>//Code Smell<br>fun calculateCircleArea(radius: Double): Double {<br>    return 3.14 * radius * radius<br>}<br><br>fun calculateRectangleArea(width: Double, height: Double): Double {<br>    return 3.14 * width * height // Oops, copy-paste mistake<br>}</pre><pre>//Correct Refactor<br>fun calculateCircleArea(radius: Double): Double {<br>    return 3.14 * radius * radius<br>}<br><br>fun calculateRectangleArea(width: Double, height: Double): Double {<br>    return width * height<br>}</pre><p><strong>Large Classes:</strong> Large classes that handle numerous responsibilities violate the single responsibility principle. Such classes become difficult to understand and modify over time. Breaking them down into smaller, focused classes adhering to the single responsibility principle results in more modular and maintainable code.</p><pre>//Long Class - WineManager <br>class WineManager {<br>    fun addWine(wine: Wine) {<br>        // Add wine to database<br>    }<br><br>    fun updateWine(wine: Wine) {<br>        // Update wine details in database<br>    }<br><br>    fun calculateTotalRevenue() {<br>        // Calculate total revenue from all wines<br>    }<br><br>    fun processOrder(order: Order) {<br>        // Validate order, deduct quantities, update inventory, and send confirmation<br>    }<br><br>    fun generateSalesReport() {<br>        // Generate sales report with various statistics<br>    }<br><br>    // ... more methods related to wine management ...<br>}</pre><pre>//Refactored - Smaller, Focused Classes:<br>class WineCatalog {<br>    fun addWine(wine: Wine) {<br>        // Add wine to database<br>    }<br><br>    fun updateWine(wine: Wine) {<br>        // Update wine details in database<br>    }<br>}<br><br>class RevenueCalculator {<br>    fun calculateTotalRevenue() {<br>        // Calculate total revenue from all wines<br>    }<br>}<br><br>class OrderProcessor {<br>    fun processOrder(order: Order) {<br>        // Validate order, deduct quantities, update inventory, and send confirmation<br>    }<br>}<br><br>class SalesReportGenerator {<br>    fun generateSalesReport() {<br>        // Generate sales report with various statistics<br>    }<br>}</pre><p><strong>Primitive Obsession:</strong> Primitive Obsession involves using primitive data types for complex domain concepts, leading to a lack of clarity and increased error risk. By creating dedicated classes to encapsulate domain concepts and their behavior, such as a Currency class, developers enhance code clarity, type safety, and maintainability.</p><pre>// Wrong: Using primitive types for currencies<br>val usdAmount: Double = 100.0<br>val eurAmount: Double = 80.0<br>val exchangeRateToUSD: Double = 1.18<br><br>// Performing calculations without type safety or clarity<br>val totalAmount: Double = usdAmount + (eurAmount * exchangeRateToUSD)<br>println(&quot;Total amount in USD: $totalAmount&quot;)</pre><pre>// Correct: Using a dedicated Currency class<br>class Currency(val code: String, val exchangeRateToUSD: Double) {<br>    fun convertToUSD(amount: Double): Double {<br>        return amount * exchangeRateToUSD<br>    }<br>}<br><br>fun main() {<br>    val usd = Currency(&quot;USD&quot;, 1.0)<br>    val eur = Currency(&quot;EUR&quot;, 1.18)<br>    val amountInEur = 80.0<br><br>    // Using the Currency class for conversions<br>    val amountInUSD = eur.convertToUSD(amountInEur)<br>    println(&quot;Amount in USD: $amountInUSD&quot;)<br>}</pre><p><strong>Inappropriate Comments:</strong> Inappropriate or excessive comments often indicate that the code is not self-explanatory. Rather than cluttering the code with comments, striving for self-documenting code with meaningful variable and function names makes the codebase more readable and reduces the need for comments that can become outdated.</p><pre>//Code Smell - Inappropriate Comments:<br>class WineManager {<br>    // This is the WineManager class<br>    // It manages various wine-related functionalities<br>    // Constructor for creating a new WineManager instance<br>    constructor() {<br>        // Initialize the WineManager instance<br>    }<br><br>    // Method to add a wine to the catalog<br>    fun addWine(wine: Wine) {<br>        // Code to add the wine to the catalog<br>    }<br>    <br>    // Method to update the wine details<br>    // Takes a Wine object as parameter<br>    fun updateWine(wine: Wine) {<br>        // Code to update the wine details<br>    }<br><br>    // ... other methods with similar comments ...<br>}</pre><pre>//Refactored - Clearer Code, Concise Comments:<br>class WineManager {<br>    constructor() {<br>        // Initialize the WineManager<br>    }<br><br>    fun addWine(wine: Wine) {<br>        // Add the wine to the catalog<br>    }<br>    <br>    fun updateWine(wine: Wine) {<br>        // Update the wine details<br>    }<br><br>    // ... other methods without redundant comments ...<br>}</pre><p><strong>Long Parameter Lists:</strong> Functions with too many parameters can become confusing, and it’s often a sign that the function is trying to do too much.</p><pre>//Code Smell : Long Parameter<br>fun processWineOrder(<br>    customerId: Int,<br>    customerName: String,<br>    customerEmail: String,<br>    wines: List&lt;Wine&gt;,<br>    quantities: List&lt;Int&gt;,<br>    isPreferredCustomer: Boolean,<br>    shippingAddress: String,<br>    billingAddress: String<br>) {<br>    // Process the order using the provided parameters<br>}</pre><pre>//Refactored - Introducing a Data Class:<br>data class WineOrder(<br>    val customer: Customer,<br>    val items: List&lt;OrderItem&gt;,<br>    val shippingAddress: String,<br>    val billingAddress: String<br>)<br><br>data class Customer(<br>    val id: Int,<br>    val name: String,<br>    val email: String,<br>    val isPreferred: Boolean<br>)<br><br>data class OrderItem(<br>    val wine: Wine,<br>    val quantity: Int<br>)<br><br>fun processWineOrder(order: WineOrder) {<br>    // Process the order using the encapsulated details<br>}</pre><p><strong>Strategies for Solving Code Smells</strong>: Addressing code smells requires a strategic approach:</p><ol><li><strong>Code Reviews:</strong> Regular code reviews with colleagues can identify code smells that might be overlooked.</li><li><strong>Refactoring:</strong> Dedicate time for refactoring to systematically eliminate code smells while maintaining functionality.</li><li><strong>Code Analysis Tools:</strong> Leverage tools like Detekt in your build process to automatically spot code smells.</li><li><strong>Documentation and Training:</strong> Educate your team about code smells, their implications, and best practices to avoid them.</li></ol><p>Code smells are like signposts guiding developers toward more maintainable and efficient code. Recognizing these smells and understanding how to address them is a vital skill for any developer.</p><p>By actively identifying and rectifying code smells, projects can be elevated to new levels of readability, maintainability, and quality. Ultimately, the pursuit of clean code is an ongoing journey, where vigilance and a commitment to improvement lead to software that not only works but works well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9449d1a4e16" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/navigating-code-smells-unveiling-issues-and-crafting-solutions-in-projects-b9449d1a4e16">Navigating Code Smells: Unveiling Issues and Crafting Solutions in Projects</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amplifying Flavor Customization with Kotlin Extensions: Crafting Tailored Experiences]]></title>
            <link>https://medium.com/arpalar-tech/amplifying-flavor-customization-with-kotlin-extensions-crafting-tailored-experiences-f113933e174e?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/f113933e174e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 18:11:38 GMT</pubDate>
            <atom:updated>2023-08-25T01:01:52.543Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin stands out for its elegance, conciseness, and versatility. One of its most remarkable features is extensions, which empower developers to augment existing classes with new functionality without altering their source code.</p><p>Today I will show how we can use the Kotlin extension for different flavors, in our Android application. Here is an example of a simple compose app showing as “<strong>Android</strong>” when running</p><pre>import android.os.Bundle<br>import androidx.activity.ComponentActivity<br>import androidx.activity.compose.setContent<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.material3.MaterialTheme<br>import androidx.compose.material3.Surface<br>import androidx.compose.material3.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.tooling.preview.Preview<br>import com.indexer.extenstionforeasy.ui.theme.ExtenstionForEasyTheme<br><br><br>class MainActivity : ComponentActivity() {<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContent {<br>      ExtenstionForEasyTheme {<br>        // A surface container using the &#39;background&#39; color from the theme<br>        Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {<br>          Greeting(&quot;Android&quot;)<br>        }<br>      }<br>    }<br>  }<br>}<br><br><br>@Composable<br>fun Greeting(<br>  name: String,<br>  modifier: Modifier = Modifier<br>) {<br>  Text(<br>    text = &quot;Hello $name!&quot;,<br>    modifier = modifier<br>  )<br>}<br><br>@Preview(showBackground = true)<br>@Composable<br>fun GreetingPreview() {<br>  ExtenstionForEasyTheme {<br>    Greeting(&quot;Android&quot;)<br>  }<br>}</pre><p>Now I want to add flavor and based on the flavor I want to show “<strong>Champagne</strong>” and “<strong>Melot</strong>” so I added the flavor in the application gradle as below</p><pre>plugins {<br>  id &#39;com.android.application&#39;<br>  id &#39;org.jetbrains.kotlin.android&#39;<br>}<br><br>android {<br>  namespace &#39;com.indexer.extenstionforeasy&#39;<br>  compileSdk 34<br><br>  defaultConfig {<br>    applicationId &quot;com.indexer.extenstionforeasy&quot;<br>    minSdk 24<br>    targetSdk 34<br>    versionCode 1<br>    versionName &quot;1.0&quot;<br><br>    testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>    vectorDrawables {<br>      useSupportLibrary true<br>    }<br>  }<br><br>  flavorDimensions &quot;wine&quot;<br><br>  productFlavors {<br>    champagne {<br>      dimension &quot;wine&quot;<br>      applicationIdSuffix &quot;.champagne&quot;<br>    }<br><br>    melot {<br>      dimension &quot;wine&quot;<br>      applicationIdSuffix &quot;.melot&quot;<br>    }<br>  }<br><br>  buildTypes {<br>    release {<br>      minifyEnabled false<br>      proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>    }<br>  }<br>  compileOptions {<br>    sourceCompatibility JavaVersion.VERSION_1_8<br>    targetCompatibility JavaVersion.VERSION_1_8<br>  }<br>  kotlinOptions {<br>    jvmTarget = &#39;1.8&#39;<br>  }<br><br>  sourceSets {<br>    champagne {<br>      java {<br>        srcDirs &#39;src/champange/java&#39;<br>      }<br>    }<br>    melot {<br>      java {<br>        srcDirs &#39;src/melot/java&#39;<br>      }<br>    }<br><br>  }<br><br>  buildFeatures {<br>    compose true<br>  }<br>  composeOptions {<br>    kotlinCompilerExtensionVersion &#39;1.3.2&#39;<br>  }<br>  packagingOptions {<br>    resources {<br>      excludes += &#39;/META-INF/{AL2.0,LGPL2.1}&#39;<br>    }<br>  }<br>}<br><br>dependencies {<br><br>  implementation &#39;androidx.core:core-ktx:1.10.1&#39;<br>  implementation platform(&#39;org.jetbrains.kotlin:kotlin-bom:1.8.0&#39;)<br>  implementation &#39;androidx.lifecycle:lifecycle-runtime-ktx:2.6.1&#39;<br>  implementation &#39;androidx.activity:activity-compose:1.7.2&#39;<br>  implementation platform(&#39;androidx.compose:compose-bom:2022.10.00&#39;)<br>  implementation &#39;androidx.compose.ui:ui&#39;<br>  implementation &#39;androidx.compose.ui:ui-graphics&#39;<br>  implementation &#39;androidx.compose.ui:ui-tooling-preview&#39;<br>  implementation &#39;androidx.compose.material3:material3&#39;<br>  testImplementation &#39;junit:junit:4.13.2&#39;<br>  androidTestImplementation &#39;androidx.test.ext:junit:1.1.5&#39;<br>  androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.5.1&#39;<br>  androidTestImplementation platform(&#39;androidx.compose:compose-bom:2022.10.00&#39;)<br>  androidTestImplementation &#39;androidx.compose.ui:ui-test-junit4&#39;<br>  debugImplementation &#39;androidx.compose.ui:ui-tooling&#39;<br>  debugImplementation &#39;androidx.compose.ui:ui-test-manifest&#39;<br>}</pre><p>Now we have two new flavors champagne and merlot as you in below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhlV3o6r8Sbh4hDi3f_RnQ.png" /></figure><p>Flavoring allows for the creation of distinct versions of an app tailored to different scenarios, such as countries, features, or environments.</p><p>While flavors bring numerous benefits, managing them without the aid of extensions can introduce challenges that impact code maintainability, readability, and overall development efficiency.</p><p>1. <strong>Code Duplication:</strong> Without extensions, developers often resort to duplicating code across different flavors to accommodate varying requirements. This duplication can lead to increased maintenance efforts and the risk of inconsistencies or bugs when changes are made in one flavor but not propagated to others.</p><p>2.<strong> Reduced Readability</strong>: Lacking the encapsulation that extensions provide, code becomes more verbose and less readable. Multiple if-else conditions or separate classes may be used to handle different flavors, resulting in convoluted code that is harder to understand and debug.</p><p>3.<strong> Maintenance Complexity</strong>: The absence of extensions can amplify the complexity of maintaining multiple flavor-specific implementations. Updating a common piece of functionality requires modifications across different parts of the codebase, increasing the likelihood of introducing errors.</p><p>4. <strong>Inconsistent Naming Conventions:</strong> Without extensions, developers might create separate classes or methods for each flavor, which can lead to inconsistencies in naming conventions. This inconsistency can make it difficult for developers to predict where to find specific functionality within the codebase.</p><p>5. <strong>Long Build Times</strong>: In cases where flavors are managed without extensions, build times can be negatively impacted due to duplicate code and resources being compiled separately for each flavor. This can lead to longer compilation times, slowing down the development process.</p><p>6.<strong> Collaboration Challenges:</strong> Collaborating with a team on a project with multiple flavors, but lacking extensions, can be challenging. Team members may need to navigate through disparate parts of the codebase, leading to communication gaps and difficulties in understanding the project’s structure.</p><p>7. <strong>Prone to Errors</strong>: Handling flavor-specific logic without extensions increases the likelihood of introducing errors or omitting necessary functionality. Manual replication of code across flavors can lead to inconsistencies and difficult-to-trace bugs.</p><p>8. <strong>Inefficiency in Resource Management</strong>: Flavors often involve different resources such as layouts, strings, and assets. Managing these resources without extensions can result in redundant files, making it harder to keep track of which resources are shared and which are flavor-specific.</p><p>9. <strong>Limited Reusability:</strong> Without extensions, the lack of a consistent approach for handling flavor-specific functionality can limit code reusability. Developers may avoid reusing code if it requires significant modifications for each flavor.</p><p>10. <strong>Difficulty in Scaling</strong>: As the app evolves and more flavors are added, the challenges of managing flavors without extensions can become increasingly pronounced. Scaling up the project becomes more complex and time-consuming.</p><p>so let me refactor with the activity as below and add an extension</p><pre>//In main app i am update get string title instead of hard code<br>class MainActivity : ComponentActivity() {<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContent {<br>      ExtenstionForEasyTheme {<br>        // A surface container using the &#39;background&#39; color from the theme<br>        Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {<br>          Greeting(getStringTitle())<br>        }<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IA02SWQ2Xm0oKho2IkHNWQ.png" /></figure><pre>//That is title for Champagne flavor<br>internal fun MainActivity.getStringTitle(): String {<br>  return &quot;Champagne&quot;<br>}<br><br>//That is title for Melot flavor<br>internal fun MainActivity.getStringTitle(): String {<br>   return &quot;Melot&quot;<br>}</pre><p>Now you notice we did not need another activity in flavor and reduced the duplication of code, Also our tests are unique between different flavors. here is the benefit of using an extension</p><p><strong>Advantages of Kotlin Extensions:</strong></p><ol><li><strong>Enhanced Readability: </strong>Extensions allow developers to encapsulate logic within a specific type, making the codebase more intuitive and self-explanatory. This improves code readability and comprehension, especially for domain-specific operations.</li><li><strong>Encapsulation and Separation of Concerns:</strong> Extensions enable a cleaner separation of concerns. Related functionality can be encapsulated within extensions, reducing the need for utility classes or scattered code snippets. This contributes to a more modular and organized codebase.</li><li><strong>Compatibility and Adaptability:</strong> One of the key advantages of extensions is their compatibility with external classes. Developers can enrich classes from libraries or APIs without modifying the original source code. This adaptability is invaluable for integrating third-party libraries seamlessly.</li><li><strong>Maintainability:</strong> Kotlin extensions decouple the extended functionality from the core class, minimizing the risk of introducing bugs when upgrading libraries or changing dependencies. This leads to greater code stability and easier maintenance.</li><li><strong>Code Reusability:</strong> Extensions foster code reuse by allowing developers to define functions that can be utilized across various parts of the application. This reduces redundancy and promotes a more efficient development process.</li><li><strong>Improved Collaboration:</strong> Extensions lead to more standardized and consistent code. When used in a team setting, they can simplify collaboration by establishing common patterns and reducing the learning curve for new team members.</li><li><strong>Less Boilerplate:</strong> Kotlin extensions help reduce boilerplate code by abstracting common operations. This leads to shorter, more focused code snippets, which ultimately speeds up development and minimizes the potential for errors.</li><li><strong>Tailored Functionality: </strong>Extensions enable developers to customize classes to better fit project requirements. They can add convenience methods, validation checks, or any other features that align with specific use cases.</li></ol><p>Now already in 2023, Are you still creating duplicate activity in different flavors, let&#39;s move the way to be cleaner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f113933e174e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/amplifying-flavor-customization-with-kotlin-extensions-crafting-tailored-experiences-f113933e174e">Amplifying Flavor Customization with Kotlin Extensions: Crafting Tailored Experiences</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Drag-and-Drop Functionality in Compose]]></title>
            <link>https://medium.com/arpalar-tech/exploring-drag-and-drop-functionality-in-compose-665576ba89a0?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/665576ba89a0</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[compose-ui]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 19:01:02 GMT</pubDate>
            <atom:updated>2023-08-13T19:01:02.511Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the ongoing personal project of Pomodoro you can see all source code here <a href="https://github.com/indexer/TimeOutTask"><strong>Github</strong></a><strong>, </strong>In this project, I am using TOML for library dependencies management, Koin.</p><p>For this project, I add the helper class to support drag-and-drop functionality in compose. In app design, user interaction plays a pivotal role in engaging the audience. The PomodoroListScreen is a prime example of this, showcasing how Jetpack Compose empowers developers to create a smooth and intuitive user experience. By integrating drag-and-drop capabilities, the code enhances user interaction by allowing effortless reordering of list items.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F854164855%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F854164855&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1710016211-0f51447d144dc853f551d5bef725158057db4eca89c9e8d713f36ec5700097c2-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1440" height="3120" frameborder="0" scrolling="no"><a href="https://medium.com/media/e24489fdb410cb84298b5247999c13cb/href">https://medium.com/media/e24489fdb410cb84298b5247999c13cb/href</a></iframe><p><strong>Structure and Composition:</strong></p><p>The PomodoroListScreen function serves as the central point of the component. It takes three parameters: items, onMove, and an optional modifier. The items parameter holds the list of data to be displayed, while onMove is a callback triggered during item movement. The modifier parameter allows customization of the UI&#39;s appearance.</p><p>Inside the function, several key components are utilized to create the interactive list:<br>Coroutine Scope and State: coroutineScope and mutableItems are declared using the remember function. These enable efficient coroutine management and state persistence across recompositions.</p><ol><li><strong>Coroutine Scope and State</strong>: coroutineScope and mutableItems are declared using the remember function. These enable efficient coroutine management and state persistence across recompositions.</li><li><strong>Drag-and-Drop State:</strong> dragDropListState is obtained using the rememberDragDropListState function. This encapsulates the logic required for drag-and-drop behavior, improving code modularity.</li><li><strong>LazyColumn:</strong> This Composable element displays the list of items. It receives the drag gesture handler modifier and the drag-and-drop state as parameters. Additionally, the state of the LazyColumn is set to the drag-and-drop state&#39;s LazyListState.</li></ol><p><strong>Drag Gesture Handling:</strong></p><p>The following code defines an extension function, dragGestureHandlerthat creates a Modifier for handling drag gestures. It takes the CoroutineScope ItemListDragAndDropStateand an overscrollJob as parameters. This function uses Compose&#39;s pointer input system to detect drag gestures after a long press.</p><pre>fun Modifier.dragGestureHandler(<br>  scope: CoroutineScope,<br>  itemListDragAndDropState: ItemListDragAndDropState,<br>  overscrollJob: MutableState&lt;Job?&gt;<br>): Modifier = this.pointerInput(Unit) {<br>  detectDragGesturesAfterLongPress(<br>    onDrag = { change, offset -&gt;<br>      change.consume()<br>      itemListDragAndDropState.onDrag(offset)<br>      handleOverscrollJob(overscrollJob, scope, itemListDragAndDropState)<br>    },<br>    onDragStart = { offset -&gt; itemListDragAndDropState.onDragStart(offset) },<br>    onDragEnd = { itemListDragAndDropState.onDragInterrupted() },<br>    onDragCancel = { itemListDragAndDropState.onDragInterrupted() }<br>  )<br>}</pre><p>Inside the PomodoroListScreen function, the LazyColumn modifier is set using the dragGestureHandler extension. This effectively binds the drag gesture handling logic to the LazyColumn, making it responsive to user interactions.</p><p><strong>Handling Overscroll:</strong></p><p>The handleOverscrollJob function efficiently manages over-scrolling behavior. It checks if an over-scroll job is active and calculates the over-scroll offset using the checkForOverScroll function from the ItemListDragAndDropState. If over-scroll is detected, the job is launched to scroll the list accordingly.</p><pre>private fun handleOverscrollJob(<br>  overscrollJob: MutableState&lt;Job?&gt;,<br>  scope: CoroutineScope,<br>  itemListDragAndDropState: ItemListDragAndDropState<br>) {<br>  if (overscrollJob.value?.isActive == true) return<br>  val overscrollOffset = itemListDragAndDropState.checkForOverScroll()<br>  if (overscrollOffset != 0f) {<br>    overscrollJob.value = scope.launch {<br>      itemListDragAndDropState.getLazyListState().scrollBy(overscrollOffset)<br>    }<br>  } else {<br>    overscrollJob.value?.cancel()<br>  }<br>}</pre><p><strong>List Item Composition:</strong></p><p>The PomodoroListItem The composable function encapsulates the visual representation of individual list items. It takes item and displacementOffset as parameters. The displacementOffset indicates the vertical displacement of the item due to dragging.</p><pre>@Composable<br>private fun PomodoroListItem(<br>  item: String,<br>  displacementOffset: Float?<br>) {<br><br>  val isBeingDragged = displacementOffset != null<br>  val backgroundColor = if (isBeingDragged) {<br>    Color.LightGray<br>  } else {<br>    Color.White<br>  }<br><br>  Column(<br>    modifier = Modifier<br>      .graphicsLayer { translationY = displacementOffset ?: 0f }<br>      .background(Color.White, shape = RoundedCornerShape(4.dp))<br>      .fillMaxWidth()<br>      .fillMaxHeight()<br>  ) {<br>    Card(<br>      shape = RoundedCornerShape(8.dp), backgroundColor = backgroundColor,<br>      modifier = Modifier<br>        .fillMaxWidth()<br>        .padding(8.dp)<br>    ) {<br>      Text(text = item, modifier = Modifier.padding(16.dp))<br>    }<br>  }<br>}</pre><pre>@Composable<br>fun rememberDragDropListState(<br>  lazyListState: LazyListState = rememberLazyListState(),<br>  onMove: (Int, Int) -&gt; Unit,<br>): ItemListDragAndDropState {<br>  return remember { ItemListDragAndDropState(lazyListState, onMove) }<br>}<br><br>class ItemListDragAndDropState(<br>  private val lazyListState: LazyListState,<br>  private val onMove: (Int, Int) -&gt; Unit<br>) {<br>  private var draggedDistance by mutableStateOf(0f)<br>  private var initiallyDraggedElement by mutableStateOf&lt;LazyListItemInfo?&gt;(null)<br>  private var currentIndexOfDraggedItem by mutableStateOf(-1)<br>  private var overscrollJob by mutableStateOf&lt;Job?&gt;(null)<br><br>  // Retrieve the currently dragged element&#39;s info<br>  private val currentElement: LazyListItemInfo?<br>    get() = currentIndexOfDraggedItem.let {<br>      lazyListState.getVisibleItemInfoFor(absoluteIndex = it)<br>    }<br><br>  // Calculate the initial offsets of the dragged element<br>  private val initialOffsets: Pair&lt;Int, Int&gt;?<br>    get() = initiallyDraggedElement?.let { Pair(it.offset, it.offsetEnd) }<br><br>  // Calculate the displacement of the dragged element<br>  val elementDisplacement: Float?<br>    get() = currentIndexOfDraggedItem<br>      .let { lazyListState.getVisibleItemInfoFor(absoluteIndex = it) }<br>      ?.let { item -&gt;<br>        (initiallyDraggedElement?.offset ?: 0f).toFloat() + draggedDistance - item.offset<br>      }<br><br>  // Functions for handling drag gestures<br>  fun onDragStart(offset: Offset) {<br>    lazyListState.layoutInfo.visibleItemsInfo<br>      .firstOrNull { item -&gt; offset.y.toInt() in item.offset..(item.offset + item.size) }<br>      ?.also {<br>        currentIndexOfDraggedItem = it.index<br>        initiallyDraggedElement = it<br>      }<br>  }<br><br>  // Handle interrupted drag gesture<br>  fun onDragInterrupted() {<br>    draggedDistance = 0f<br>    currentIndexOfDraggedItem = -1<br>    initiallyDraggedElement = null<br>    overscrollJob?.cancel()<br>  }<br><br>  // Helper function to calculate start and end offsets<br>  // Calculate the start and end offsets of the dragged element<br>  private fun calculateOffsets(offset: Float): Pair&lt;Float, Float&gt; {<br>    val startOffset = offset + draggedDistance<br>    val currentElementSize = currentElement?.size ?: 0<br>    val endOffset = offset + draggedDistance + currentElementSize<br>    return startOffset to endOffset<br>  }<br><br>  // Handle the drag gesture<br>  fun onDrag(offset: Offset) {<br>    draggedDistance += offset.y<br>    val topOffset = initialOffsets?.first ?: return<br>    val (startOffset, endOffset) = calculateOffsets(topOffset.toFloat())<br><br>    val hoveredElement = currentElement<br>    if (hoveredElement != null) {<br>      val delta = startOffset - hoveredElement.offset<br>      val isDeltaPositive = delta &gt; 0<br>      val isEndOffsetGreater = endOffset &gt; hoveredElement.offsetEnd<br><br>      val validItems = lazyListState.layoutInfo.visibleItemsInfo.filter { item -&gt;<br>        !(item.offsetEnd &lt; startOffset || item.offset &gt; endOffset || hoveredElement.index == item.index)<br>      }<br><br>      val targetItem = validItems.firstOrNull {<br>        when {<br>          isDeltaPositive -&gt; isEndOffsetGreater<br>          else -&gt; startOffset &lt; it.offset<br>        }<br>      }<br><br>      if (targetItem != null) {<br>        currentIndexOfDraggedItem.let { current -&gt;<br>          onMove.invoke(current, targetItem.index)<br>          currentIndexOfDraggedItem = targetItem.index<br>        }<br>      }<br>    }<br>  }<br><br>  fun checkForOverScroll(): Float {<br>    val draggedElement = initiallyDraggedElement<br>    if (draggedElement != null) {<br>      val (startOffset, endOffset) = calculateOffsets(draggedElement.offset.toFloat())<br>      val diffToEnd = endOffset - lazyListState.layoutInfo.viewportEndOffset<br>      val diffToStart = startOffset - lazyListState.layoutInfo.viewportStartOffset<br>      return when {<br>        draggedDistance &gt; 0 &amp;&amp; diffToEnd &gt; 0 -&gt; diffToEnd<br>        draggedDistance &lt; 0 &amp;&amp; diffToStart &lt; 0 -&gt; diffToStart<br>        else -&gt; 0f<br>      }<br>    }<br>    return 0f<br>  }<br><br>  fun getLazyListState(): LazyListState {<br>    return lazyListState<br>  }<br><br>  fun getCurrentIndexOfDraggedListItem(): Int {<br>    return currentIndexOfDraggedItem<br>  }<br>}<br><br>fun LazyListState.getVisibleItemInfoFor(absoluteIndex: Int): LazyListItemInfo? {<br>  return this.layoutInfo.visibleItemsInfo.getOrNull(<br>    absoluteIndex - this.layoutInfo.visibleItemsInfo.first().index<br>  )<br>}<br><br>/*<br>  Bottom offset of the element in Vertical list<br>*/<br>val LazyListItemInfo.offsetEnd: Int<br>  get() = this.offset + this.size<br><br>/*<br>   Moving element in the list<br>*/<br>fun &lt;T&gt; MutableList&lt;T&gt;.move(<br>  from: Int,<br>  to: Int<br>) {<br>  if (from == to)<br>    return<br>  val element = this.removeAt(from) ?: return<br>  this.add(to, element)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665576ba89a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/exploring-drag-and-drop-functionality-in-compose-665576ba89a0">Exploring Drag-and-Drop Functionality in Compose</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Thing We Didn’t Notice]]></title>
            <link>https://medium.com/arpalar-tech/the-thing-we-didnt-notice-aa3c65d85ee0?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/aa3c65d85ee0</guid>
            <category><![CDATA[beginner-coding]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 15:41:57 GMT</pubDate>
            <atom:updated>2023-04-09T15:41:57.858Z</atom:updated>
            <content:encoded><![CDATA[<h4>About Forgotten One Design pattern</h4><p>These days I am reading a lot of tutorials and reading medium articles about Android development. Most explain new technologies and how we improve in terms of UI.</p><p>In our daily learning, new things are very important but also understanding basic things is as well, At this time we don’t care about memory management because our phone memory is efficient as a normal computer so we didn’t care much about memory consumption.</p><p>Even though our phone memory is efficient, we need to care about memory management, In my opinion, a good application does not depend on how much DAU is in the app, it depends on how much they care about detail optimization. So Today I will explain one of the important optimizations which is Memory allocation.</p><p>In Android development, there are several ways to optimize memory usage and avoid unnecessary object creation</p><ol><li><strong>Object Pooling</strong>: Developers can implement their own object pooling mechanism, where a fixed number of objects are created and reused instead of creating new objects every time they are needed. This can help reduce memory usage and improve performance, especially for objects that are expensive to create.</li><li><strong>Lazy Initialization</strong>: Objects can be lazily initialized, meaning they are only created when they are actually needed. This can help avoid unnecessary object creation up front, especially for objects that may not be needed during the entire lifecycle of an application.</li><li><strong>Caching</strong>: Developers can cache objects in memory to reuse them instead of creating new objects with the same properties. This can be achieved using techniques such as using LRU (Least Recently Used) caches, in-memory databases, or other caching mechanisms provided by Android frameworks or third-party libraries.</li><li><strong>Object Reuse</strong>: Developers can design their objects to be reusable, by minimizing their state and keeping them stateless, so that they can be used by multiple components or activities without the need for creating new objects.</li><li><strong>Efficient Data Structures</strong>: Developers can use efficient data structures, such as sparse arrays or maps, to reduce the memory usage when storing and retrieving data, instead of using collections that may create unnecessary objects.</li><li><strong>Performance Optimization</strong>: Developers can optimize their code for performance by avoiding unnecessary object allocations and ensuring efficient memory management practices, such as avoiding excessive object creation in tight loops or performance-critical sections of the code.</li></ol><p>I think we all used these ways in our application, so I will not mention the detail of the above ways. Today I will explain one of the design patterns which we have forgotten.</p><p>This Forgotten design pattern is<strong> The Flyweight</strong> design pattern. It is a creational method that is used to optimize memory usage by sharing common parts of objects among multiple objects, rather than duplicating them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*_da04_XYf5dsJh5RH3owIA.png" /></figure><p>It is specifically designed to address scenarios where a large number of objects with similar properties need to be created and used in an application. The main idea behind the Flyweight pattern is to separate the intrinsic state (shared state) of an object from the extrinsic state (unique state) of an object.</p><p>The intrinsic state consists of properties that are common among multiple objects and can be shared, while the extrinsic state consists of properties that are unique to each object and cannot be shared.</p><p>he Flyweight pattern typically involves the following components:</p><ol><li><strong>Flyweight</strong>: Represents the shared objects that are stored and reused among multiple objects. It contains the intrinsic state, which is shared among objects.</li><li><strong>ConcreteFlyweight</strong>: Implements the Flyweight interface and represents the concrete shared objects that are created and reused.</li><li><strong>FlyweightFactory</strong>: Manages the creation and caching of Flyweight objects. It maintains a pool of Flyweight objects and provides methods to retrieve and create Flyweight objects.</li><li><strong>Client</strong>: Represents the objects that use the Flyweight objects. It stores the extrinsic state, which is unique to each object, and passes it to the Flyweight objects when needed</li></ol><p>Now coding time, let&#39;s see together how flyweight can be applied in our Android application.</p><pre>// WeatherInfo.kt<br>data class WeatherInfo(<br>    val location: String,<br>    val weather: String,<br>    val weatherIcon: String<br>)<br><br>// WeatherService.kt<br>interface WeatherService {<br>    fun getCurrentLocation(): String<br>    fun getCurrentWeather(location: String): String<br>    fun getWeatherIcon(weather: String): String<br>}<br><br>// WeatherInfoFactory.kt<br>object WeatherInfoFactory {<br>    private val weatherInfoCache = mutableMapOf&lt;String, WeatherInfo&gt;()<br><br>    fun getWeatherInfo(location: String, weather: String): WeatherInfo {<br>        val key = &quot;$location-$weather&quot;<br>        if (weatherInfoCache.containsKey(key)) {<br>            return weatherInfoCache[key]!!<br>        } else {<br>            val weatherIcon = getWeatherIcon(weather)<br>            val weatherInfo = WeatherInfo(location, weather, weatherIcon)<br>            weatherInfoCache[key] = weatherInfo<br>            return weatherInfo<br>        }<br>    }<br><br>    private fun getWeatherIcon(weather: String): String {<br>        // Implementation for getting weather icon based on weather<br>    }<br>}<br><br>// ViewModel.kt<br>class WeatherViewModel(<br>    private val weatherService: WeatherService<br>) : ViewModel() {<br>    private val weatherInfo = MutableLiveData&lt;WeatherInfo&gt;()<br>    val weatherInfoUI: LiveData&lt;WeatherInfo&gt; get() = weatherInfo<br><br>    fun fetchWeatherInfo() {<br>        viewModelScope.launch {<br>            try {<br>                val location = weatherService.getCurrentLocation()<br>                val weather = weatherService.getCurrentWeather(location)<br>                val weatherInfo = WeatherInfoFactory.getWeatherInfo(location, weather)<br>                weatherInfoUI.value = weatherInfo<br>            } catch (e: Exception) {<br>                // Handle error<br>            }<br>        }<br>    }<br>}<br><br>// MainActivity.kt<br>class MainActivity : AppCompatActivity() {<br>    private val viewModel: WeatherViewModel by viewModels()<br>    private lateinit var weatherTextView: TextView<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br><br>        weatherTextView = findViewById(R.id.weatherTextView)<br><br>        viewModel.weatherInfoUI.observe(this, { weatherInfo -&gt;<br>            weatherTextView.text = &quot;Location: ${weatherInfo.location}\n&quot; +<br>                    &quot;Weather: ${weatherInfo.weather}\n&quot; +<br>                    &quot;Icon: ${weatherInfo.weatherIcon}&quot;<br>        })<br><br>        // Fetch weather info<br>        viewModel.fetchWeatherInfo()<br>    }<br>}</pre><p>In this example, we use the Flyweight design pattern to reduce the memory usage when creating WeatherInfo objects. The WeatherInfoFactory acts as a factory for creating and caching WeatherInfo objects. It maintains a cache of WeatherInfo objects based on the location and weather and returns the cached object if it already exists, otherwise, it creates a new object, caches it and returns it.</p><p>By using the Flyweight design pattern, we can avoid creating multiple WeatherInfo objects with the same location and weather, which can help optimize memory usage when dealing with a large number of similar objects. This can be especially useful in scenarios where creating new objects is expensive in terms of memory and performance, and there is a need to reuse objects with similar properties to reduce memory overhead.</p><p>At this point don’t confuse them with Singleton Design patterns, The Flyweight and Singleton design patterns are both creational design methods that are used to manage objects in software applications, but they serve different purposes and have different implementations.</p><ol><li><strong>Purpose</strong>: The Flyweight pattern is used to optimize memory usage by sharing common parts of objects among multiple objects, while the Singleton pattern is used to ensure that a class has only one instance and provides a global point of access to that instance.</li><li><strong>Object Sharing</strong>: In the Flyweight pattern, objects with similar properties are shared and reused to avoid creating multiple objects with the same properties, which helps reduce memory usage. In the Singleton pattern, a single instance of a class is created and shared among all objects that need to access it, ensuring that only one instance of the class exists throughout the application.</li><li><strong>Object Creation:</strong> In the Flyweight pattern, objects are typically created by a factory or a factory method, which can cache and reuse objects based on their properties. In the Singleton pattern, the single instance of the class is typically created when the class is first accessed, and subsequent requests for the instance return the same instance without creating a new one.</li><li><strong>Instance Management:</strong> In the Flyweight pattern, the responsibility of managing the shared objects and their caching is typically handled by a factory or a factory method. In the Singleton pattern, the responsibility of managing a single instance of the class is typically handled by the class itself.</li><li><strong>Multiple Instances:</strong> The Flyweight pattern allows for the creation of multiple instances of similar objects with shared properties, while the Singleton pattern restricts the creation of multiple instances to only one instance of the class.</li><li><strong>Scope:</strong> The Flyweight pattern is typically used in scenarios where there are a large number of objects with similar properties, and memory optimization is a concern. The Singleton pattern is typically used in scenarios where there should be only one instance of a class throughout the application, such as for managing configuration settings, logging, or database connections.</li></ol><p>In summary, the Flyweight pattern is used to optimize memory usage by sharing common parts of objects, while the Singleton pattern is used to ensure that a class has only one instance throughout the application. Both patterns have different use cases, implementations, and implications in terms of object creation, sharing, and instance management. So you will think why this design pattern is not popular among developers.</p><p>Here are some reasons why the Flyweight pattern may not be as popular among developers:</p><ol><li><strong>Complexity:</strong> Implementing the Flyweight pattern can introduce additional complexity in the form of managing the shared state, maintaining a pool of objects, and handling the extrinsic state. This can require careful design and implementation, which may not be preferred in simple or small-scale applications.</li><li><strong>Limited Use Cases</strong>: The Flyweight pattern is most useful in scenarios where there are a large number of objects with similar properties, and memory optimization is a significant concern. However, not all applications may have such requirements, and developers may not see the need to implement the Flyweight pattern in every situation.</li><li><strong>Performance Overhead</strong>: While the Flyweight pattern can optimize memory usage, it may introduce additional overhead in terms of managing the shared state and pool of objects. This can impact performance, especially in applications where performance is critical, and developers may choose other approaches that provide a better trade-off between memory usage and performance.</li><li><strong>Simpler Alternatives</strong>: In some cases, there may be simpler alternatives available to achieve similar memory optimization goals, such as object pooling, lazy initialization, caching, or other memory management techniques, which may be easier to implement and maintain compared to the Flyweight pattern.</li></ol><p>The popularity of the pattern among developers may depend on the specific requirements and constraints of the application, the complexity of implementation, performance considerations, and the availability of simpler alternatives for achieving similar memory optimization goals. It’s important to note that the popularity of a design pattern may vary depending on the context, requirements, and preferences of the development team.</p><p>Whatever you optimize your application’s memory in terms of <strong>Flyweight pattern</strong> or <strong>Preference for other design patterns </strong>that is fine. The important thing is we have to be careful with our application and our code.</p><p>Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa3c65d85ee0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/the-thing-we-didnt-notice-aa3c65d85ee0">The Thing We Didn’t Notice</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why RecyclerView Adapter is called an Adapter]]></title>
            <link>https://medium.com/arpalar-tech/why-recyclerview-adapter-is-called-an-adapter-a3b69f761721?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3b69f761721</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 15:27:58 GMT</pubDate>
            <atom:updated>2023-04-09T15:27:58.705Z</atom:updated>
            <content:encoded><![CDATA[<h4>about why recycler view adapter is called recycler view adapter</h4><p>Do you know why we are very used to with <strong>Adapter (ArrayAdapter, RecyclerView Adapter ) </strong>in Android Development, have you ever think why we call as <strong>Adapter</strong>?</p><p>In this article let me explain we call as Adapter, <strong>RecyclerView Adapter</strong> is called an adapter because it follows the <a href="https://refactoring.guru/design-patterns/adapter"><strong>Adapter Design Pattern</strong></a>, which is a design pattern used to bridge incompatible interfaces.</p><p>In Android, <strong>Adapters</strong> are used to populate views such as <strong>ListViews</strong>, <strong>GridViews</strong>, and <strong>RecyclerViews</strong> with data. An <strong>Adapter</strong> acts as a <strong>bridge</strong> between the data source and the view, and it converts the data into a format that the view can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*D1Ywg4BAuXOSnuJXHhZa5w.jpeg" /></figure><p>Let me explain a bit about what is <strong>Adapters Design Patterns</strong>, as mention as above t<strong>he adapter design pattern</strong> is a structural design pattern that allows incompatible interfaces to work together.</p><p>It enables objects with incompatible interfaces to collaborate by creating a middleman that translates the interface of one object into an interface that the other object can understand.If you still don’t get the point, no worry i will explain with example:</p><p>In the context of a Car, an Adapter Design Pattern can be used to make the Car object work with other objects that have incompatible interfaces.</p><pre>class Car {<br>    fun start() {<br>        println(&quot;Starting the car...&quot;)<br>    }<br><br>    fun stop() {<br>        println(&quot;Stopping the car...&quot;)<br>    }<br><br>    fun fillFuel() {<br>        println(&quot;Filling up the gas tank...&quot;)<br>    }<br><br>    fun drive() {<br>        start()<br>        println(&quot;Driving the car...&quot;)<br>        stop()<br>    }<br>}</pre><p>The start(), stop(), and fillFuel() methods work with the Car object&#39;s internal combustion engine. However, we also have an ElectricCar object that has a different interface with the following methods:</p><pre>interface ElectricCar {<br>    fun charge()<br>    fun drive()<br>}</pre><p>The charge() method is used to charge the electric car&#39;s batteries, while the drive() method is used to start driving the car. These methods are incompatible with the Car object&#39;s methods.</p><p>To make the Car object work with the ElectricCar object, we can create an adapter class that implements the ElectricCar interface and translates the charge() method to the fillFuel() method of the Car object.</p><pre>class ElectricCarAdapter(private val car: Car) : ElectricCar {<br>    override fun charge() {<br>        car.fillFuel()<br>    }<br><br>    override fun drive() {<br>        car.drive()<br>    }<br>}</pre><p>In this adapter class, we take a Car object as a parameter in the constructor and implement the charge() and drive() methods of the ElectricCar interface. The charge() method is implemented by calling the car.fillFuel() method, which fills up the gas tank of the Car object. The drive() method is simply translated to a call to the car.drive() method.</p><p>Now, we can create an instance of the ElectricCarAdapter class and pass it a Car object to make the two objects work together:</p><pre>val car = Car()<br>val electricCar = ElectricCarAdapter(car)<br><br>electricCar.charge() // The adapter translates the method call to the Car object&#39;s fillFuel() method.<br>electricCar.drive() // The adapter translates the method call to the Car object&#39;s drive() method.</pre><p>In this example, the ElectricCar object’s charge() method call is translated to a call to the Car object&#39;s fillFuel() method by the adapter class. Similarly, the drive() method call is translated to a call to the Car object&#39;s drive() method. This allows us to use the ElectricCar object&#39;s interface to work with the Car object&#39;s internal combustion engine.</p><p>After reading this hope you will be understand how Adapter Design useful and how it works. So let continue about how the Adapter Design Pattern is applied in the RecyclerView:</p><ol><li><strong>Data source</strong>: The RecyclerView.Adapter takes data from a data source, which can be a list, array, database, or any other data source.</li><li><strong>View creation</strong>: The RecyclerView.Adapter creates views for each item in the data source. This is done in the onCreateViewHolder() method, which inflates the layout for the view and creates a ViewHolder object to hold the view.</li><li><strong>View binding</strong>: The RecyclerView.Adapter binds data from the data source to each view. This is done in the onBindViewHolder() method, which retrieves the data for the current position and binds it to the view.</li><li><strong>View recycling</strong>: The RecyclerView.Adapter recycles views that have scrolled off the screen to save memory and improve performance. This is done in the onBindViewHolder() method as well, by reusing the ViewHolder object for a new view at a different position.</li></ol><p>The RecyclerView.Adapter class is responsible for bridging the gap between the data source and the RecyclerView by converting the data into a format that can be displayed in a list or grid format.</p><p>It does this by creating and managing views for each item in the data source and binding data to each view as it is displayed on the screen. This makes it easier to display large amounts of data in a scrollable list or grid format in Android applications.</p><p>This implementation of the <strong>Adapter Design Pattern</strong> enables the <strong>RecyclerView</strong> or <strong>ListView</strong> to display data from a variety of data sources, including arrays, lists, and databases. By using an Adapter, the <strong>View</strong> can remain decoupled from the data source, which promotes maintainability and flexibility in the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b69f761721" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/why-recyclerview-adapter-is-called-an-adapter-a3b69f761721">Why RecyclerView Adapter is called an Adapter</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI with Clean Architecture]]></title>
            <link>https://medium.com/arpalar-tech/mvi-with-clean-architecture-73ee67caccc1?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/73ee67caccc1</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 06:14:50 GMT</pubDate>
            <atom:updated>2023-04-03T17:36:44.684Z</atom:updated>
            <content:encoded><![CDATA[<h4>Refactor version of MVI with Clean Architecture</h4><p><strong>MVI</strong> and <strong>MVI with Clean Architecture</strong> are both architectural patterns for developing Android applications. However, they differ in the way they handle application logic and data flow. This difference also applies to MVVM and MVVM with clean architecture.</p><p><strong>MVI</strong> is a pattern that separates an application into three components: <strong>Model</strong>, <strong>View</strong>, and <strong>Intent</strong>. The Model represents the state of the application, the View displays the UI, and the Intent represents user interactions with the UI. The MVI pattern is generally lightweight and straightforward to implement, making it a popular choice for small to medium-sized applications. You can see a detailed explanation in this <a href="https://medium.com/@yemonkyaw007/mvi-in-potatos-way-f0264d9fa822"><strong>article</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*0_C7frKD492iMG9X6lagqA.jpeg" /></figure><p><strong>MVI with Clean Architecture</strong>, on the other hand, is a more structured and scalable approach to Android application development. It combines the principles of MVI with the Clean Architecture principles of <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-e7b5cfe8c7a1"><strong>Separation of Concerns (SoC)</strong></a> and <a href="https://medium.com/@yemonkyaw007/solid-from-zero-to-potato-5-994e02850062"><strong>Dependency Inversion (DI)</strong></a>.</p><p><strong>Clean Architecture</strong> provides a clear separation of concerns by dividing an application into layers, where each layer has a specific responsibility and interacts only with specific layers. The layers in Clean Architecture include the <strong>Presentation Layer</strong>,<strong> Domain Layer</strong>, and <strong>Data Layer.</strong></p><p><strong>The Presentation Layer</strong> handles user interactions and UI rendering. It is responsible for communicating with the Domain Layer, which contains the application’s business logic. The Data Layer handles data storage and retrieval, interacting with the Domain Layer through defined interfaces.</p><p>To illustrate the differences between <strong>MVI and MVI with Clean Architecture</strong>, let’s consider an example of a Student application. In an MVI application, the Model would contain the student data, the View would display the student data, and the Intent would represent user actions such as adding, editing, or deleting students.</p><p>In contrast, in an MVI with a Clean Architecture application, the Presentation Layer would handle UI rendering and user interactions. The Domain Layer would contain the business logic, such as validating student data or retrieving student information from the Data Layer. The Data Layer would be responsible for storing and retrieving student data from a database or remote API.</p><p>In the Domain Layer, there might be use cases such as “Add Student,” “Delete Student,” or “Get Student List.” The Presentation Layer would then call these use cases to update the UI or interact with the user.</p><p>The advantage of MVI with Clean Architecture is that it provides a more structured and scalable approach. It allows for easier testing, reduces coupling between components, and makes it easier to modify or add new features to the application. However, it can also be more complex to implement and may be overkill for small applications that don’t require a lot of business logic or data storage.</p><p>Previous MVI example :</p><pre>// Define the reducer function to update the state of the application based <br>// on user intents<br>fun reduce(state: AppState, intent: UserIntent): AppState {<br>    return when (intent) {<br>        is UserIntent.AddStudent -&gt; addStudent(state, intent.student)<br>        is UserIntent.EditStudent -&gt; editStudent(state, intent.student)<br>        is UserIntent.DeleteStudent -&gt; deleteStudent(state, intent.student)<br>    }<br>}<br><br>// Define the data model for a student<br>data class Student(val name: String, val age: Int, val grade: String)<br><br>// Define the state of the application<br>data class AppState(val students: List&lt;Student&gt;)<br><br>// Define the actions that the user can perform<br>sealed class UserIntent {<br>    data class AddStudent(val student: Student) : UserIntent()<br>    data class EditStudent(val student: Student) : UserIntent()<br>    data class DeleteStudent(val student: Student) : UserIntent()<br>}<br><br>// Define the UI component to display the list of <br>// students and handle user inputs<br>class StudentListView {<br>    lateinit var presenter: StudentListPresenter<br>    <br>    fun render(state: AppState) {<br>        // Render the list of students on the screen<br>    }<br>    <br>    fun handleUserInput(intent: UserIntent) {<br>        // Pass the user intent to the presenter to update <br>        // the state of the application<br>        presenter.handleUserIntent(intent)<br>    }<br>}<br><br>// Define the presenter to handle user inputs and <br>// update the state of the application<br>class StudentListPresenter(private val reducer: (AppState, UserIntent) <br>-&gt; AppState) {<br>    lateinit var view: StudentListView<br>    var state = AppState(emptyList())<br>    <br>    fun handleUserIntent(intent: UserIntent) {<br>        state = reducer(state, intent)<br>        view.render(state)<br>    }<br>}<br><br>// Usage example<br>fun main() {<br>    val presenter = StudentListPresenter(::reduce)<br>    val view = StudentListView()<br>    presenter.view = view<br>    view.presenter = presenter<br>    <br>    val newStudent = Student(&quot;Ye Mon&quot;, 18, &quot;F-&quot;)<br>    view.handleUserInput(UserIntent.AddStudent(newStudent))<br>    <br>    val updatedStudent = Student(&quot;Nyan&quot;, 19, &quot;A+&quot;)<br>    view.handleUserInput(UserIntent.EditStudent(updatedStudent))<br>    <br>    val deletedStudent = Student(&quot;Thet&quot;, 20, &quot;A&quot;)<br>    view.handleUserInput(UserIntent.DeleteStudent(deletedStudent))<br>}<br><br><br>// Define separate functions to handle each type of user intent<br>fun addStudent(state: AppState, student: Student): AppState {<br>    return state.copy(students = state.students + student)<br>}<br><br>fun editStudent(state: AppState, student: Student): AppState {<br>    val updatedStudents = state.students.map { if (it.name == student.name) student else it }<br>    return state.copy(students = updatedStudents)<br>}<br><br>fun deleteStudent(state: AppState, student: Student): AppState {<br>    val filteredStudents = state.students.filterNot { it.name == student.name }<br>    return state.copy(students = filteredStudents)<br>}</pre><p>So let&#39;s refactor the previous MVI code to Clean Architecture,</p><p><strong>The Domain layer</strong> contains the Use Cases, which are responsible for performing the business logic of the application. Each Use Case takes a repository instance as a dependency and encapsulates a specific piece of logic (in this case, adding, editing, deleting, or retrieving students).</p><p><strong>The Presentation layer </strong>that is responsible for communicating with the user interface and invoking the appropriate Use Cases to perform business logic.</p><p><strong>Data Laye</strong>r the data layer is responsible for fetching and storing data. In this example, we define a StudentRepository interface in the data layer that defines the methods for getting and updating Student data.</p><p><strong>ViewModel Layer</strong> : the ViewModel layer is responsible for handling the business logic and transforming the StudentIntent into a StudentViewState. In this example, we define a StudentViewModel class that takes in a StudentUseCase as a dependency. At this point don’t confuse with Android ViewModel, Android ViewModel is just making more easily to handle in this layer.</p><p>Finally, we’ve instantiated the dependencies (in this case, just the StudentRepository and the <strong>Use Cases</strong>) using dependency injection. This allows us to easily swap out implementations of these dependencies (e.g. for testing purposes) without modifying the rest of the codebase.</p><blockquote><strong>I will not refactor all of the previous example, please do refactor your self which does not included in my example</strong></blockquote><pre>fun main() {<br>    val database = DatabaseImpl()<br>    val studentRepository = StudentRepositoryImpl(database) <br>    val studentUseCase = StudentUseCase(studentRepository)<br>    val studentViewModel = StudentViewModel(studentUseCase)<br><br>    // Test loading students<br>    studentViewModel.processIntent(StudentIntent.LoadStudents)<br>    when (val state = studentViewModel.uiViewState) {<br>        is StudentViewState.Loading -&gt; println(&quot;Loading students...&quot;)<br>        is StudentViewState.Success -&gt; {<br>            println(&quot;Loaded ${state.students.size} students:&quot;)<br>            state.students.forEach { student -&gt;<br>                println(&quot; - ${student.id} (${student.Name}) - Grade ${student.grade}&quot;)<br>            }<br>        }<br>        is StudentViewState.Error -&gt; println(&quot;Error loading students: ${state.errorMessage}&quot;)<br>    }<br><br>    // Test updating a student<br>    val studentToUpdate = Student(&quot;1&quot;, &quot;Nyan&quot;, &quot;F&quot;)<br>    studentViewModel.processIntent(StudentIntent.EditStudent(studentToUpdate))<br>    // Verify that the student was updated by loading the students again<br>    when (val state = studentViewModel.uiViewState) {<br>        is StudentViewState.Loading -&gt; println(&quot;Loading students...&quot;)<br>        is StudentViewState.Success -&gt; {<br>            val updatedStudent = state.students.find { it.id == studentToUpdate.id }<br>            if (updatedStudent != null) {<br>                println(&quot;Updated ${updatedStudent.Name} (${updatedStudent.id}) - Grade ${updatedStudent.grade}&quot;)<br>            } else {<br>                println(&quot;Error updating student: student not found&quot;)<br>            }<br>        }<br>        is StudentViewState.Error -&gt; println(&quot;Error loading students: ${state.errorMessage}&quot;)<br>    }<br><br>}<br><br>/*ViewModel Layer<br>The ViewModel layer is responsible for handling the business <br>logic and transforming the StudentIntent into a StudentViewState.<br>In this example, we define a StudentViewModel <br>class that takes in a StudentUseCase <br>(which we&#39;ll define next) as a dependency. */<br>class StudentViewModel(private val studentUseCase: StudentUseCase) {<br><br>    private var viewState: StudentViewState = StudentViewState.Loading<br>    var uiViewState: StudentViewState = viewState<br><br>    fun processIntent(intent: StudentIntent) {<br>        when (intent) {<br>            is StudentIntent.LoadStudents -&gt; loadStudents()<br>            is StudentIntent.EditStudent -&gt; {<br>                updateStudent(intent.student)<br>            }<br>        }<br>    }<br><br>    private fun loadStudents() {<br>        uiViewState = StudentViewState.Loading<br>        try {<br>            val students = studentUseCase.getStudents()<br>            uiViewState = StudentViewState.Success(students)<br>        } catch (e: Exception) {<br>            uiViewState = StudentViewState.Error(e.message ?: &quot;Unknown error&quot;)<br>        }<br>    }<br><br><br>     private fun updateStudent(student: Student) {<br>        val students = studentUseCase.updateStudent(student)<br>        uiViewState = StudentViewState.Success(students)<br>    }<br>}<br><br>// Define the data model for a student<br>data class Student(val id: String, val Name: String, val grade: String)<br><br>interface Database {<br>    fun getStudents(): List&lt;Student&gt;<br>    fun updateStudent(student : Student) : List&lt;Student&gt;<br>}<br><br>class DatabaseImpl : Database {<br>    private val students = mutableListOf(<br>        Student(&quot;1&quot;, &quot;Thet&quot;, &quot;A&quot;),<br>        Student(&quot;2&quot;, &quot;Nyan&quot;, &quot;A+&quot;),<br>        Student(&quot;3&quot;, &quot;Ye Mon&quot;, &quot;B+&quot;)<br>    )<br>    <br>    override fun updateStudent(student : Student) : List&lt;Student&gt;{<br>      //should be update data from database according to user given value<br>      //now only mock<br>      val updatedStudents = students.map { if (it.id == student.id) student else it }<br>      return updatedStudents<br>    }<br><br>    override fun getStudents(): List&lt;Student&gt; {<br>        return students.toList()<br>    }<br>}<br><br>/*<br>Data Layer<br>The data layer is responsible for fetching and storing data. <br>In this example, we define a StudentRepository interface<br>in the data layer that defines the methods for getting <br>and updating Student data.<br>*/<br>interface StudentRepository {<br>    fun getStudents(): List&lt;Student&gt;<br>    fun updateStudent(student : Student)  : List&lt;Student&gt;<br>}<br><br>class StudentRepositoryImpl(private val database: Database) : StudentRepository {<br>    override fun getStudents(): List&lt;Student&gt; {<br>        return database.getStudents()<br>    }<br>    <br>    override fun updateStudent(student : Student) : List&lt;Student&gt; {<br>        return database.updateStudent(student)<br>    }<br>}<br><br>/*<br>Presentation Layer<br>The presentation layer is responsible for rendering the UI <br>and responding to user actions. In this example, <br>we define a StudentViewState sealed class that represents <br>the different states of the UI.<br>*/<br>sealed class StudentViewState {<br>    object Loading : StudentViewState()<br>    data class Success(val students: List&lt;Student&gt;) : StudentViewState()<br>    data class Error(val errorMessage: String) : StudentViewState()<br>}<br><br>// StudentIntent sealed class that represents the different user actions<br>sealed class StudentIntent {<br>    object LoadStudents : StudentIntent()<br>    data class EditStudent(val student: Student) : StudentIntent()<br>}<br><br>/*<br>Use Case Layer<br>The use case layer is responsible for defining the business logic <br>and interacting with the data layer. In this example, we define <br>a StudentUseCase class that takes in a StudentRepository as a dependency.<br>*/<br>class StudentUseCase(private val studentRepository: StudentRepository) {<br><br>    fun getStudents(): List&lt;Student&gt; {<br>        return studentRepository.getStudents()<br>    }<br>    <br>    fun updateStudent(student: Student)  : List&lt;Student&gt; {<br>        return studentRepository.updateStudent(student)<br>    }<br><br>}</pre><p>Now you will see your code is more decouple in each layer than previous MVI pattern by separating different layer and each layer have their own responsibility.</p><p>That’s it! with this architecture, the StudentViewModel is responsible for handling the user actions and updating the UI, while the StudentUseCase is responsible for the business logic and interacting with the data layer. This makes it easy to test and maintain the codebase, since each layer has clear responsibilities and dependencies.</p><p>Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking and you will be more understand about what the different between two different architecture and why we should use clean architecture.</p><p><strong>Bonuses</strong> : example of how to refactor the StudentViewModel class to follow the Single <strong>Responsibility Principle (SRP)</strong> and <strong>Open/Closed Principle (OCP)</strong>:</p><pre>interface StudentViewStateHandler {<br>    fun handleLoading()<br>    fun handleSuccess(students: List&lt;Student&gt;)<br>    fun handleError(message: String)<br>}<br><br>class StudentViewModel(<br>    private val studentUseCase: StudentUseCase,<br>    private val stateHandler: StudentViewStateHandler<br>) {<br>    fun processIntent(intent: StudentIntent) {<br>        when (intent) {<br>            is StudentIntent.LoadStudents -&gt; loadStudents()<br>            is StudentIntent.UpdateStudent -&gt; updateStudent(intent.student)<br>        }<br>    }<br><br>    private fun loadStudents() {<br>        stateHandler.handleLoading()<br>        try {<br>            val students = studentUseCase.getStudents()<br>            stateHandler.handleSuccess(students)<br>        } catch (e: Exception) {<br>            stateHandler.handleError(e.message ?: &quot;Unknown error&quot;)<br>        }<br>    }<br><br>    private fun updateStudent(student: Student) {<br>        studentUseCase.updateStudent(student)<br>    }<br>}<br><br><br>class ConsoleViewStateHandler : StudentViewStateHandler {<br>    override fun handleLoading() {<br>        println(&quot;Loading students...&quot;)<br>    }<br><br>    override fun handleSuccess(students: List&lt;Student&gt;) {<br>        println(&quot;Loaded ${students.size} students:&quot;)<br>        students.forEach { student -&gt;<br>            println(&quot; - ${student.name} (${student.age}) - Grade ${student.grade}&quot;)<br>        }<br>    }<br><br>    override fun handleError(message: String) {<br>        println(&quot;Error loading students: $message&quot;)<br>    }<br>}<br><br>fun main() {<br>    val studentRepository = StudentRepositoryImpl() <br>     // Replace this with your own implementation <br>    // of the repository interface<br>    val studentUseCase = StudentUseCase(studentRepository)<br><br>    // Use the ConsoleViewStateHandler to print out the view state<br>    val studentViewModel = StudentViewModel(studentUseCase,<br>    ConsoleViewStateHandler())<br><br>    // Test loading students<br>    studentViewModel.processIntent(StudentIntent.LoadStudents)<br><br>    // Test updating a student<br>    val studentToUpdate = Student(&quot;1&quot;, &quot;Nyan&quot;, &quot;A+&quot;)<br>    studentViewModel.processIntent(StudentIntent.UpdateStudent(studentToUpdate))<br><br>    // Verify that the student was updated by loading the students again<br>    studentViewModel.processIntent(StudentIntent.LoadStudents)<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ee67caccc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/mvi-with-clean-architecture-73ee67caccc1">MVI with Clean Architecture</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVI in potato’s way]]></title>
            <link>https://medium.com/arpalar-tech/mvi-in-potatos-way-f0264d9fa822?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/f0264d9fa822</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 10:04:48 GMT</pubDate>
            <atom:updated>2023-04-02T15:57:01.080Z</atom:updated>
            <content:encoded><![CDATA[<p>“<strong>Rome wasn’t built in a day</strong>”, I think all of us already hear this word is often used to remind us of the amount of time and effort it takes to create something great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*IRhLxeGZ5W26kjxtVVugyg.jpeg" /></figure><p>I mentioned the above words because I wanna give support to new joiners for our native mobile development. We are so lucky because we become developers at an early stage so we don’t have a lot of things to choose from but new joiners are not.</p><p>But currently, there are a lot of <strong>frameworks</strong>, <strong>libraries,</strong> and <strong>architecture</strong> to follow. Even if you are already familiar with <strong>MVP</strong> and <strong>MVVM</strong>, you should also know about MVI and also a lot of things to learn in a limited time.</p><blockquote><strong>TLDR</strong> Actually this is not really about MVI architecture I added this keyword to boots my article</blockquote><p>I am writing this article because I saw a lot of talented new joiners in our industries who do not satisfy themself in terms of technology so they are trying to learn new things every day. So they do the one mistake as I did before which is we only care to finish rather than why and how its works behind. I wanna suggest don’t wanna go fast in the early stage always remember “<strong>Rome wasn’t built in a day</strong>”.</p><p>Lets me stop my bullshit now, let&#39;s go to the explanation about how I learn MVI in my potato’s ways.</p><p><strong>MVI</strong> stands for <strong>Model-View-Intent</strong>, which is an architectural pattern used in software development to separate the different components of an application into distinct roles.</p><p>In <strong>MVI</strong>, the Model represents the state of the application and the business logic behind it. The View is responsible for rendering the UI and receiving user inputs, while the Intent represents the user’s actions or intentions.</p><p>Here’s a simple example of how MVI can be applied in the context of a student management system:</p><p><strong>Model</strong>: The model consists of the data related to a student, such as their name, age, and grade.</p><p><strong>View</strong>: The view is responsible for displaying the student’s information on the screen and allowing the user to interact with it. For example, the user might be able to view a list of students, add a new student, or edit an existing student’s information.</p><p><strong>Intent</strong>: The intent represents the user’s actions or intentions, such as adding a new student to the system or updating an existing student’s information.</p><p>So I think you understand what is <strong>MVI</strong> by reading my article right? How can be even though I don’t understand which is MVI by reading this? Just kidding let me explain to you with a detailed example so you will be more understanding about <strong>MVI</strong>.</p><p>First, define the data model for a student as a Kotlin data class. We then define the state of the application as an AppState data class, which contains a list of students.</p><pre>// Define the data model for a student<br>//Data Model for Student<br>data class Student(val name: String, val age: Int, val grade: String)<br><br>// let assume currently as Data Model<br>data class AppState(val students: List&lt;Student&gt;)</pre><p>In this class, the Student is for holding student data, which is for AppState. AppState is for storing the Application State which you will see in detail later. So let&#39;s create the <strong>Intent</strong> to handle the user action below</p><pre>// Define the actions that the user can perform<br>sealed class UserIntent {<br>    data class AddStudent(val student: Student) : UserIntent()<br>    data class EditStudent(val student: Student) : UserIntent()<br>    data class DeleteStudent(val student: Student) : UserIntent()<br>}</pre><p>In the above example, we already added <strong>Model</strong> and <strong>Intent, </strong>so we need<strong> V</strong> to complete the<strong> MVI</strong>. let me the view for Students to handle user actions and to show student data.</p><pre>// Define the UI component to display the list of students <br>// and handle user inputs<br>class StudentListView {<br><br>    fun render(state: AppState) {<br>        // Render the list of students on the screen<br>    }<br><br>    fun handleUserInput(intent: UserIntent) {<br>        // Pass the user intent to the presenter <br>        // to update the state of the application<br>    }<br>}</pre><p><strong>Tada!</strong> congratulations now finish the MVI but you will see our Model, View, and Intent are not connected to each other so we can’t do anything with this architecture. so make this architecture useful and connected.</p><p><strong>To implement MVI</strong>, we would first define the data model for a student and create a separate class to manage the state of the application based on the data model.</p><p>Next, we would create the UI elements (views) to display the student’s information and handle user inputs, and finally, we would define the intents that the user can perform and the corresponding actions that the application should take in response to those intents. So let me refactor the above code as follow :</p><pre>// Define the data model for a student<br>data class Student(val name: String, val age: Int, val grade: String)<br><br>// Define the state of the application<br>data class AppState(val students: List&lt;Student&gt;)<br><br>// Define the actions that the user can perform<br>sealed class UserIntent {<br>    data class AddStudent(val student: Student) : UserIntent()<br>    data class EditStudent(val student: Student) : UserIntent()<br>    data class DeleteStudent(val student: Student) : UserIntent()<br>}<br><br>// Define the reducer function to update the state of the <br>// application based on user intents<br>// Note that this is not related with React-redux <br>fun reduce(state: AppState, intent: UserIntent): AppState {<br>    return when (intent) {<br>        is UserIntent.AddStudent -&gt; {<br>          state.copy(students = state.students + intent.student)<br>        }<br>        is UserIntent.EditStudent -&gt; {<br>          state.copy(students = state.students.map { <br>            if (it.name == intent.student.name) <br>              intent.student else it })<br>        }<br>        is UserIntent.DeleteStudent -&gt; {<br>            state.copy(students = state.students.filterNot { <br>              it.name == intent.student.name })<br>        }<br>    }<br>}<br><br>// Define the UI component to display the list of <br>// students and handle user inputs<br>class StudentListView {<br>    lateinit var presenter: StudentListPresenter<br>    <br>    fun render(state: AppState) {<br>        // Render the list of students on the screen<br>    }<br>    <br>    fun handleUserInput(intent: UserIntent) {<br>        // Pass the user intent to the presenter to update <br>        // the state of the application<br>        presenter.handleUserIntent(intent)<br>    }<br>}<br><br>// Define the presenter to handle user inputs and <br>// update the state of the application<br>class StudentListPresenter(private val reducer: (AppState, UserIntent) <br>-&gt; AppState) {<br>    lateinit var view: StudentListView<br>    var state = AppState(emptyList())<br>    <br>    fun handleUserIntent(intent: UserIntent) {<br>        state = reducer(state, intent)<br>        view.render(state)<br>    }<br>}<br><br>// Usage example<br>fun main() {<br>    val presenter = StudentListPresenter(::reduce)<br>    val view = StudentListView()<br>    presenter.view = view<br>    view.presenter = presenter<br>    <br>    val newStudent = Student(&quot;Ye Mon&quot;, 18, &quot;F-&quot;)<br>    view.handleUserInput(UserIntent.AddStudent(newStudent))<br>    <br>    val updatedStudent = Student(&quot;Nyan&quot;, 19, &quot;A+&quot;)<br>    view.handleUserInput(UserIntent.EditStudent(updatedStudent))<br>    <br>    val deletedStudent = Student(&quot;Thet&quot;, 20, &quot;A&quot;)<br>    view.handleUserInput(UserIntent.DeleteStudent(deletedStudent))<br>}</pre><p>we define the actions that the user can perform as sealed classes that extend the UserIntent interface. We also define a reducer function that takes the current state of the application and user intent as input and returns a new state based on the intent.</p><p>We then define the UI component as a StudentListView class that renders the list of students on the screen and handles user inputs. We also define a StudentListPresenter class that handles user inputs and updates the state of the application by calling the reducer function.</p><p>Finally, in the usage example, we create a new instance of the presenter and the view and connect them to each other. We then simulate user inputs by adding a new student, editing an existing student, and deleting a student. The presenter updates the state of the application based on the user inputs, and the view renders the updated list of students on the screen.</p><p>I hope you will understand how we can implement <strong>MVI</strong> in our own way without needing for Android studio and MVI is not only for android.</p><p>Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking.</p><p><strong>Bonus:</strong><a href="https://gist.github.com/indexer/ae67e67eccd82d5ecaa05e9f64187884">https://gist.github.com/indexer/ae67e67eccd82d5ecaa05e9f64187884</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0264d9fa822" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/mvi-in-potatos-way-f0264d9fa822">MVI in potato’s way</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID — From Zero To Potato 5]]></title>
            <link>https://medium.com/arpalar-tech/solid-from-zero-to-potato-5-994e02850062?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/994e02850062</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 09:58:46 GMT</pubDate>
            <atom:updated>2023-04-01T09:58:47.376Z</atom:updated>
            <content:encoded><![CDATA[<h4>About <strong>Dependency Inversion Principle (DIP) </strong>in this article ,this will be last article about <strong>SOLID.</strong></h4><p>Today I will continue explain about <strong>Dependency Inversion Principle (DIP) </strong>in this article.We will be familiar about others principle in <strong>SOLID</strong> because even if we don’t know about <strong>SOLID </strong>principle we can learn from our senior’s code, various medium article and tutorials, but you will be very rare to hear what is <strong>Dependency Inversion</strong> and how should we used it and why we should use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Dj1I7LtAR4LJltSNQyKUUw.jpeg" /></figure><p>By the way, if you are already working as Android Developer don’t confuse with <strong>Dependency Injection. </strong>You will be already familiar with popular libraries Dagger,Hilt and Koin. These two are very different so be careful when you explain especially in interviews.</p><p><strong>Dependency Injection</strong> is an implementation technique for populating instance variables of a class. <strong>Dependency Inversion</strong> is a general design guideline which recommends that classes should only have direct relationships with high-level abstractions.</p><blockquote>Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules; both should depend on abstractions.</blockquote><p>Let me explain you with simple code implementation, after that you will be more understand about <strong>DIP. </strong>As usual let start with Student class that has a dependency on a Teacher class to perform some functionality:</p><pre>class Student(private val teacher: Teacher) {<br>    fun askQuestion(question: String) {<br>        teacher.answerQuestion(question)<br>    }<br>}</pre><p>In above example the Student class depends directly on the Teacher class, violating the DIP because a <strong>high-level module</strong> (Student) is depending on a <strong>low-level module</strong> (Teacher).</p><p>so let refactor to adhere to the <strong>DIP</strong>, we can introduce an abstraction between the Student and Teacher classes:</p><pre>interface QuestionAnswerer {<br>    fun answerQuestion(question: String)<br>}<br><br>class Teacher : QuestionAnswerer {<br>    override fun answerQuestion(question: String) {<br>        // answer the specified question<br>    }<br>}<br><br>class Student(private val questionAnswerer: QuestionAnswerer) {<br>    fun askQuestion(question: String) {<br>        questionAnswerer.answerQuestion(question)<br>    }<br>}</pre><p>In this refactored version, we introduce an abstraction called QuestionAnswerer that the Student class depends on instead of the Teacher class directly. The Teacher class implements the QuestionAnswerer interface, and the Student class now depends on the interface rather than the concrete Teacher class.</p><p>This adheres to the DIP because the Student class is now depending on an abstraction (QuestionAnswerer) rather than a concrete implementation (Teacher). This allows for greater flexibility and extensibility, as any class that implements the QuestionAnswerer interface can be used as a dependency for the Student class, not just the Teacher class.</p><p>After seeing the refactored version, i hope you will get why we should use <strong>Dependency</strong> <strong>Inversion</strong> too, <strong>DIP</strong> helps to decouple the components in your application and can make your code more flexible, maintainable, and easier to test.</p><p>Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking. Happy coding for all you then before.</p><p><strong>Previous Article about SOLID :</strong></p><p><strong>Single Responsibility Principle (SRP)</strong> : <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-e7b5cfe8c7a1">https://medium.com/arpalar-tech/solid-from-zero-to-potato-e7b5cfe8c7a1</a></p><p><strong>Open/Closed Principle (OCP):</strong> <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-2-5a4c17bd8ec8">https://medium.com/arpalar-tech/solid-from-zero-to-potato-2-5a4c17bd8ec8</a></p><p><strong>Liskov Substitution Principle (LSP):</strong> <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-3-94d6f63dbbfe">https://medium.com/arpalar-tech/solid-from-zero-to-potato-3-94d6f63dbbfe</a></p><p><strong>Interface Segregation Principle (ISP): </strong><a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-4-d1d9b42c3a78">https://medium.com/arpalar-tech/solid-from-zero-to-potato-4-d1d9b42c3a78</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=994e02850062" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-5-994e02850062">SOLID — From Zero To Potato 5</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID — From Zero To Potato 4]]></title>
            <link>https://medium.com/arpalar-tech/solid-from-zero-to-potato-4-d1d9b42c3a78?source=rss----6d53a7e11b53---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1d9b42c3a78</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[YE MON KYAW]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 04:29:59 GMT</pubDate>
            <atom:updated>2023-04-10T15:35:47.101Z</atom:updated>
            <content:encoded><![CDATA[<h4>About <strong>Interface Segregation Principle (ISP)</strong></h4><p>Today i will explain about <strong>Interface Segregation Principle (ISP), this </strong>principle is very similar with <strong>LSP, </strong>so don’t be confuse with<strong> LSP, so i will explain about what is different between this two principle.</strong></p><p><strong>LSP</strong> governs relationships between parent and child classes (i.e. hierarchical relationships). It tells you <strong><em>how to implement</em></strong>. The <strong>ISP</strong> governs relationships between parent and client classes (i.e. producer/consumer relationships). It tells you <strong><em>when to implement</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CNAOzNVatxpaBYxmCSvBfQ.jpeg" /></figure><p>So let move what is <strong>Interface Segregation Principle (ISP), ISP</strong> states that we should design interfaces that are specific to the needs of a particular client or set of clients, rather than creating large, monolithic interfaces that may be unnecessary for some clients.</p><blockquote>Interface Segregation Principle (ISP): A client should not be forced to depend on interfaces it does not use.</blockquote><p>Let move to the implementation, we have an interface called StudentActivities that defines various methods related to student activities:</p><pre>interface StudentActivities {<br>    fun joinClub(club: String)<br>    fun joinSportsTeam(sportsTeam: String)<br>    fun attendEvent(event: String)<br>    fun volunteerForEvent(event: String)<br>    fun joinStudyGroup(subject: String)<br>}</pre><p>we also have a Student class that implements this interface as below :</p><pre>class Student : StudentActivities {<br>    override fun joinClub(club: String) {<br>        // join the specified club<br>    }<br><br>    override fun joinSportsTeam(sportsTeam: String) {<br>        // join the specified sports team<br>    }<br><br>    override fun attendEvent(event: String) {<br>        // attend the specified event<br>    }<br><br>    override fun volunteerForEvent(event: String) {<br>        // volunteer for the specified event<br>    }<br><br>    override fun joinStudyGroup(subject: String) {<br>        // join the specified study group<br>    }<br>}</pre><p>In this example, you will notice the Student class is forced to implement all the methods of the StudentActivities interface, even if the student may not be interested in all the activities defined in the interface. This violates the Interface Segregation Principle because the interface is too broad and not cohesive.</p><p>Let refactor to the correct above example now, we can break the StudentActivities interface into smaller, more focused interfaces that are easier for clients to consume:</p><pre>interface ClubActivities {<br>    fun joinClub(club: String)<br>}<br><br>interface SportsActivities {<br>    fun joinSportsTeam(sportsTeam: String)<br>}<br><br>interface EventActivities {<br>    fun attendEvent(event: String)<br>    fun volunteerForEvent(event: String)<br>}<br><br>interface StudyGroupActivities {<br>    fun joinStudyGroup(subject: String)<br>}<br><br>class Student : ClubActivities, SportsActivities, EventActivities, StudyGroupActivities {<br>    override fun joinClub(club: String) {<br>        // join the specified club<br>    }<br><br>    override fun joinSportsTeam(sportsTeam: String) {<br>        // join the specified sports team<br>    }<br><br>    override fun attendEvent(event: String) {<br>        // attend the specified event<br>    }<br><br>    override fun volunteerForEvent(event: String) {<br>        // volunteer for the specified event<br>    }<br><br>    override fun joinStudyGroup(subject: String) {<br>        // join the specified study group<br>    }<br>}</pre><p>In this refactored version, we split down the StudentActivities interface into four smaller, more focused interfaces: ClubActivities, SportsActivities, EventActivities, and StudyGroupActivities. The Student class now implements only the interfaces that are relevant to its behavior.</p><p>This adheres to the <strong>Interface Segregation Principle</strong> because clients that need only a <strong><em>specific subset of the activities defined in the interfaces</em></strong> can now depend only on the corresponding smaller interface, rather than having to depend on a larger, less cohesive interface that contains methods they don’t need.</p><p>Thank you for taking the time to read this article. I hope that my writing has been informative and thought-provoking.I will explain about <strong>Dependency Inversion Principle (DIP) </strong>in next article. Happy Coding to all of you.</p><p><strong>Previous Article about SOLID :</strong></p><p><strong>Single Responsibility Principle (SRP)</strong> : <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-e7b5cfe8c7a1">https://medium.com/arpalar-tech/solid-from-zero-to-potato-e7b5cfe8c7a1</a></p><p><strong>Open/Closed Principle (OCP):</strong> <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-2-5a4c17bd8ec8">https://medium.com/arpalar-tech/solid-from-zero-to-potato-2-5a4c17bd8ec8</a></p><p><strong>Liskov Substitution Principle (LSP):</strong> <a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-3-94d6f63dbbfe">https://medium.com/arpalar-tech/solid-from-zero-to-potato-3-94d6f63dbbfe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d9b42c3a78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arpalar-tech/solid-from-zero-to-potato-4-d1d9b42c3a78">SOLID — From Zero To Potato 4</a> was originally published in <a href="https://medium.com/arpalar-tech">Arpalar Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>