<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Michael Avoyan on Medium]]></title>
        <description><![CDATA[Stories by Michael Avoyan on Medium]]></description>
        <link>https://medium.com/@michael.avoyan?source=rss-7c4072671c12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cIm77vuVgoHuW2W4ibCldg.png</url>
            <title>Stories by Michael Avoyan on Medium</title>
            <link>https://medium.com/@michael.avoyan?source=rss-7c4072671c12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:54:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michael.avoyan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[When AI Makes Code Cheaper, SDK Architecture Matters More]]></title>
            <link>https://medium.com/@michael.avoyan/when-ai-makes-code-cheaper-sdk-architecture-matters-more-7bcfecb4e5e3?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcfecb4e5e3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 11:25:13 GMT</pubDate>
            <atom:updated>2026-10-20T15:25:20.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EE-GJHTBbHDmqrsNJoCOzw.png" /></figure><p><em>AI can produce an implementation. It cannot decide which parts of a system should be stable, what consumers can rely on, or how an abstraction should survive change.</em></p><p>Across my career, I’ve built SDKs for different ecosystems: Apple platforms, Android, shared Kotlin, and JavaScript and TypeScript services. Moving between them taught me that cross-platform engineering is not about making every implementation look alike. It is about discovering what must mean the same thing, and what should remain native to its environment.</p><p>That distinction is becoming more important as AI makes implementation faster. When code is easier to produce, the scarce skill shifts: from writing every line to making the right architectural decisions before and around those lines.</p><h3>The Most Important SDK Decisions Are About the Boundary</h3><p>An SDK lives between its own implementation and products it does not control. Its consumers bring their own lifecycle, dependencies, release cadence, conventions, and constraints. The SDK has to provide a useful capability without assuming ownership of the whole application.</p><p>That boundary is where the durable decisions sit. What can a consumer depend on? Which errors are visible, and in what form? Who owns a resource or a retry? What may change without forcing every adopter to change with it?</p><p>These are architectural questions, but they are also product questions. An SDK’s public contract shapes how quickly another team can integrate, how safely it can upgrade, and how much of the SDK’s internal complexity leaks into the consuming application.</p><p>A generated implementation can be elegant and still get the boundary wrong. It may expose details that should remain internal, hide a platform constraint consumers need to understand, or introduce an abstraction that is easy to write but expensive to support.</p><h3>Cross-Platform Experience Is About Knowing What Not to Unify</h3><p>Working across Swift, Objective-C, Kotlin, Java, Kotlin Multiplatform, JavaScript, and TypeScript can look like a tour of languages. For me, the deeper lesson has been about the limits of sameness.</p><p>Each ecosystem brings different expectations for types, concurrency, lifecycle, packaging, and errors. Copying the same surface API everywhere can create the appearance of consistency while making each version less natural, and sometimes less safe in its own environment.</p><p>The useful question is not, “How do I make these implementations identical?” It is, “Which behavior should be consistent for every consumer, and which mechanism should respect the platform?” The meaning of an operation may need to stay stable while its implementation and idiomatic interface differ. A shared layer is valuable when it preserves important semantics and reduces real duplication. It is a liability when it conceals differences that consumers must handle.</p><p>That judgment comes from seeing the same architectural problem expressed through different tools. Language fluency helps, but the harder skill is separating the invariant from the incidental.</p><h3>AI Makes the First Draft Abundant. It Does Not Make Context Abundant.</h3><p>AI can help explore a codebase, sketch alternatives, draft adapters, and produce tests or documentation. It lowers the effort of getting from an idea to something concrete. That changes the workflow: teams can investigate more options and implement a selected direction with less repetitive work.</p><p>But the output is only as grounded as the context and constraints behind it. AI does not automatically know which API is already a promise to consumers, which platform difference is intentional, which dependency cannot be upgraded, or which trade-off the organization has chosen to own.</p><p>That context is architecture. If it is missing, code generation does not fill the gap; it turns uncertainty into code. The result may pass a local test while increasing coupling, weakening compatibility, or making future change harder.</p><p>So the architect’s work does not disappear when implementation accelerates. It moves closer to the decisions that shape what gets generated: clarifying the system boundary, making constraints explicit, comparing trade-offs, and defining what evidence will count as correct.</p><h3>Design the Contract Before You Generate the Implementation</h3><p>In AI-assisted SDK work, I would start with a few questions before asking for code:</p><ul><li>Who consumes this capability, and what must they be able to rely on?</li><li>What belongs in the stable public contract, and what should remain an implementation detail?</li><li>Which behaviors must match across platforms, and where should each platform retain its own idiom?</li><li>How are failure, cancellation, lifecycle, and resource ownership represented?</li><li>What compatibility and migration promises will constrain future changes?</li></ul><p>Once those questions have answers, AI becomes much more useful. It can implement a bounded design, surface inconsistencies between platform versions, or help create tests tied to explicit behavior. Without that foundation, a fast implementation can simply make the wrong abstraction harder to undo.</p><h3>Verification Must Follow the Boundary</h3><p>SDK correctness cannot be measured only inside the SDK repository. Unit tests can show that internal behavior works under chosen conditions. They cannot, by themselves, prove that the library integrates cleanly into the different applications that depend on it.</p><p>Verification should match the promises the SDK makes: supported runtimes and dependencies, consumer-facing API behavior, failure paths, lifecycle interactions, and upgrade compatibility. Documentation and examples deserve the same attention. They are often the first real integration surface a consumer encounters.</p><p>AI can help generate tests, but a larger test suite is not automatically stronger evidence. Tests need to represent consumer expectations, not merely confirm the implementation’s assumptions. And where a real device, runtime, or consumer application has not been checked, that gap should remain visible rather than being disguised by a successful build.</p><h3>The New Leverage Is Architectural Judgment</h3><p>When implementation took more time, writing code could feel like the center of engineering. AI changes that balance. It can make the first version arrive sooner, but it also makes it easier to create more code than a team can thoughtfully support.</p><p>For SDKs, the consequence is clear: the differentiator is not who can generate the most code or reproduce the same interface in the most languages. It is who can choose a boundary that consumers understand, preserve the right invariants across ecosystems, and evolve the contract without trapping adopters in yesterday’s decisions.</p><p>My experience across platforms has reinforced that architecture is not the diagram drawn before implementation. It is the set of choices that keeps an SDK coherent as languages, consumers, and requirements differ and as the implementation changes.</p><p><strong>AI makes it easier to build what we ask for. The enduring engineering skill is knowing what is worth asking for and designing it so other teams can depend on it.</strong></p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcfecb4e5e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AI Development Loops]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-ai-development-loops-8639212f635b?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/8639212f635b</guid>
            <category><![CDATA[ai-loop]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 17:19:40 GMT</pubDate>
            <atom:updated>2026-10-20T15:24:37.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogrLEBGoqfDC-avXgoKPDA.png" /></figure><p>Most engineers treat AI coding assistants like a smarter autocomplete. They write a prompt, get code back, fix what is wrong, and move on. That works until it doesn’t, which is somewhere around the third feature of any project with real complexity.</p><p>The engineers who get dramatically different results from the same tools do one thing differently: <em>they loop</em>. They treat AI interaction as a process, not a transaction. They design systems of prompts that feed into each other, produce verifiable artifacts, check their own output, and iterate to a defined quality bar before moving on.</p><p>This article is about those systems. Not the basics of AI-assisted development, if you are still figuring out how to get Claude Code to generate a function, this is the wrong starting point. This is for engineers who already use AI assistants daily and want to close the gap between “AI makes me faster” and “AI makes my software better.”</p><p><strong><em>The difference is loops.</em></strong></p><h3><strong>PART 1: WHY ONE-SHOT PROMPTING IS A CEILING</strong></h3><p>One-shot prompting has a well-known failure mode: the model gives you something plausible that is wrong in a way you cannot immediately detect. It compiles. It looks reasonable. It fails at runtime, or worse, passes tests that should not have passed.</p><p>The reason is statistical. A language model predicts the most likely next token given everything before it. For common patterns: CRUD endpoints, authentication boilerplate, standard sorting algorithms, “most likely” is often correct. For your specific architecture, your domain logic, your edge cases, “most likely” is a guess dressed up as confidence.</p><p>One-shot prompting also collapses a complex task into a single inference pass. You ask for a complete feature. The model generates something complete. You look at whether it is right. You were never going to be able to verify a full feature in one pass, so you scan it, miss things, and ship problems.</p><p>Loops solve both problems. They break the work into steps where each step has a verifiable output. They feed the output of one step into the next as grounding context, which keeps the model anchored to concrete artifacts rather than generating from abstract descriptions. And they create checkpoints where a human, or another AI agent validates before proceeding.</p><p>The performance gap is not marginal. Teams that structure their AI work as iterative loops consistently report fewer regressions, higher test coverage, and code that stays maintainable longer than teams that use one-shot generation. The model is the same. The process is not.</p><h4><strong>THE ANATOMY OF AN AI LOOP</strong></h4><p>Every loop has four components:</p><ol><li><strong>Input:</strong> <em>what you feed into the iteration. This can be a prompt, previous output, test results, benchmark data, a diff, or a combination.</em></li><li><strong>Agent:</strong> <em>the AI model or specialized configuration performing the work. In multi-agent setups, different agents handle different steps.</em></li><li><strong>Output:</strong> <em>a concrete artifact. Code, tests, a plan document, a review comment, a benchmark result, a documentation page. Vague outputs break loops.</em></li><li><strong>Exit condition:</strong> <em>the measurable criterion that determines whether you move on or iterate again. Without a defined exit condition, a loop runs forever or stops arbitrarily.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*QDEWPHZ_7t-JC8oHES8WeQ.png" /></figure><p>The exit condition is the part most engineers skip. “Does the code look okay?” is not an exit condition. “All 47 unit tests pass, coverage is above 80%, no High or Critical findings in the security scan” is. You define exit conditions before you start, not after you see the output.</p><h3><strong>PART 2: THE SIX CORE LOOP PATTERNS</strong></h3><h4><strong>2.1 Planning → Implementation → Review</strong></h4><p>This is the most commonly skipped loop and the one with the highest leverage. Engineers want to write code, not plans. The planning step feels like overhead. <strong>It is not.</strong></p><h4><strong>Phase 1: Planning</strong></h4><p>Ask the AI to produce a detailed plan for the feature. Not code. A plan with:</p><ul><li>Defined interfaces and contracts</li><li>Layer boundaries and dependency direction</li><li>Data flow from input to output</li><li>Edge cases and error states</li><li>Test strategy</li><li>File structure</li></ul><h4><strong>Phase 2: Implementation</strong></h4><p>Implement against the plan. Treat the plan as the spec. Any deviation from the plan is either a deliberate decision (document it) or drift (fix it).</p><h4><strong>Phase 3: Review</strong></h4><p>Ask the AI to review the implementation against the plan. Give it both artifacts. Ask it to identify:</p><ul><li>Deviations from the agreed architecture</li><li>Unimplemented edge cases</li><li>Missing error states</li><li>Test gaps</li></ul><p>Then iterate. The review output becomes the input for the next implementation pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5ETQW_Vb8B7eyyVrPjGKQ.png" /></figure><p><strong>Exit condition:</strong> review output returns zero High-severity gaps and implementation matches the plan’s interface contracts.</p><h4><strong>Prompt Template: Planning Phase</strong></h4><p>Role<em>:</em></p><p><em>You are a senior mobile/backend architect.</em></p><p>Context:</p><p><em>[Paste your architectural context document here: MVVM pattern, layer structure, DI approach, existing interfaces, etc.]</em></p><p>Task:</p><p><em>Produce a detailed implementation plan for the [Feature Name] feature.</em></p><p>Requirements:</p><ul><li><em>Define all new interfaces and their contracts</em></li><li><em>Specify which existing interfaces are consumed</em></li><li><em>Map data flow: UI event → ViewModel → UseCase → Repository → Data</em></li><li><em>List all error states and how they surface to the UI</em></li><li><em>Define the UI state model (sealed class / enum)</em></li><li><em>Propose file structure with layer assignments</em></li><li><em>Outline test strategy: what to test, at which layer, with which approach</em></li></ul><p>Constraints:</p><ul><li><em>Domain layer must not import Android/iOS framework code</em></li><li><em>All dependencies injected via constructor</em></li><li><em>No business logic in UI layer</em></li></ul><p>Output format:</p><ul><li><em>Markdown document with numbered sections</em></li><li><em>File tree</em></li><li><em>Interface definitions (pseudocode is fine at this stage)</em></li><li><em>Checklist of implementation steps</em></li></ul><p>Do NOT generate implementation code yet.</p><p><strong>Prompt Template: Review Phase</strong></p><p>Role:</p><p><em>You are a senior code reviewer with deep knowledge of Clean Architecture.</em></p><p>Context:</p><p><em>[Paste the plan document produced in </em><strong><em>Phase 1</em></strong><em>]</em></p><p>Artifacts to review:</p><p><em>[Paste the implemented code or link to diff]</em></p><p>Task:</p><p><em>Compare the implementation against the plan. Identify:</em></p><p><em>1. Deviations from agreed architecture</em></p><ul><li><em>Missing interfaces</em></li><li><em>Wrong layer assignments</em></li><li><em>Violated dependency directions</em></li></ul><p><em>2. Unimplemented requirements</em></p><ul><li><em>Edge cases from the plan that have no handling</em></li><li><em>Error states that are swallowed or not surfaced</em></li></ul><p><em>3. Test gaps</em></p><ul><li><em>Test cases mentioned in the plan that are missing</em></li><li><em>Branches with no test coverage</em></li></ul><p><em>4. Quality issues</em></p><ul><li><em>Business logic in the wrong layer</em></li><li><em>Missing dependency injection</em></li></ul><p><em>Output format:</em></p><ul><li><em>Severity: High / Medium / Low</em></li><li><em>Location: file and function name</em></li><li><em>Issue description</em></li><li><em>Suggested fix</em></li></ul><h4><strong>Best Practices: Planning → Implementation → Review</strong></h4><ul><li>Produce the plan as a committed document, not a prompt artifact. It belongs in your repo under /docs or /specs, reviewed like code.</li><li>Never skip the review phase because “it looks fine.” The model that wrote the code will not spontaneously catch its own architectural drift.</li><li>When the review finds gaps, do not re-plan from scratch. Produce a targeted fix list and iterate on implementation only.</li><li>Three iterations is usually the ceiling. If you are still finding High-severity issues after three passes, the plan itself is the problem.</li></ul><h4><strong>2.2 Developer → QA → Fix</strong></h4><p>This pattern separates code generation from test generation from defect resolution. Each phase has a different objective and a different model configuration.</p><p>The common mistake is asking the AI to “write the code and the tests at the same time.” Tests written by the same agent in the same context as the implementation tend to test what was implemented, not what should be implemented. They inherit the same blind spots.</p><p>Separating the phases forces the QA step to be adversarial. You can even use a different model or system prompt for the QA agent to make it structurally independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GGNfcQQKok2JfpwcOOJ9Q.png" /></figure><p>Exit condition: all generated tests pass, coverage threshold met (define this in advance 80% line coverage is a reasonable minimum for domain and ViewModel layers).</p><h4><strong>Prompt Template: QA Phase (Adversarial)</strong></h4><p>Role:</p><p><em>You are a QA engineer. Your job is to break the implementation, not to validate it.</em></p><p>Context:</p><p><em>[Paste the plan document]</em></p><p>Implementation to test:</p><p><em>[Paste the code]</em></p><p>Task:</p><p><em>Write a comprehensive test suite for this implementation.</em></p><p><em>Approach:</em></p><ul><li><em>Do NOT assume the implementation is correct</em></li><li><em>Start from the requirements in the plan, not from the code</em></li><li><em>Write tests that would catch deviations from the plan</em></li><li><em>Include: Happy path; All error states defined in the plan; Boundary conditions; Invalid inputs; Concurrent access (if applicable); State transition sequences (initial → loading → success/error)</em></li></ul><p><em>Test naming convention:</em></p><p><em>givenCondition_whenAction_thenExpectedResult</em></p><p><em>Constraints (Android):</em></p><ul><li><em>Use coroutine test utilities (runTest, StandardTestDispatcher)</em></li><li><em>Mock repositories, not use cases</em></li><li><em>Do not import Android framework in domain tests</em></li></ul><p><em>Constraints (iOS):</em></p><ul><li><em>Use async/await with XCTest</em></li><li><em>Test @Published transitions with XCTestExpectation</em></li></ul><p><em>Output:</em></p><ul><li><em>Complete test files, ready to run</em></li><li><em>Coverage summary: which paths are covered, which are deliberately excluded and why</em></li></ul><h4><strong>Best Practices: Developer → QA → Fix</strong></h4><ul><li>Run the generated tests before fixing failures. If the suite itself does not compile, fix the tests first.</li><li>When tests reveal architectural problems (not just bugs), fix the architecture. Do not write code that makes wrong tests pass.</li><li>Set a max iteration count (typically 3). If tests still fail after three fix cycles, the QA agent has likely generated incorrect tests or the plan was wrong. Stop, review, and restart with a corrected plan.</li><li>Track which tests were auto-generated versus human-authored. Auto-generated tests should be reviewed before being treated as the source of truth.</li></ul><h4><strong>2.3 Generate → Test → Debug</strong></h4><p>This pattern is close to Developer → QA → Fix but is more granular and more automated. Rather than generating an entire feature at once, you generate small units, test them immediately, debug failures, and commit only what passes.</p><p>The key discipline is small batch size. Generate one function or one class at a time. Test it. Debug it. Commit it. Move on.</p><h4><strong>Prompt Template: Debug Phase</strong></h4><p>Role:</p><p><em>You are a debugging specialist.</em></p><p>Failing test:</p><p><em>[Paste the test]</em></p><p>Expected behavior:</p><p><em>[Paste the relevant section of the plan]</em></p><p>Current implementation:</p><p><em>[Paste the code under test]</em></p><p>Test output:</p><p><em>[Paste the actual test failure output: stack trace, assertion failure, etc.]</em></p><p>Task:</p><p><em>Diagnose the failure. Determine whether:</em></p><p><em>1. The implementation is wrong (fix the implementation)</em></p><p><em>2. The test expectation is wrong (fix the test, explain why)</em></p><p><em>3. The plan has a gap (identify what is missing)</em></p><p><em>Provide:</em></p><ul><li><em>Root cause analysis (2-3 sentences)</em></li><li><em>Fix (code change only, no new features)</em></li><li><em>Explanation of why the fix is correct</em></li></ul><p><em>Constraints:</em></p><ul><li><em>Do not change test assertions to match wrong behavior</em></li><li><em>Do not add workarounds that hide the underlying issue</em></li><li><em>If the fix requires changing the plan, say so explicitly</em></li></ul><h4><strong>Best Practices: Generate → Test → Debug</strong></h4><ul><li>“Small batch size” is the single most effective thing you can do to make AI debugging reliable. The model debugs a 50-line function with high accuracy. It debugs a 500-line class with much lower accuracy because the search space for the root cause is too large.</li><li>Always include the actual test output, not a description of the failure. “The test fails” is not useful. The stack trace is.</li><li>If the model suggests changing the test to match the output, reject that suggestion unless it can justify why the test expectation was wrong against the original requirements.</li></ul><h4><strong>2.4 Refactor → Benchmark → Optimize</strong></h4><p>Optimization without measurement is guessing. This loop enforces measurement at every step.</p><p>Phase 1:</p><p><em>Refactor: clean the code without changing behavior. Tests must pass.</em></p><p>Phase 2</p><p><em>Benchmark: run performance tests and record baseline numbers.</em></p><p>Phase 3</p><p><em>Optimize: make targeted changes to improve the specific metric that matters. Run benchmarks again. Compare.</em></p><p>The loop continues until the target metric is met or you have exhausted the viable optimization space.</p><h4><strong>Prompt Template: Benchmark Phase</strong></h4><p>Role:</p><p><em>You are a performance engineer.</em></p><p>Code under analysis:</p><p><em>[Paste the function or module]</em></p><p>Context:</p><ul><li><em>Language: [Kotlin/Swift/TypeScript/etc.]</em></li><li><em>Runtime environment: [Android API 26+, iOS 16+, Node 20, etc.]</em></li><li><em>Known constraints: [memory limit, latency target, etc.]</em></li></ul><p>Task:</p><ol><li><em>Identify the top 3 performance risks in this code (be specific: name the line or operation)</em></li><li><em>Propose a benchmarking strategy:</em></li></ol><ul><li><em>What to measure (latency, memory, allocations, throughput)</em></li><li><em>How to measure it (which library, which test harness)</em></li><li><em>What baseline to establish before optimizing</em></li></ul><p><em>3. Write benchmark tests using [Android: Jetpack Microbenchmark / Macrobenchmark / JMH | iOS: XCTest measure / XCTMetric / MetricKit | Web: Benchmark.js / k6]</em></p><p>Output:</p><ul><li><em>Ranked list of performance risks with justification</em></li><li><em>Benchmark test code</em></li><li><em>Baseline measurement targets</em></li></ul><p>Do NOT optimize yet. Measure first.</p><h4><strong>Prompt Template: Optimize Phase</strong></h4><p>Role:</p><p><em>You are a performance engineer.</em></p><p>Benchmark results (before):</p><p><em>[Paste benchmark output]</em></p><p>Performance target:</p><p><em>[e.g., p99 latency &lt; 50ms, heap allocation &lt; 2MB per request]</em></p><p>Current implementation:</p><p><em>[Paste code]</em></p><p>Task:</p><p><em>Propose and implement targeted optimizations to meet the performance target.</em></p><p>Rules:</p><ul><li><em>One optimization at a time</em></li><li><em>All existing tests must remain green after each change</em></li><li><em>Explain why each optimization helps (reference the benchmark data)</em></li><li><em>Do not over-optimize: stop when the target is met</em></li></ul><p><em>For each optimization:</em></p><ul><li><em>Describe the change</em></li><li><em>Predict the expected impact</em></li><li><em>Provide the modified code</em></li></ul><p>After implementation, re-run benchmarks and report delta.</p><h4><strong>Best Practices: Refactor → Benchmark → Optimize</strong></h4><ul><li>Never start with optimization. Refactor first. Clean code is easier to benchmark and the performance problems are easier to see.</li><li>Benchmark the specific operation that matters to your users, not a synthetic microbenchmark that looks good but does not correspond to real usage.</li><li>Commit after each optimization that passes tests and shows measurable improvement. If an optimization makes things worse, roll it back immediately rather than stacking changes.</li></ul><h4><strong>2.5 Security → Review → Remediate</strong></h4><p>Security review is one area where AI loops provide immediate, measurable value. A structured security audit loop finds a class of vulnerabilities that manual review often misses, not because the reviewer is not skilled, but because auditing 500 lines of code for every possible injection vector, authentication bypass, and data leak is exhausting and error-prone.</p><p>The loop is not a replacement for a human security audit. It is a pre-filter that catches common issues before the expensive human review even starts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFg16ga2SuNbatimdQabjQ.png" /></figure><h4><strong>Prompt Template: Security Review Phase</strong></h4><p>Role:</p><p><em>You are a security engineer conducting a threat-focused code review. You are looking for vulnerabilities, not style issues.</em></p><p>Code under review:</p><p><em>[Paste the code]</em></p><p>Context:</p><ul><li><em>Application type: [Mobile/API/Web]</em></li><li><em>Authentication mechanism: [JWT/OAuth/Session]</em></li><li><em>Data sensitivity: [PII handled? Payment data? Auth tokens?]</em></li><li><em>Platform: [Android/iOS/Node/etc.]</em></li></ul><p>Review checklist: check every item:</p><p><em>OWASP Mobile Top 10 (if applicable):</em></p><p><em>M1: Improper Platform Usage</em></p><p><em>M2: Insecure Data Storage</em></p><p><em>M3: Insecure Communication</em></p><p><em>M4: Insecure Authentication</em></p><p><em>M5: Insufficient Cryptography</em></p><p><em>M6: Insecure Authorization</em></p><p><em>M7: Client Code Quality</em></p><p><em>M8: Code Tampering</em></p><p><em>M9: Reverse Engineering</em></p><p><em>M10: Extraneous Functionality</em></p><p>General:</p><ul><li><em>SQL / command injection vectors</em></li><li><em>Unvalidated inputs at trust boundaries</em></li><li><em>Hardcoded secrets or credentials</em></li><li><em>Sensitive data in logs</em></li><li><em>Token storage in insecure locations</em></li><li><em>Missing certificate pinning</em></li><li><em>Exposed API keys in client code</em></li><li><em>Error messages that leak internal state</em></li><li><em>Race conditions in auth flows</em></li><li><em>Missing rate limiting or brute-force protection</em></li></ul><p>Output format:</p><ul><li><em>Severity: Critical / High / Medium / Low / Informational</em></li><li><em>OWASP category</em></li><li><em>File and line number</em></li><li><em>Description of the vulnerability</em></li><li><em>Proof-of-concept exploitation path (where applicable)</em></li><li><em>Recommended fix</em></li></ul><p><strong>Exit condition:</strong> zero Critical and zero High findings after remediation.</p><h4><strong>Best Practices: Security → Review → Remediate</strong></h4><ul><li>Run this loop on every PR that touches authentication, authorization, data storage, network communication, or user input handling. Not just on “security-sensitive” features, most features touch at least one of these.</li><li>The remediation agent must re-run the full security review after applying fixes. Patches introduce new bugs. Re-scan.</li><li>Track the pattern of findings across features. If SQL injection appears three times in three different places, you have a process problem, not a code problem.</li><li>Do not suppress findings without documentation. Every “accepted risk” should be a committed decision record.</li></ul><h4><strong>2.6 Documentation → Validation → Improvement</strong></h4><p>Generated documentation has a short shelf life if it is not validated against the code. The loop keeps documentation alive.</p><p>Phase 1:</p><p><em>Generate: produce documentation from code and architectural context.</em></p><p>Phase 2</p><p><em>Validate: check that the documentation accurately describes the code as it is now, not as it was when the docs were first written.</em></p><p>Phase 3</p><p><em>Improve: fix discrepancies and add anything the validation step flagged as missing.</em></p><h4><strong>Prompt Template: Validation Phase</strong></h4><p>Role:</p><p><em>You are a technical writer and quality reviewer.</em></p><p>Documentation:</p><p><em>[Paste the documentation page]</em></p><p>Current implementation:</p><p><em>[Paste the code it describes]</em></p><p>Task:</p><p><em>Identify every discrepancy between the documentation and the implementation:</em></p><ol><li><em>Incorrect descriptions (the code does X but the docs say Y)</em></li><li><em>Missing coverage (the code does X but the docs do not mention it)</em></li><li><em>Outdated references (the docs reference functions, classes, or parameters that no longer exist)</em></li><li><em>Incorrect data flow diagrams (if present)</em></li><li><em>Missing error states</em></li><li><em>Missing or wrong API contracts</em></li></ol><p>Output:</p><ul><li><em>List of discrepancies with severity (Blocker / Major / Minor)</em></li><li><em>For each discrepancy: what the docs say vs. what the code does</em></li><li><em>Suggested correction</em></li></ul><h4><strong>Best Practices: Documentation → Validation → Improvement</strong></h4><ul><li>Tie documentation validation to your CI pipeline. Run it on every PR that changes documented code. If the diff touches a file referenced in a docs page, trigger the validation loop.</li><li>Generate documentation in Markdown and commit it alongside the code. Documentation that lives only in a wiki drifts faster.</li><li>The validation step is more valuable than the generation step. Any AI can generate plausible documentation. Only a validation loop can catch when that documentation becomes wrong.</li></ul><h3><strong>PART 3: MULTI-AGENT WORKFLOWS</strong></h3><p>A single AI agent does everything with average quality. Specialized agents do one thing well. The difference becomes obvious when you need the code to be simultaneously well-architected, well-tested, secure, and documented, which is always.</p><p>Multi-agent workflows assign each concern to a specialized agent configuration. Each agent has:</p><ul><li>A fixed role in its system prompt</li><li>A defined input format</li><li>A defined output format</li><li>A defined handoff protocol to the next agent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*dWbG-U4a6qtK84s6oc3q_A.png" /></figure><h4><strong>Agent Role Configurations</strong></h4><p>Below is a practical system prompt template for each agent type. In tools that support system prompts or persistent instruction files (Cursor rules, Claude Code’s CLAUDE.md, Windsurf rules), these become the default mode for that agent.</p><h4><strong>Architect Agent</strong></h4><p>Role:</p><p><em>You are a software architect. You do not write implementation code. Your output is specifications, interface definitions, and architectural decisions.</em></p><p>Responsibilities:</p><ul><li><em>Define system contracts before any code is written</em></li><li><em>Enforce Clean Architecture (Presentation → Domain → Data)</em></li><li><em>Identify cross-cutting concerns (auth, logging, error handling)</em></li><li><em>Produce diagrams and specifications in Markdown</em></li></ul><p>Rules:</p><ul><li><em>Never generate implementation code in your output</em></li><li><em>Always define dependency direction explicitly</em></li><li><em>Flag any requirement that violates stated architectural principles</em></li><li><em>Every interface you define must include: inputs, outputs, error states</em></li></ul><h4><strong>Developer Agent</strong></h4><p>Role:</p><p><em>You are a software developer. You implement against specifications. You do not make architectural decisions.</em></p><p>Responsibilities:</p><ul><li><em>Implement exactly what the specification defines</em></li><li><em>If the specification is ambiguous, ask before implementing</em></li><li><em>Write clean, well-named code with no business logic in the wrong layer</em></li><li><em>Generate stub tests alongside implementation (full tests are the QA agent’s job)</em></li></ul><p>Rules:</p><ul><li><em>If the spec and a simpler implementation conflict, follow the spec</em></li><li><em>No deviations from agreed layer boundaries</em></li><li><em>Raise a flag if any requirement is technically infeasible as specified</em></li></ul><h4><strong>QA Agent</strong></h4><p>Role:</p><p><em>You are an adversarial QA engineer. Your objective is to find failures in the implementation, not to confirm it works.</em></p><p>Responsibilities:</p><ul><li><em>Write tests from the specification, not from the code</em></li><li><em>Treat the implementation as potentially wrong</em></li><li><em>Cover all stated error states and edge cases</em></li><li><em>Define coverage requirements before writing tests</em></li></ul><p>Rules:</p><ul><li><em>Never modify test assertions to match wrong implementation behavior</em></li><li><em>If a test reveals a specification gap, flag it, do not paper over it</em></li><li><em>Your test suite must be runnable with zero manual setup</em></li></ul><h4><strong>Security Agent</strong></h4><p>Role:</p><p><em>You are a security engineer. You review code for vulnerabilities. You do not fix code, you produce findings for the remediation agent.</em></p><p>Responsibilities:</p><ul><li><em>Check every trust boundary for validation failures</em></li><li><em>Identify data that could be exposed or leaked</em></li><li><em>Audit authentication and authorization logic</em></li><li><em>Review token handling and storage</em></li></ul><p>Rules:</p><ul><li><em>Every finding must have a severity and a concrete exploitation path</em></li><li><em>Do not flag theoretical risks without a plausible attack vector</em></li><li><em>Mark findings as “accepted risk” only when there is a documented business reason</em></li></ul><h4><strong>Performance Agent</strong></h4><p>Role:</p><p><em>You are a performance engineer. You measure before you optimize.</em></p><p>Responsibilities:</p><ul><li><em>Establish baseline measurements for every optimization target</em></li><li><em>Identify the top bottlenecks with evidence from profiling data</em></li><li><em>Implement targeted optimizations one at a time</em></li><li><em>Re-measure after every change</em></li></ul><p>Rules:</p><ul><li><em>Never optimize without a measurement baseline</em></li><li><em>Stop optimizing when the target is met, not when the code is “as fast as possible”</em></li><li><em>All optimizations must leave the test suite green</em></li></ul><h4><strong>Practical Tooling for Multi-Agent Workflows</strong></h4><p><strong>Claude Code:</strong> use separate conversation sessions with different <em>CLAUDE.md</em> configurations per agent role, or use the subagent spawning capabilities in agentic mode.</p><p><strong>Cursor: </strong>maintain separate rule files per agent type in <em>.cursor/rules/</em>. Switch rule sets when switching roles.</p><p><strong>GitHub Copilot: </strong>use different system prompt files for Copilot Chat per role, loaded from your project context.</p><p>Multi-agent orchestration tools <em>(LangGraph, CrewAI, AutoGen)</em>: wire the agents as a pipeline with explicit handoffs and artifact passing between steps.</p><h4><strong>Best Practices: Multi-Agent Workflows</strong></h4><ul><li>Enforce agent isolation. An architect agent that also writes implementation code defeats the purpose. The value comes from the structural independence between roles.</li><li>Persist agent outputs as committed artifacts. The spec document, the QA report, the security findings, these belong in your repository, not in a chat window. They are the audit trail of your development process.</li><li>Build explicit handoff protocols. Every agent receives a defined input format and produces a defined output format. Loose handoffs (“here is some context”) produce loose results.</li><li>Use different models for adversarial roles. The QA agent finds more bugs if it was not the one that wrote the code. Where you have model choice, use a different model or a fresh context for QA and security.</li></ul><h3><strong>PART 4: RECURSIVE IMPROVEMENT LOOPS WITH QUALITY GATES</strong></h3><p>A quality gate is a measurable condition that must be true before the loop advances. Without quality gates, you iterate until you feel good about the result, which is subjective, inconsistent, and frequently wrong.</p><p>Quality gates force you to define “done” before you start, which has the useful side effect of revealing when “done” is underspecified.</p><h4><strong>Defining Quality Gates</strong></h4><p><strong>For each loop, define gates at three levels:</strong></p><p><strong>Functional gates:</strong> the code does what it should do.</p><ul><li>All tests pass</li><li>Test coverage above threshold (specify the threshold)</li><li>No unhandled error paths from the spec</li></ul><p><strong>Structural gates: </strong>the code is built correctly.</p><ul><li>No Clean Architecture violations (domain imports no framework code)</li><li>All dependencies injected via constructor</li><li>No business logic in UI layer</li><li>Lint and static analysis clean</li></ul><p><strong>Quality gates: </strong>the code will remain maintainable.</p><ul><li>No Critical or High findings from security scan</li><li>Performance targets met (specify the targets)</li><li>Documentation coverage above threshold</li></ul><h4><strong>Example Quality Gate Specification</strong></h4><p>Feature: <strong>Login</strong></p><p>Functional gate:</p><ul><li><em>LoginUseCaseTest: 100% pass</em></li><li><em>LoginViewModelTest: 100% pass</em></li><li><em>Integration test: login flow passes end-to-end</em></li><li><em>Coverage: domain layer &gt;= 90%, presentation layer &gt;= 80%</em></li></ul><p>Structural gate:</p><ul><li><em>No Android imports in domain/ directory</em></li><li><em>No business logic in LoginScreen.kt or LoginView.swift</em></li><li><em>Lint: zero errors, zero warnings</em></li><li><em>Architecture check: ArchUnit (Android) / SwiftLint + custom rules (iOS)</em></li></ul><p>Quality gate:</p><ul><li><em>Security scan: zero Critical, zero High findings</em></li><li><em>Login latency: p95 &lt; 800ms under simulated network conditions</em></li><li><em>Memory: no leaks detected in LeakCanary / Instruments</em></li></ul><p><strong>Loop terminates when: all three gates pass on the same iteration.</strong></p><p>Recursive Loop Structure with Quality Gates</p><h4><strong>Prompt Template: Gate Check</strong></h4><p>Role:</p><p><em>You are a quality engineer performing a gate check.</em></p><p>Quality gates:</p><p><em>[Paste your gate specification here]</em></p><p>Current artifacts:</p><ul><li><em>Test results: [paste]</em></li><li><em>Coverage report: [paste]</em></li><li><em>Lint output: [paste]</em></li><li><em>Security scan results: [paste]</em></li><li><em>Benchmark results: [paste]</em></li></ul><p>Task:</p><p><em>For each gate, state: PASS or FAIL.</em></p><p><em>For each FAIL:</em></p><ul><li><em>Which gate failed</em></li><li><em>What the current value is vs. the required value</em></li><li><em>Which agent should address it (developer, QA, security, performance)</em></li><li><em>Specific action required</em></li></ul><p><em>Do not suggest “acceptable” failures. A gate either passes or it does not.</em></p><p>Output:</p><ul><li><em>Gate summary table (Gate | Status | Current | Required | Owner)</em></li><li><em>Ordered action list for all failures</em></li></ul><h4><strong>Best Practice: Quality Gates</strong></h4><ul><li>Never negotiate quality gates after implementation begins. Define them before you write the first prompt, commit them to the repository, and treat a failed gate as a blocker, not a suggestion.</li><li>Start with fewer gates and higher thresholds. “All tests pass and coverage &gt;= 80%” is better than eight loosely defined gates. Precision matters more than comprehensiveness.</li><li>Automate gate checks in CI. A gate that requires manual verification will be skipped under deadline pressure.</li><li>Log gate results per iteration. You want to see the trend (are things improving?) not just the final state.</li></ul><h3><strong>PART 5: PROMPT ENGINEERING PATTERNS FOR RELIABLE LOOPS</strong></h3><p>Five patterns make AI loops significantly more reliable. Most engineers use one or two of them by accident. All five together create a measurable difference in output consistency.</p><h4><strong>Pattern 1: Role-Context-Constraint-Output (RCCO)</strong></h4><p>Every prompt in a loop should have all four components:</p><p><strong>Role:</strong> what the agent is</p><p><strong>Context:</strong> what it knows about the current state</p><p><strong>Constraint:</strong> what it must not do</p><p><strong>Output:</strong> what it must produce</p><p>Omitting any component degrades reliability. Omitting Role means the model defaults to a generic helpful assistant, which is not what you want for an adversarial QA agent. Omitting Constraint means the model will take convenient shortcuts. Omitting Output means you get whatever format the model prefers, which breaks structured handoffs.</p><h4><strong>Pattern 2: Explicit Negative Space</strong></h4><p>Tell the agent what not to do, not just what to do. AI models are optimized to be helpful, which means they will expand scope, add features, and make “improvements” that break your loop structure.</p><p>Instead of: “Implement the LoginUseCase.”</p><p>Write: <em>“Implement the LoginUseCase as specified. Do not modify LoginRepository. Do not add features not in the spec. Do not change existing tests. Scope is limited to LoginUseCase.kt.”</em></p><h4><strong>Pattern 3: Anchor to Artifacts</strong></h4><p>Each prompt should reference concrete artifacts from previous steps, not abstract descriptions of previous steps.</p><p>Instead of: “Now that we have the plan, implement the feature.”</p><p>Write: <em>“Implement against the specification in [attached/pasted spec document]. Section 3.2 defines the interface you must implement. Section 4.1 defines the error states you must handle.”</em></p><p>The model cannot contradict a specific document. It can invent anything if you give it only a vague reference.</p><h4><strong>Pattern 4: Verification Step Inside the Prompt</strong></h4><p>Ask the model to verify its own output before presenting it.</p><p><strong>Template:</strong></p><p>After generating [output], review it against [criteria] and confirm:</p><ul><li>[criterion 1]: Yes / No + explanation if No</li><li>[criterion 2]: Yes / No + explanation if No</li><li>[criterion 3]: Yes / No + explanation if No</li></ul><p>If any criterion is No, revise before outputting.</p><p>This is not a substitute for external verification, but it catches a significant fraction of obvious errors before they reach the next loop stage.</p><h4><strong>Pattern 5: Step-Locked Output</strong></h4><p>When a loop has multiple phases, lock each phase to a single output type. A planning phase produces only a plan. An implementation phase produces only code. A review phase produces only a review.</p><p>Mixing outputs in a single prompt (“plan the feature and then implement it”) lets the model shortcut the planning step. You end up with an implementation that contains an implicit plan the model never made explicit, which means you cannot review it, verify it, or use it as input to the next stage.</p><h4><strong>Prompt Engineering Anti-Patterns to Avoid</strong></h4><p>“Do your best.” The model does not know what your best is. Specify it.</p><p>“Make it production-ready.” This is not a constraint. Every model believes everything it produces is production-ready.</p><p>Asking for a review and an implementation in the same prompt. You will get an implementation with a review tacked on. The review will not catch what it should.</p><p>Pasting your entire codebase as context for every prompt. Context pollution degrades model performance. Include only what is relevant to the current step.</p><p>Accepting output that changes scope. If you asked for a LoginUseCase fix and the model also modified LoginViewModel “as a helpful improvement,” reject the change to LoginViewModel and ask for a scope-limited resubmission.</p><h3><strong>PART 6: CONTEXT MANAGEMENT FOR LONG-RUNNING IMPLEMENTATIONS</strong></h3><p>Context windows are larger than they were two years ago, but they are still finite, and performance degrades before you hit the hard limit. A 200,000-token context is not a license to dump your entire codebase into every prompt.</p><p>Context management is active work. You decide what is in context at each step.</p><h4><strong>Strategy 1: Progressive Disclosure</strong></h4><p>Start with high-level context. Add detail only when the current step needs it.</p><p>Early phases (planning): architectural context only. Layer descriptions, existing interfaces, domain rules.</p><p>Mid phases (implementation): the spec for this feature plus the interfaces it depends on. Not the full codebase.</p><p>Late phases (debugging): the specific failing test plus the specific function it tests plus the relevant dependencies. Nothing else.</p><h4><strong>Strategy 2: Persistent Context Documents</strong></h4><p>Maintain a set of short, dense context documents that describe your project’s key properties. These are not code comments, they are agent-facing documents that give an AI assistant the essentials without requiring it to read every file.</p><p><strong>architecture.md:</strong> layer structure, dependency rules, naming conventions</p><p><strong>conventions.md:</strong> DI approach, state management pattern, error handling contract</p><p><strong>interfaces.md:</strong> key domain interfaces and their contracts (kept up to date)</p><p>Feed only the relevant documents to each agent, not all of them.</p><h4><strong>Strategy 3: Artifact Summarization</strong></h4><p>As a loop progresses, earlier artifacts (the original plan, the first review pass) become less relevant. Summarize them.</p><p><strong>Prompt Template: Context Summarization</strong></p><p>Role:</p><p><em>You are a technical writer.</em></p><p>Full document:</p><p><em>[Paste the plan or review document]</em></p><p>Task:</p><p><em>Produce a compressed summary for use as context in subsequent loop iterations.</em></p><p>The summary must preserve:</p><ul><li><em>All interface contracts and their signatures</em></li><li><em>All error states and their handling</em></li><li><em>All architectural constraints</em></li><li><em>The current completion status of each section</em></li></ul><p>The summary may omit:</p><ul><li><em>Rationale and explanation (preserve the decision, drop the justification)</em></li><li><em>Examples that are not referenced in constraints</em></li></ul><p>Target length: under 500 words.</p><h4><strong>Strategy 4: File-Based Context for Agentic Tools</strong></h4><p>Claude Code, Cursor, and similar tools that can read your filesystem are better at context management than chat-based tools. Let them read the files rather than pasting everything into the prompt.</p><p>The discipline here is file structure. If your project is organized by Clean Architecture layers, an agent can read exactly the files it needs for the current step. If everything is in one directory, it reads everything or guesses.</p><h4><strong>Strategy 5: Session Boundaries</strong></h4><p>Long-running implementations should have session boundaries. At the end of each session:</p><ol><li>Commit what is done (with a descriptive commit message)</li><li>Update your context documents with current state</li><li>Write a brief handoff note: what was completed, what decisions were made, what comes next</li></ol><p>The next session starts from committed code and explicit context, not from trying to reconstruct state from a long conversation history.</p><h4><strong>Best Practices: Context Management</strong></h4><ul><li>Less context is usually better context. An agent with five relevant files performs better than an agent with fifty partially-relevant files.</li><li>Context documents are code. Review them, version them, update them when the architecture changes.</li><li>When you notice the model “forgetting” earlier constraints mid-conversation, that is a context window pressure signal. Summarize and restart the session.</li><li>Agentic tools with file access (Claude Code, Cursor) need good file organization more than they need good prompts. Structure your project so an agent can navigate it.</li></ul><h3><strong>PART 7: CI/CD INTEGRATION</strong></h3><p>Loops integrated into CI/CD pipelines run automatically on every change, without requiring a developer to remember to run them. This is where iterative AI development scales from a personal productivity practice to a team engineering practice.</p><h4><strong>What CI/CD Integration Looks Like</strong></h4><p><strong>Pre-commit hooks: fast, local checks</strong></p><ul><li><strong>AI-assisted lint check:</strong> catches obvious architectural violations before the commit</li><li><strong>Test generation check:</strong> flags commits that add production code without corresponding tests</li></ul><p><strong>PR checks: runs on every pull request</strong></p><ul><li><strong>Automated code review:</strong> AI reviews the diff for architectural violations, SOLID violations, and common bugs</li><li><strong>Security scan:</strong> runs the Security → Review loop on changed files</li><li><strong>Documentation validation:</strong> checks that changed code has up-to-date documentation</li></ul><p><strong>Post-merge checks: runs on the main branch</strong></p><ul><li><strong>Performance regression detection: </strong>runs benchmarks and compares to baseline</li><li><strong>Coverage trend:</strong> tracks whether coverage is going up or down over time</li><li><strong>Architecture drift detection:</strong> flags when layer boundaries have been violated</li></ul><h4><strong>Example: AI Code Review as a CI Step</strong></h4><p>The following describes a CI-integrated AI review pipeline:</p><ol><li>PR is opened with code changes</li><li>CI extracts the diff (changed files only)</li><li>AI review agent receives:</li></ol><ul><li>The diff</li><li>The architecture context document</li><li>The feature spec (if one exists for this PR)</li><li>The quality gate specification</li></ul><p>4. Agent produces a structured review report</p><p>5. Report is posted as PR comments (High/Critical issues as blocking, Medium/Low as suggestions)</p><p>6. PR cannot be merged until High/Critical review comments are resolved</p><h4><strong>Prompt Template: CI Code Review</strong></h4><p>Role:</p><p><em>You are a code reviewer integrated into a CI pipeline.</em></p><p><em>Your review comments will be posted on a pull request.</em></p><p><em>Be specific. Be brief. Be accurate.</em></p><p>Architectural context:</p><p><em>[Paste architecture.md]</em></p><p>Changed files (diff):</p><p><em>[Paste the diff]</em></p><p>Review for:</p><ol><li><em>Architectural violations (blocking)</em></li></ol><ul><li><em>Domain layer importing framework code</em></li><li><em>Business logic in UI layer</em></li><li><em>Incorrect dependency direction</em></li><li><em>Missing interfaces where required</em></li></ul><p><em>2. SOLID violations (blocking if severe)</em></p><ul><li><em>God classes with multiple responsibilities</em></li><li><em>Missing dependency injection</em></li><li><em>Concrete dependencies where interfaces required</em></li></ul><p><em>3. Common bugs (blocking)</em></p><ul><li><em>Unhandled null/nil paths</em></li><li><em>Main thread blocking in async code</em></li><li><em>Missing error state handling from spec</em></li></ul><p><em>4. Code quality (non-blocking suggestions)</em></p><ul><li><em>Naming clarity</em></li><li><em>Function size</em></li><li><em>Missing tests for new code paths</em></li></ul><p>Output format for each finding:</p><p><em>FILE: path/to/file.kt</em></p><p><em>LINE: 42</em></p><p><em>SEVERITY: Blocking | Suggestion</em></p><p><em>CATEGORY: Architecture | SOLID | Bug | Quality</em></p><p><em>ISSUE: [one sentence description]</em></p><p><em>FIX: [one sentence fix, or “Refactor required” if complex]</em></p><p><em>Post only findings you are confident in.</em></p><p><em>Do not flag style preferences as bugs.</em></p><h4><strong>Integration with Specific Tools</strong></h4><p><strong>Claude Code: </strong>supports automated scripting via its CLI. You can invoke it from a CI script with a pre-constructed prompt and capture structured output.</p><p><strong>GitHub Copilot CLI: </strong>can be integrated into GitHub Actions with the <em>gh copilot</em> commands and custom workflow scripts.</p><p><strong>Cursor:</strong> primarily a local tool for CI integration, use the underlying model API (Anthropic, OpenAI) directly in CI scripts.</p><p><strong>Custom pipelines:</strong> use the model API (Anthropic Claude, OpenAI GPT-4o, Google Gemini) directly in CI scripts. Pass the diff and context as the prompt, parse the structured output, and post comments using the GitHub/GitLab API.</p><h4><strong>Best Practices: CI/CD Integration</strong></h4><ul><li>Start with the review loop only. It is the easiest to integrate, produces immediate value, and requires no changes to developer workflow. Add other loops incrementally.</li><li>Make blocking findings actionable. “Architecture violation” is not a CI comment. “Domain layer (LoginUseCase.kt:34) imports android.util.Log, move logging to the data layer or use a domain-safe logging interface” is.</li><li>Track false positive rate. If developers are regularly marking AI review comments as incorrect, your review prompt has a problem. Review the false positives quarterly and update the prompt.</li><li>Do not let CI AI review replace human review. Use it to handle the repetitive, rule-based checks so human reviewers can focus on logic, design, and domain correctness.</li></ul><h3><strong>PART 8: MINIMIZING HALLUCINATIONS AND PREVENTING REGRESSIONS</strong></h3><p>Hallucinations in code generation are not random. They follow predictable patterns. Understanding the patterns lets you design loops that catch them.</p><h4><strong>Common Hallucination Patterns</strong></h4><p><strong>Invented APIs:</strong> the model generates calls to library methods that do not exist, or uses real methods with wrong signatures.</p><p><strong>Detection: </strong>compilation and test runs catch this immediately. Never review generated code without running it.</p><p><strong>Plausible-but-wrong logic: </strong>the code looks correct for the common case but fails on edge cases that were specified.</p><p><strong>Detection: </strong>adversarial QA (Section 2.2). The QA agent tests from the spec, not from the implementation.</p><p><strong>Architectural drift: </strong>the model gradually moves logic into the wrong layer across multiple iterations, especially if the architecture context is not refreshed.</p><p><strong>Detection: </strong>architecture validation tools (ArchUnit for Android, custom SwiftLint rules for iOS) run in CI.</p><p><strong>Silent requirement omission: </strong>the model implements the happy path and quietly omits error states.</p><p><strong>Detection: </strong>review the spec against the generated code explicitly. Use the review prompt in Section 2.1.</p><p><strong>Stale context hallucination:</strong> in a long session, the model “remembers” an interface from three iterations ago that has since been changed.</p><p><strong>Detection:</strong> session boundaries and artifact summarization (Section 6).</p><h4><strong>Anti-Regression Strategies</strong></h4><p><strong>Strategy 1: Treat the test suite as the regression contract.</strong></p><p>Before any AI-assisted change, run the test suite and record results. After the change, run it again. Any new failure is a regression. This sounds obvious but it is regularly skipped when engineers are moving fast.</p><p><strong>Strategy 2: Commit before every AI-assisted refactor.</strong></p><p>If the model’s refactoring breaks something, you need a clean rollback point. Commit the working state before you start. This is not about protecting against bad AI, it is the same discipline you would apply to any refactoring.</p><p><strong>Strategy 3: Pin the spec.</strong></p><p>When you give the model a spec document, do not let it modify the spec. The spec is the source of truth. If the model suggests changing the spec to accommodate a simpler implementation, that is a conversation to have explicitly, not something that should happen silently.</p><p><strong>Strategy 4: Scope-lock every prompt.</strong></p><p>Every implementation prompt should specify exactly which files the model is allowed to touch. Review the diff before committing. If the model modified files outside its scope, investigate why before accepting the changes.</p><p><strong>Strategy 5: Incremental commits.</strong></p><p>Commit working state after every successful loop iteration. This gives you a clear history of what changed when, and it makes bisecting regressions straightforward.</p><h3><strong>PART 9: BREAKING LARGE FEATURES INTO ITERATIVE PHASES</strong></h3><p>The most common reason AI-assisted development goes wrong on large features is not the AI, it is the feature decomposition. When you hand a large feature to the AI as a single task, you get a large, hard-to-review output with compounded errors.</p><p>Phase decomposition is the practice of breaking a feature into independent, deliverable increments where each increment:</p><ul><li>Can be tested in isolation</li><li>Has its own quality gates</li><li>Produces committed code before the next phase begins</li><li>Has a clear interface to the phases that follow</li></ul><h4><strong>Example: Payment Flow Feature</strong></h4><p>Naive approach: “Implement the full payment flow including cart, payment method selection, Stripe integration, order confirmation, and receipt email.”</p><h4><strong>Phase-decomposed approach:</strong></h4><p><strong>Phase 1:</strong> Domain contracts</p><p>Output: PaymentRepository interface, PaymentUseCase interface, PaymentResult sealed class, error types</p><p>Tests: contract compliance tests (no implementation yet)</p><p>Gate: domain layer has zero framework imports, all interfaces defined</p><p><strong>Phase 2:</strong> Domain logic</p><p>Output: PaymentUseCase implementation, validation logic, business rules</p><p>Tests: full unit test coverage of use case</p><p>Gate: 100% test pass, &gt;= 90% coverage, domain layer still clean</p><p><strong>Phase 3:</strong> Data layer</p><p>Output: StripePaymentRepository, DTO models, mapping logic</p><p>Tests: repository unit tests with mock Stripe SDK</p><p>Gate: tests pass, mapping correctness verified, no secret keys in code</p><p><strong>Phase 4:</strong> Presentation ViewModel</p><p>Output: PaymentViewModel, UI state model</p><p>Tests: ViewModel state transition tests</p><p>Gate: all state transitions tested, ViewModel has no direct data layer dependency</p><p><strong>Phase 5:</strong> Presentation UI</p><p>Output: PaymentScreen (Compose / SwiftUI)</p><p>Tests: UI tests for critical paths</p><p>Gate: UI tests pass, no business logic in UI layer</p><p><strong>Phase 6:</strong> Integration</p><p>Output: end-to-end flow wired together</p><p>Tests: integration tests covering full payment flow</p><p>Gate: integration tests pass, all previous gates still hold</p><p>Each phase ends with a committed, reviewed PR. If Phase 3 introduces a regression in Phase 2, you catch it before Phase 4 begins.</p><h4><strong>Phase Decomposition Prompt Template</strong></h4><p>Role:</p><p><em>You are a software architect.</em></p><p>Feature description:</p><p><em>[Describe the feature]</em></p><p>Existing architecture:</p><p><em>[Paste architecture context]</em></p><p>Task:</p><p><em>Decompose this feature into independent implementation phases.</em></p><p><em>For each phase:</em></p><ul><li><em>Phase name and number</em></li><li><em>Objective (one sentence)</em></li><li><em>Input: what must exist before this phase can start</em></li><li><em>Output: what this phase produces (files, interfaces, tests)</em></li><li><em>Quality gate: measurable pass criteria</em></li><li><em>Dependencies: which other phases depend on this phase’s output</em></li></ul><p>Rules:</p><ul><li><em>Each phase must be independently testable</em></li><li><em>No phase produces code that depends on unimplemented future phases</em></li><li><em>Each phase ends with committable, reviewable code</em></li><li><em>Domain layer phases must precede data layer phases must precede presentation phases</em></li></ul><p>Output:</p><p><em>Markdown document with numbered phases, in dependency order.</em></p><h4><strong>Best Practices: Feature Decomposition</strong></h4><ul><li>If you cannot define a testable output for a phase, the phase is not well-defined. Keep decomposing.</li><li>Domain-first ordering is not optional for Clean Architecture projects. Defining interfaces before implementations is what makes each phase independently testable.</li><li>The phase document belongs in your repository alongside the code. When a phase is complete, mark it in the document and commit the update.</li></ul><h3><strong>PART 10: GIT WORKFLOW BEST PRACTICES FOR AI LOOPS</strong></h3><p>AI-assisted development produces code faster than manual development. That speed makes git discipline more important, not less. Without it, you end up with large, hard-to-review commits that mix AI-generated code with human edits and contain changes that span multiple logical phases.</p><h4><strong>Commit Protocol for AI Loops</strong></h4><h4><strong>Rule 1: One loop iteration, one commit.</strong></h4><p>Each successful loop iteration (passing all defined gate checks for that phase) produces exactly one commit. The commit message describes what the loop produced, not what you asked the AI to do.</p><p>Good: “Add LoginUseCase with test coverage, all domain gate checks pass”</p><p>Bad: “AI-generated login code”</p><h4><strong>Rule 2: Never commit unreviewed AI output.</strong></h4><p>This sounds obvious. It is regularly violated when engineers are moving quickly. Every AI-generated file gets read before it gets staged. Every. File.</p><h4><strong>Rule 3: Branch per feature phase.</strong></h4><p>Each phase of a feature decomposition gets its own branch, not a feature branch that accumulates all phases. This makes PR review tractable, a reviewer can look at the domain phase diff without seeing the UI changes.</p><p><strong>Branch naming convention:</strong></p><p><em>feature/[feature-name]/phase-[n]-[description]</em></p><p><strong>Example:</strong></p><p><em>feature/payment/phase-1-domain-contracts</em></p><p><em>feature/payment/phase-2-use-case</em></p><p><em>feature/payment/phase-3-stripe-repository</em></p><h4><strong>Rule 4: Commit the spec alongside the code.</strong></h4><p>When Phase 1 of a feature produces a spec document, commit the spec on the same branch as the Phase 1 code. The spec is the context for future reviews. Without it in the repo, reviewers are reviewing code without a spec.</p><h4><strong>Rule 5: Include AI loop results in commit descriptions.</strong></h4><p>Example commit message format:</p><p>feat(payment): implement PaymentUseCase with validation</p><p>Phase 2 of payment feature decomposition.</p><p>Gate check results:</p><ul><li>Unit tests: 12/12 pass</li><li>Domain coverage: 94%</li><li>Architecture check: clean (zero framework imports)</li><li>Security scan: no findings</li></ul><p>Changes:</p><ul><li>domain/usecase/PaymentUseCase.kt</li><li>domain/usecase/PaymentUseCaseTest.kt</li></ul><p>Spec reference: docs/specs/payment-feature.md (Phase 2)</p><p>This is visible history. Six months later, a new engineer can look at any commit and understand what process produced it and what quality checks it passed.</p><h4><strong>PR Review Protocol</strong></h4><p>When submitting a PR from an AI loop phase:</p><p>Include in the PR description:</p><ul><li>Which phase of the feature decomposition this is</li><li>The quality gate specification and results</li><li>Known limitations or deferred items</li><li>What the reviewer should focus on (architecture? logic? edge cases?)</li></ul><p>Tag AI-generated sections:</p><p>Not every line needs a tag, but if a section was generated by an AI and you did not deeply review the logic, say so in a comment or the PR description. Reviewers adjust their scrutiny accordingly.</p><p>Use the AI code review prompt as a pre-review step:</p><p>Run the CI review prompt on your own PR before submitting. Resolve blocking findings before asking a human to review. Human review time is expensive, use it for things AI cannot catch.</p><h3><strong>PART 11: ANTI-PATTERNS THAT KILL AI LOOP EFFECTIVENESS</strong></h3><h4><strong>11.1 The God Prompt</strong></h4><p>Asking one prompt to plan, implement, test, document, and review a feature. The output is never as good as running five separate loops. The model spreads its attention across all five concerns and does none of them as well as a dedicated pass would.</p><h4><strong>11.2 Skipping Exit Criteria</strong></h4><p>Starting a loop without defined exit criteria means you iterate until you feel done. You will feel done too early when you are under deadline pressure and too late when you are anxious. Neither produces consistent results. Define the criteria before the first iteration.</p><h4><strong>11.3 Trusting Without Verifying</strong></h4><p>Running AI-generated code without running it. Running AI-generated tests without reading them. Accepting AI-generated security findings without understanding what they mean. These feel like efficiency gains. They are how bugs get shipped.</p><h4><strong>11.4 Context Pollution</strong></h4><p>Dumping your entire codebase into every prompt. Keeping a conversation active across 50 messages until the model has lost track of constraints from 40 messages ago. Mixing context from different features in the same session. All of these degrade model performance. Smaller, cleaner context produces better output.</p><h4><strong>11.5 Scope Creep Acceptance</strong></h4><p>The model will frequently add features you did not request. Extra validation. Helper utilities. “Improved” versions of adjacent functions. Most of this is well-intentioned and wrong. Accepting out-of-scope changes makes your diff harder to review and introduces changes that have not been through the loop’s quality process.</p><h4><strong>11.6 Using AI to Avoid Understanding</strong></h4><p>The fastest path to an unmaintainable codebase: have the AI write it, accept the output, move on, and never understand what was generated. When something breaks six months later, nobody knows how the code works. Use AI to go faster, not to avoid understanding what you are building.</p><h4><strong>11.7 Loop Fatigue</strong></h4><p>Running too many loops on too many concerns simultaneously. If your process has ten loop types and you run all of them on every change, you will skip most of them under pressure. Pick the two or three that have the highest leverage for your project type and run them consistently. Add more loops when the process is stable.</p><h4><strong>11.8 Ignoring the Trend</strong></h4><p>Accepting “mostly passing” gates with the intention to fix the remaining issues later. They never get fixed. Quality gates pass or they do not. Partial passes are failures.</p><h3><strong>PART 12: REAL-WORLD WORKFLOW EXAMPLES</strong></h3><p><strong>Example 1: New Feature Development (Android, Fintech App)</strong></p><p>Team: 4 engineers, building a biometric authentication feature.</p><p>Tools: Claude Code (architect and QA roles), Cursor (developer role), GitHub Actions (CI integration).</p><p>Day 1: Architecture session (Architect Agent)</p><p>Single two-hour session. Architect agent produces:</p><ul><li>BiometricAuthRepository interface (domain layer)</li><li>BiometricAuthUseCase interface with error states</li><li>UI state model: Idle / Authenticating / Success(token) / Error(reason)</li><li>File structure across 8 files</li><li>Test strategy document</li></ul><p>Output committed as: docs/specs/biometric-auth-phase-1.md</p><p>Day 2: Domain implementation (Developer Agent → QA Agent → Fix Agent)</p><p>Developer agent implements BiometricAuthUseCase (no Android BiometricManager imports, pure domain logic).</p><p>QA agent writes 14 tests from the spec, tests zero Android classes.</p><p>First run: 11/14 pass. Three failures reveal missing error handling for CancellationException.</p><p>Fix agent addresses all three. Second run: 14/14 pass, 91% coverage.</p><p>Gate: passes. Committed.</p><p>Day 3: Data layer (Developer Agent → QA Agent)</p><p>BiometricAuthRepositoryImpl using Android BiometricPrompt.</p><p>QA agent uses mocked BiometricPrompt.</p><p>12/12 tests pass on first run. (Domain spec was precise enough that implementation was straightforward.)</p><p>Gate: passes. Committed.</p><p>Day 4: Presentation layer + CI integration</p><p>ViewModel and Compose screen generated. ViewModel tests: 8/8 pass.</p><p>Security agent reviews full feature: finds one Medium finding (token not cleared on Activity destroy). Remediated.</p><p>Documentation agent generates feature.md.</p><p>PR opened with all gate results in description. Human review: 45 minutes, focused on business logic only. Merged.</p><p>Total AI loop time: approximately 12 hours across 4 days.</p><p>Estimated traditional development time for same quality level: 3–4 days.</p><p>Test coverage: 88% across the feature.</p><p>Security findings at merge: zero.</p><p><strong>Example 2: Performance Optimization Loop (Node.js API)</strong></p><p>Context: a route handler was identified as slow under load (p95 &gt; 2s).</p><p>Iteration 1: Benchmark</p><p>Performance agent establishes baseline: p50 = 800ms, p95 = 2100ms.</p><p>Identifies top 3 bottlenecks: N+1 database query, missing index, synchronous file read inside request handler.</p><p>Iteration 2: Optimize: N+1 query</p><p>Fix applied. Benchmarks re-run: p50 = 320ms, p95 = 900ms.</p><p>All tests green. Committed.</p><p>Iteration 3: Optimize: database index</p><p>Index added via migration. Benchmarks: p50 = 180ms, p95 = 420ms.</p><p>All tests green. Committed.</p><p>Iteration 4: Optimize: async file read</p><p>File read moved outside request handler with caching. Benchmarks: p50 = 90ms, p95 = 210ms.</p><p>Performance target (p95 &lt; 500ms) met.</p><p>Loop terminates. Final result committed.</p><p>Total iterations: 3 optimization passes after baseline.</p><p>Improvement: p95 reduced by 90%.</p><p>Regressions introduced: zero (test suite enforced at each step).</p><p><strong>Example 3: Security Audit Loop (Cross-Platform Mobile App)</strong></p><p>Context: pre-release security audit on a payment feature.</p><p>Round 1: Security agent review</p><p>Findings: 2 Critical, 3 High, 4 Medium.</p><p>Critical: auth token stored in SharedPreferences (Android), auth token stored in UserDefaults (iOS).</p><p>High: payment amount not validated before API call, API key in BuildConfig accessible via reflection.</p><p>Round 2: Remediation</p><p>All Critical and High findings addressed.</p><p>Token storage: EncryptedSharedPreferences (Android), Keychain (iOS).</p><p>Amount validation: added to PaymentUseCase, tested.</p><p>API key: moved to secure backend proxy.</p><p>Round 3: Re-review</p><p>Re-ran security agent on all changed files.</p><p>Findings: 0 Critical, 0 High, 2 Medium (accepted with documentation).</p><p>Gate: passes.</p><p>Time from first review to cleared: 2 days.</p><p>Findings that would have shipped without the loop: 2 Critical.</p><h3><strong>CONCLUSION</strong></h3><p>The gap between engineers who get consistently excellent results from AI coding assistants and those who get inconsistent results is not about which tool they use or how good their prompts are in isolation. It is about whether they have a process.</p><p>Loops are the process. Define the phases. Define the exit criteria. Run the agents. Verify the outputs. Commit what passes. Iterate on what does not.</p><p>The specific tools like Claude Code, Cursor, GitHub Copilot, Windsurf, Gemini CLI, matter less than people think. What matters is the structure you impose on how you use them. A well-designed loop with a mid-tier model consistently outperforms an unstructured workflow with the best model available.</p><p><em>Start with one loop. The Planning → Implementation → Review loop in Part 2 is the highest-leverage starting point. Add quality gates. Commit the spec alongside the code. Run it for two weeks and compare the quality of your output to what you were producing before.</em></p><p>Then add a second loop. Then a third. Build the multi-agent pipeline when you are ready to invest the setup time. Integrate into CI when your loops are stable enough to run unattended.</p><p>The ceiling on what AI-assisted development can produce has not been reached. The floor, the minimum quality you should accept, is defined by whether you loop.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8639212f635b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Mobile Apps with AI Coding Assistants]]></title>
            <link>https://medium.com/@michael.avoyan/building-scalable-mobile-apps-with-cursor-ai-de335e9234f0?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/de335e9234f0</guid>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 15:51:54 GMT</pubDate>
            <atom:updated>2026-10-20T15:26:01.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYWcVT93QA6xXAvhxS-xcA.png" /></figure><p>AI Coding Assistants are changing how mobile software gets written. Tools like Cursor, Claude Code, GitHub Copilot, and Windsurf can plan features, generate context-aware code, refactor intelligently, produce tests on demand, and generate documentation you can publish straight to your team’s wiki. When you pair an AI Coding Assistant with disciplined engineering practices, you get developer speed without giving up quality.</p><p>This guide covers advanced best practices, reusable instruction files, prompt templates, architectural guidance, refactoring workflows, documentation generation, and <strong>ready-to-paste project templates</strong> for Android and iOS. The techniques here work regardless of which AI Coding Assistant you use.</p><h3>1) Plan Before You Code</h3><p>AI performs best when given precise plans rather than vague requests. Start every feature by asking the agent to outline a detailed plan that includes UI, domain logic, use cases, tests, and documentation, while clearly instructing the AI to:</p><ul><li>Respect Clean Architecture</li><li>Apply SOLID</li><li>Separate layers correctly</li><li>Generate test coverage</li><li>Include documentation</li></ul><p><strong>Prompt Example</strong></p><pre>Plan for Login Feature using Clean Architecture and SOLID principles:<br><br>Platforms:<br>- Android: Jetpack Compose UI, Hilt DI, Coroutines API<br>- iOS: SwiftUI screens, Combine networking<br><br>Architecture Requirements:<br>- Follow Clean Architecture (Presentation → Domain → Data)<br>- Domain layer must contain entities, repository interfaces, and use cases<br>- Domain layer must not depend on framework or UI code<br>- Data layer implements repository interfaces and handles networking/mapping<br>- Presentation layer (ViewModel + UI) depends only on domain abstractions<br><br>SOLID Requirements:<br>- Single Responsibility: Each class handles one responsibility<br>- Dependency Inversion: Depend on abstractions, not concrete implementations<br>- Interface Segregation: Keep interfaces focused and minimal<br>- Open/Closed: Extend behavior without modifying existing domain logic<br><br>Include:<br>- Domain interfaces and use case definitions<br>- Android-specific implementations (Compose + Hilt + Coroutines)<br>- iOS-specific implementations (SwiftUI + Combine)<br>- Unit tests for domain layer<br>- ViewModel tests<br>- Integration test outline<br>- Documentation files for Azure DevOps Wiki<br><br>Return:<br>- A structured Markdown checklist<br>- File paths for Android and iOS<br>- Clear dependency direction between layers<br>- Notes explaining where Clean Architecture boundaries are enforced</pre><h3>2) Engineer Context, Not Just Prompts</h3><p>AI Coding Assistants work better when they can reference your project’s conventions. Add context documents to your repository, architectural descriptions, interface contracts, domain rules, coding conventions, so the assistant can draw on them when generating or refactoring code.</p><h3>Architectural Summary</h3><h4>Android:</h4><ul><li><strong>Pattern:</strong> Strict MVVM</li><li><strong>UI Layer:</strong> Jetpack Compose (stateless Composables)</li><li><strong>State Management:</strong> StateFlow exposed from ViewModel</li><li><strong>ViewModel:</strong> Lifecycle-aware, injected via Hilt</li><li><strong>Dependency Injection:</strong> Hilt manages repository and use case bindings</li><li><strong>Concurrency:</strong> Kotlin Coroutines for async work</li><li><strong>Flow of Data:</strong><br> Composable → ViewModel → UseCase → Repository → Data Source<br> Repository → UseCase → ViewModel → StateFlow → UI</li></ul><p><strong>Key Principles</strong></p><ul><li>UI contains no business logic.</li><li>ViewModel exposes immutable state.</li><li>Domain logic is framework-independent.</li><li>Dependencies flow inward (Presentation → Domain).</li></ul><h4>iOS</h4><ul><li><strong>Pattern:</strong> Strict MVVM</li><li><strong>UI Layer:</strong> SwiftUI Views (stateless rendering)</li><li><strong>State Management:</strong> @Published properties inside ObservableObject ViewModels</li><li><strong>Reactive Layer:</strong> Combine (or async/await bridging to Combine where required)</li><li><strong>Concurrency:</strong> async/await for networking</li><li><strong>Flow of Data:</strong><br> SwiftUI View → ViewModel → UseCase → Repository → Network<br> Repository → ViewModel → @Published → View</li></ul><p><strong>Key Principles</strong></p><ul><li>Views only render state.</li><li>ViewModel handles orchestration and transforms domain results.</li><li>Business logic lives in domain layer abstractions.</li><li>Repository implementations are injected and conform to protocols.</li></ul><h4>Cross-Platform Architectural Alignment</h4><p><strong>Both platforms share:</strong></p><ul><li>MVVM separation of concerns</li><li>Reactive UI driven by observable state</li><li>Dependency injection</li><li>Async data flow</li><li>Testable domain logic independent of UI</li><li>Clear unidirectional data flow</li></ul><p>This shared structure makes it easier to design features consistently across Android and iOS while keeping platform-specific UI layers thin and maintainable.</p><p><strong>Prompt Example</strong></p><pre># Architectural Context Summary<br><br>## Android Architecture<br><br>Pattern: MVVM  <br>UI Layer: Jetpack Compose (stateless Composables)  <br>State Management: `StateFlow` exposed from ViewModel  <br>Dependency Injection: Hilt  <br>Concurrency: Kotlin Coroutines  <br><br>### Data Flow<br><br>Composable → ViewModel → UseCase → Repository → Data Source  <br>Repository → UseCase → ViewModel → StateFlow → UI  <br><br>### Responsibilities<br><br>- Composable<br>  - Renders state only<br>  - No business logic<br>  - Delegates events to ViewModel<br><br>- ViewModel<br>  - Orchestrates use cases<br>  - Exposes immutable `StateFlow`<br>  - Handles lifecycle-aware state<br><br>- UseCase<br>  - Encapsulates single business action<br>  - Pure Kotlin logic<br>  - No Android framework dependency<br><br>- Repository Interface<br>  - Defined in domain layer<br>  - Abstracts data source<br><br>- Repository Implementation<br>  - Lives in data layer<br>  - Handles networking, mapping, caching<br><br>### Architectural Principles<br><br>- Unidirectional data flow<br>- Separation of concerns<br>- Dependency inversion (Presentation depends on Domain abstractions)<br>- Domain layer independent of framework code<br><br>---<br><br>## iOS Architecture<br><br>Pattern: Strict MVVM  <br>UI Layer: SwiftUI (stateless Views)  <br>State Management: `@Published` inside `ObservableObject`  <br>Reactive Layer: Combine  <br>Concurrency: async/await  <br><br>### Data Flow<br><br>SwiftUI View → ViewModel → UseCase → Repository → Network  <br>Repository → ViewModel → `@Published` → View  <br><br>### Responsibilities<br><br>- SwiftUI View<br>  - Declarative UI rendering<br>  - No business logic<br>  - Binds to ViewModel state<br><br>- ViewModel<br>  - ObservableObject<br>  - Transforms domain results into UI state<br>  - Coordinates async operations<br><br>- UseCase<br>  - Pure business logic<br>  - No UI framework dependency<br><br>- Repository Protocol<br>  - Defined in domain layer<br>  - Implemented in data layer<br><br>### Architectural Principles<br><br>- Unidirectional data flow<br>- UI driven entirely by state<br>- Dependency inversion via protocols<br>- Domain isolated from framework concerns<br><br>---<br><br>## Cross-Platform Alignment<br><br>Both platforms share:<br><br>- MVVM separation<br>- Reactive state-driven UI<br>- Dependency injection<br>- Async execution model<br>- Domain logic isolated from UI<br>- Clear inward dependency direction</pre><h3>3) Rule Files: Persistent Engineering Guardrails</h3><p>Every major AI Coding Assistant supports some form of persistent instruction file that applies rules across all sessions. These replace repeated prompt instructions and give the assistant a stable view of your engineering conventions.</p><p>The file format and location varies by AI Coding Assistant:</p><p>Cursor: .cursor/rules/*.mdc</p><p>Claude Code: CLAUDE.md (project root) or .claude/ directory</p><p>GitHub Copilot: .github/copilot-instructions.md</p><p>Windsurf: .windsurfrules</p><p>Regardless of format, the content is what matters. Below are the rules you should encode. Adapt them to whatever syntax your AI Coding Assistant expects.</p><h4>Android Rule Files (Compose + Hilt + Coroutines)</h4><p><strong>android-core instructions</strong></p><pre>---<br>description: Android Core Architecture Rules (Compose + Hilt + Coroutines)<br>globs:<br>  - &quot;**/*.kt&quot;<br>alwaysApply: true<br>---<br><br># Android Architecture Rules<br><br>## 1. Clean Architecture Enforcement<br><br>RULE: Follow Clean Architecture with clear layer separation:<br>  - Presentation (UI + ViewModel)<br>  - Domain (Entities, UseCases, Repository Interfaces)<br>  - Data (Repository Implementations, DTOs, Mappers)<br><br>RULE: Domain layer must not depend on Android framework classes.<br>RULE: Dependencies must point inward (Presentation → Domain → Data).<br>RULE: Repository interfaces live in the domain layer.<br><br>---<br><br>## 2. MVVM Conventions<br><br>RULE: Use MVVM pattern.<br>RULE: Composables must be stateless and render only state.<br>RULE: Business logic must not exist inside Composables.<br>RULE: ViewModels orchestrate use cases and expose immutable state.<br><br>---<br><br>## 3. State Management<br><br>RULE: ViewModels expose immutable StateFlow.<br>RULE: Internal mutable state must remain private.<br>RULE: UI observes StateFlow via collectAsState().<br>RULE: Model UI state using sealed classes or data classes.<br><br>Example UI State Pattern:<br>  - Loading<br>  - Success(data)<br>  - Error(message)<br><br>---<br><br>## 4. Dependency Injection (Hilt)<br><br>RULE: Use Hilt for dependency injection.<br>RULE: ViewModels must use @HiltViewModel.<br>RULE: Inject UseCases into ViewModels.<br>RULE: Inject Repository implementations via constructor injection.<br>RULE: Avoid field injection.<br><br>---<br><br>## 5. Coroutines &amp; Async Handling<br><br>RULE: All asynchronous work must use Kotlin Coroutines.<br>RULE: Network calls must run in appropriate dispatcher (IO).<br>RULE: ViewModels launch coroutines using viewModelScope.<br>RULE: Handle exceptions explicitly using try/catch or Result wrapper.<br>RULE: Never block the main thread.<br><br>---<br><br>## 6. SOLID Principles<br><br>RULE: Single Responsibility — Each class must have one clear responsibility.<br>RULE: Dependency Inversion — Depend on abstractions, not implementations.<br>RULE: Interface Segregation — Keep interfaces small and focused.<br>RULE: Open/Closed — Extend behavior without modifying domain logic.<br>RULE: Avoid large God classes.<br><br>---<br><br>## 7. Error Handling &amp; Result Modeling<br><br>RULE: Domain layer must return Result&lt;T&gt; or sealed result types.<br>RULE: Do not expose raw exceptions to UI.<br>RULE: Map technical errors into UI-friendly error states.<br><br>---<br><br>## 8. Testing Requirements<br><br>RULE: All UseCases must have unit tests.<br>RULE: ViewModels must have unit tests covering:<br>  - success flow<br>  - failure flow<br>  - edge cases<br>RULE: Use coroutine test utilities for suspend functions.<br>RULE: Mock repositories, never mock use cases.<br><br>---<br><br>## 9. Code Quality Standards<br><br>RULE: Prefer constructor injection.<br>RULE: Avoid static singletons unless justified.<br>RULE: Avoid tightly coupling UI and data layers.<br>RULE: Keep functions small and expressive.<br>RULE: Use meaningful naming aligned with domain language.</pre><h4><strong>android-compose instructions</strong></h4><pre>---<br>description: Jetpack Compose UI Rules (MVVM + StateFlow)<br>globs:<br>  - &quot;app/src/**/*.kt&quot;<br>alwaysApply: true<br>---<br><br># Jetpack Compose UI Rules<br><br>## 1. Stateless UI Enforcement<br><br>RULE: Composables must be stateless whenever possible.<br>RULE: Business logic must NOT exist inside Composables.<br>RULE: Composables must receive state and event callbacks as parameters.<br>RULE: Do not perform data fetching directly in Composables.<br><br>Correct Pattern:<br>Composable(<br>  state = viewModel.uiState,<br>  onEvent = { viewModel.handleEvent(it) }<br>)<br><br>---<br><br>## 2. State Management<br><br>RULE: UI must observe ViewModel StateFlow using collectAsState().<br>RULE: UI state must be represented using sealed classes or immutable data classes.<br>RULE: Avoid mutable state in UI unless strictly local (e.g., remember for UI-only behavior).<br>RULE: Never expose MutableStateFlow outside ViewModel.<br><br>Example State Pattern:<br>sealed class LoginUiState {<br>  object Loading<br>  data class Success(val user: User)<br>  data class Error(val message: String)<br>}<br><br>---<br><br>## 3. Unidirectional Data Flow<br><br>RULE: Data flow must be unidirectional:<br>  UI → ViewModel → UseCase → Repository → Data<br>RULE: UI reacts to state changes, it does not mutate state directly.<br>RULE: Events are passed upward via lambdas.<br><br>---<br><br>## 4. Side-Effect Management<br><br>RULE: Use LaunchedEffect for one-off side effects.<br>RULE: Use rememberUpdatedState when referencing lambdas in effects.<br>RULE: Avoid launching coroutines directly in Composables unless scoped via LaunchedEffect.<br>RULE: Navigation events must be triggered from ViewModel state, not directly in UI logic.<br><br>---<br><br>## 5. Composition Best Practices<br><br>RULE: Keep Composables small and focused.<br>RULE: Extract reusable UI components.<br>RULE: Avoid deeply nested composables.<br>RULE: Separate screen-level composables from reusable components.<br><br>Structure Example:<br>- LoginScreen.kt (screen-level)<br>- LoginContent.kt (UI rendering)<br>- LoginComponents.kt (reusable UI parts)<br><br>---<br><br>## 6. Performance Guidelines<br><br>RULE: Use remember and derivedStateOf appropriately.<br>RULE: Avoid unnecessary recompositions.<br>RULE: Keys must be stable in LazyColumn/LazyRow.<br>RULE: Do not perform heavy computations inside Composables.<br><br>---<br><br>## 7. Theming &amp; Styling<br><br>RULE: Use MaterialTheme for colors, typography, and shapes.<br>RULE: Avoid hardcoded colors and dimensions.<br>RULE: Support dark mode automatically.<br>RULE: Ensure accessibility (contentDescription for icons).<br><br>---<br><br>## 8. Navigation<br><br>RULE: Use Compose Navigation for screen navigation.<br>RULE: Do not navigate directly from UI based on raw state mutation.<br>RULE: Navigation events should be emitted from ViewModel and consumed once.<br><br>---<br><br>## 9. Preview Requirements<br><br>RULE: Provide @Preview functions for screen-level composables.<br>RULE: Use mock state for previews.<br>RULE: Previews must not depend on ViewModel instantiation.<br><br>---<br><br>## 10. Testing Alignment<br><br>RULE: UI must be testable using Compose UI Test.<br>RULE: Use testTags for critical components.<br>RULE: Avoid tightly coupling UI to platform-specific behavior.</pre><h4><strong>android-tests instructions</strong></h4><pre>---<br>description: Android Testing Rules (Unit + ViewModel + Compose + Coroutines)<br>globs:<br>  - &quot;**/*Test.kt&quot;<br>  - &quot;**/*Tests.kt&quot;<br>alwaysApply: true<br>---<br><br># Android Testing Rules<br><br>## 1. Test-First Enforcement<br><br>RULE: Generate tests before implementation when creating new features.<br>RULE: Every UseCase must have dedicated unit tests.<br>RULE: Every ViewModel must have unit tests covering:<br>  - success flow<br>  - failure flow<br>  - loading state<br>  - edge cases<br><br>---<br><br>## 2. Domain Layer Testing<br><br>RULE: Domain tests must not depend on Android framework classes.<br>RULE: Use fake or mock repository implementations.<br>RULE: Validate business logic only.<br>RULE: Test all branches of Result or sealed response types.<br><br>Example:<br>- valid credentials<br>- invalid credentials<br>- exception propagation<br>- mapping correctness<br><br>---<br><br>## 3. ViewModel Testing<br><br>RULE: Use coroutine test utilities (runTest).<br>RULE: Replace Dispatchers.Main with TestDispatcher.<br>RULE: Assert StateFlow emissions in correct order.<br>RULE: Do not test UI rendering in ViewModel tests.<br><br>Required Assertions:<br>- Initial state<br>- Loading state<br>- Success state<br>- Error state<br><br>---<br><br>## 4. Coroutine &amp; Flow Testing<br><br>RULE: Use kotlinx-coroutines-test utilities.<br>RULE: Advance virtual time when needed.<br>RULE: Avoid real delays in tests.<br>RULE: Collect flows deterministically.<br><br>Example Tools:<br>- runTest<br>- StandardTestDispatcher<br>- UnconfinedTestDispatcher<br><br>---<br><br>## 5. Repository Testing<br><br>RULE: Repository implementations must be tested with:<br>  - success network response<br>  - API error response<br>  - mapping correctness<br>RULE: Mock network layer.<br>RULE: Validate DTO-to-domain mapping.<br><br>---<br><br>## 6. Compose UI Testing<br><br>RULE: Use Compose UI Test framework.<br>RULE: Add testTags to critical UI components.<br>RULE: Verify:<br>  - loading indicator visibility<br>  - error messages displayed<br>  - button enabled/disabled states<br>RULE: Avoid testing implementation details.<br><br>---<br><br>## 7. Integration Testing<br><br>RULE: Integration tests must validate:<br>  - Full login flow<br>  - Interaction between ViewModel and Repository<br>  - Navigation triggers (if applicable)<br><br>RULE: Use Hilt testing utilities for dependency replacement.<br>RULE: Replace real network with fake implementation.<br><br>---<br><br>## 8. Mocking Rules<br><br>RULE: Mock repositories, not use cases.<br>RULE: Prefer fakes for domain tests.<br>RULE: Avoid mocking value objects or simple data classes.<br>RULE: Do not mock framework classes unless required.<br><br>---<br><br>## 9. Test Naming &amp; Structure<br><br>RULE: Use descriptive test names:<br>  givenCondition_whenAction_thenExpectedResult<br><br>Example:<br>  givenInvalidEmail_whenLogin_thenEmitErrorState<br><br>RULE: Keep Arrange-Act-Assert structure clear.<br>RULE: One logical assertion per test scenario.<br><br>---<br><br>## 10. Coverage Expectations<br><br>RULE: All public UseCases must be covered.<br>RULE: All ViewModels must cover success and error paths.<br>RULE: Edge cases must be tested explicitly.<br>RULE: Avoid superficial tests that only verify method calls.</pre><h4>iOS Rule Files (SwiftUI + Combine)</h4><h4><strong>ios-core instructions</strong></h4><pre>---<br>description: iOS Core Architecture Rules (SwiftUI + Combine + Clean Architecture)<br>globs:<br>  - &quot;**/*.swift&quot;<br>alwaysApply: true<br>---<br><br># iOS Architecture Rules<br><br>## 1. Clean Architecture Enforcement<br><br>RULE: Follow Clean Architecture with strict separation:<br>  - Presentation (Views + ViewModels)<br>  - Domain (Entities, UseCases, Repository Protocols)<br>  - Data (Repository Implementations, Network, Mappers)<br><br>RULE: Domain layer must not import SwiftUI, Combine, or networking frameworks.<br>RULE: Dependencies must point inward (Presentation → Domain → Data).<br>RULE: Repository protocols must be defined in the Domain layer.<br><br>---<br><br>## 2. MVVM Pattern (Strict)<br><br>RULE: SwiftUI Views must be declarative and stateless.<br>RULE: Views must not contain business logic.<br>RULE: ViewModels must handle orchestration and state transformation.<br>RULE: Views must bind to ViewModel via @StateObject or @ObservedObject.<br><br>Correct Flow:<br>View → ViewModel → UseCase → Repository → Network<br>Repository → ViewModel → @Published → View<br><br>---<br><br>## 3. State Management<br><br>RULE: ViewModels must conform to ObservableObject.<br>RULE: UI state must be exposed via @Published properties.<br>RULE: Avoid exposing mutable internal state publicly.<br>RULE: Model UI state using enums or immutable structs.<br><br>Example State Pattern:<br>enum LoginState {<br>  case idle<br>  case loading<br>  case success(User)<br>  case error(String)<br>}<br><br>---<br><br>## 4. Combine &amp; Async Handling<br><br>RULE: Use async/await for networking where possible.<br>RULE: Combine publishers must be transformed inside ViewModel.<br>RULE: Avoid heavy Combine chains inside Views.<br>RULE: Errors must be mapped to domain or UI-friendly states.<br><br>RULE: Never block the main thread.<br>RULE: Mark UI-updating methods with @MainActor.<br><br>---<br><br>## 5. Dependency Injection<br><br>RULE: Use constructor injection for dependencies.<br>RULE: ViewModels must receive UseCases via initializer.<br>RULE: Repository implementations must conform to domain protocols.<br>RULE: Avoid global singletons unless explicitly required.<br><br>---<br><br>## 6. SOLID Principles<br><br>RULE: Single Responsibility — Each type must have one clear responsibility.<br>RULE: Dependency Inversion — Depend on protocols, not concrete types.<br>RULE: Interface Segregation — Keep protocols focused and minimal.<br>RULE: Open/Closed — Extend behavior without modifying domain logic.<br>RULE: Avoid large ViewModels that mix responsibilities.<br><br>---<br><br>## 7. Mapping &amp; Data Handling<br><br>RULE: DTOs must not leak into Domain layer.<br>RULE: Use dedicated mapper types for DTO → Entity conversion.<br>RULE: Domain entities must remain framework-independent.<br><br>---<br><br>## 8. Error Handling<br><br>RULE: Do not expose raw networking errors to UI.<br>RULE: Map technical errors to domain-level errors.<br>RULE: UI must display user-friendly error messages.<br><br>---<br><br>## 9. Code Structure Expectations<br><br>Recommended folder structure:<br><br>Sources/<br>  Domain/<br>    Entities/<br>    Repositories/<br>    UseCases/<br>  Data/<br>    Network/<br>    Repositories/<br>    Mappers/<br>  Presentation/<br>    Views/<br>    ViewModels/<br><br>---<br><br>## 10. Documentation Alignment<br><br>RULE: All new features must include Markdown documentation:<br>  - Architecture overview<br>  - Data flow explanation<br>  - Public API contracts<br>Documentation must be suitable for Azure DevOps Wiki publishing.</pre><h4><strong>ios-tests instructions</strong></h4><pre>---<br>description: iOS Testing Rules (XCTest + Combine + Async/Await)<br>globs:<br>  - &quot;**/*Tests.swift&quot;<br>  - &quot;Tests/**/*.swift&quot;<br>alwaysApply: true<br>---<br><br># iOS Testing Rules<br><br>## 1. Test-First Enforcement<br><br>RULE: Generate unit tests before implementing new features.<br>RULE: Every UseCase must have dedicated unit tests.<br>RULE: Every ViewModel must have tests covering:<br>  - initial state<br>  - loading state<br>  - success state<br>  - error state<br>  - edge cases<br><br>---<br><br>## 2. Domain Layer Testing<br><br>RULE: Domain tests must not import SwiftUI or Combine.<br>RULE: Domain tests must not depend on networking frameworks.<br>RULE: Use fake or mock repository implementations.<br>RULE: Validate pure business logic only.<br><br>Required Coverage:<br>- valid credentials<br>- invalid credentials<br>- failure handling<br>- mapping correctness<br><br>---<br><br>## 3. ViewModel Testing<br><br>RULE: Test ViewModels independently from Views.<br>RULE: Validate all @Published state transitions.<br>RULE: Ensure state updates occur on the main thread (@MainActor).<br>RULE: Do not test SwiftUI rendering in ViewModel tests.<br><br>Pattern:<br>Given → When → Then<br><br>Example:<br>givenInvalidEmail_whenLogin_thenStateIsError<br><br>---<br><br>## 4. Async/Await Testing<br><br>RULE: Use XCTest async/await support.<br>RULE: Await async functions explicitly.<br>RULE: Avoid real delays in tests.<br>RULE: Use controlled test doubles instead of real network calls.<br><br>Example:<br>func testLoginSuccess() async throws {<br>    let result = await useCase.execute(...)<br>    XCTAssertEqual(result, expected)<br>}<br><br>---<br><br>## 5. Combine Testing<br><br>RULE: Use XCTestExpectation to test Combine publishers.<br>RULE: Collect publisher outputs deterministically.<br>RULE: Ensure subscriptions are cancelled after assertions.<br>RULE: Avoid complex publisher chains in tests.<br><br>Example Pattern:<br>- Create expectation<br>- Subscribe<br>- Fulfill expectation<br>- Wait and assert<br><br>---<br><br>## 6. Repository Implementation Testing<br><br>RULE: Mock network layer.<br>RULE: Validate DTO to domain mapping.<br>RULE: Test:<br>  - successful response<br>  - server error<br>  - decoding failure<br><br>RULE: Repository tests must not rely on real network calls.<br><br>---<br><br>## 7. Integration Testing<br><br>RULE: Integration tests must validate:<br>  - ViewModel + Repository interaction<br>  - Async flow correctness<br>  - Error propagation to UI state<br><br>RULE: Replace dependencies using dependency injection.<br>RULE: Avoid real backend calls.<br><br>---<br><br>## 8. Mocking &amp; Test Doubles<br><br>RULE: Prefer fakes for domain tests.<br>RULE: Use protocol-based mocks.<br>RULE: Do not mock value types unnecessarily.<br>RULE: Avoid mocking simple data structures.<br><br>---<br><br>## 9. Naming &amp; Structure<br><br>RULE: Use descriptive test names:<br>  givenCondition_whenAction_thenExpectedResult<br><br>Example:<br>  givenNetworkFailure_whenLogin_thenEmitErrorState<br><br>RULE: Follow Arrange-Act-Assert pattern.<br>RULE: One behavior per test.<br><br>---<br><br>## 10. Coverage Expectations<br><br>RULE: All public UseCases must be covered.<br>RULE: All ViewModels must cover success and failure branches.<br>RULE: Async flows must be validated.<br>RULE: Tests must verify behavior, not implementation details.</pre><h3>4) Test-First Workflows</h3><p><strong>Generate tests before implementation.</strong> This is not a style preference, it has structural consequences. Writing tests first forces you to define behavior contracts before you have any implementation to bias them. It also makes the AI output more useful: when you ask the assistant to “implement the login use case so that these tests pass,” you get far better code than when you ask it to implement from scratch.</p><p><strong>A test-first approach ensures:</strong></p><ul><li>Business logic is validated independently of UI</li><li>Edge cases are defined explicitly</li><li>State transitions are predictable</li><li>Refactoring is safe</li><li>Clean Architecture boundaries remain intact</li></ul><p>Instead of asking the AI to “implement login,” you first ask it to define the behavior contract through tests.</p><p><strong>Prompt Example</strong></p><pre>Test-First Workflow for Login Feature<br><br>Step 1: Generate tests only (do NOT generate implementation yet).<br><br>Architecture Requirements:<br>- Follow Clean Architecture.<br>- Domain layer must be framework-independent.<br>- ViewModel must expose immutable UI state.<br>- Use SOLID principles.<br><br>Generate:<br><br>1. Domain Layer Tests<br>   - LoginUseCaseTest<br>   - Cover:<br>     - valid credentials<br>     - invalid credentials<br>     - repository failure<br>     - unexpected exception<br>   - Use fake repository implementation.<br><br>2. ViewModel Tests<br>   - LoginViewModelTest<br>   - Verify state transitions:<br>     - initial state<br>     - loading state<br>     - success state<br>     - error state<br>   - Use coroutine test utilities (Android) or async/await XCTest (iOS).<br><br>3. Integration Test Outline<br>   - Describe how to test full login flow using mocked repository.<br><br>Constraints:<br>- Do not generate implementation code.<br>- Keep domain tests free from framework dependencies.<br>- Use descriptive test naming:<br>  givenCondition_whenAction_thenExpectedResult<br><br>Return:<br>- Markdown checklist<br>- File paths<br>- Complete test code scaffolding</pre><h3>5) Clean Architecture + SOLID Principles</h3><p>Strong architecture and design principles make large projects maintainable, extensible, and testable. When working with AI, architecture must be explicit. If you do not constrain structure, the model will default to convenience instead of long-term maintainability.</p><p><strong>Clean Architecture enforces separation of concerns:</strong></p><ul><li><strong>Presentation</strong> (UI + ViewModel)</li><li><strong>Domain</strong> (Entities, UseCases, Repository Interfaces)</li><li><strong>Data</strong> (Repository Implementations, DTOs, Mappers)</li></ul><p>Dependencies must always point inward:</p><p>Presentation → Domain → Data</p><p>The Domain layer must remain framework-independent and contain pure business logic.</p><p><strong>SOLID principles reinforce this structure:</strong></p><ul><li><strong>Single Responsibility</strong>: Each class has one clear responsibility.</li><li><strong>Open/Closed</strong>: Extend behavior without modifying domain logic.</li><li><strong>Liskov Substitution</strong>: Implementations must respect interface contracts.</li><li><strong>Interface Segregation</strong>: Keep interfaces minimal and focused.</li><li><strong>Dependency Inversion</strong>: Depend on abstractions, not concrete implementations.</li></ul><p>When prompting AI Coding Assistant, you must explicitly demand architectural discipline.</p><p><strong>Prompt Example</strong></p><pre>Implement Login Feature using Clean Architecture and SOLID.<br><br>Architecture Constraints:<br>- Follow Clean Architecture:<br>  Presentation → Domain → Data<br>- Domain layer must not depend on Android, SwiftUI, Combine, or networking frameworks.<br>- Repository interfaces must live in the Domain layer.<br>- Data layer must implement Domain interfaces.<br>- Presentation layer must depend only on Domain abstractions.<br><br>SOLID Requirements:<br>- Single Responsibility per class.<br>- Use constructor injection.<br>- Depend on protocols/interfaces only.<br>- Avoid large, multi-purpose ViewModels.<br>- Use small focused interfaces.<br><br>Generate:<br><br>1. Domain Layer<br>   - User entity<br>   - AuthRepository interface/protocol<br>   - LoginUseCase<br><br>2. Data Layer<br>   - DTO models<br>   - Repository implementation<br>   - Mapper from DTO → Entity<br><br>3. Presentation Layer<br>   - LoginViewModel<br>   - UI state model (sealed class / enum)<br>   - Compose screen (Android)<br>   - SwiftUI View (iOS)<br><br>4. Tests<br>   - Unit tests for LoginUseCase<br>   - ViewModel state transition tests<br><br>Return:<br>- Markdown checklist<br>- File paths<br>- Clear dependency diagram<br>- Short explanation of how Clean Architecture boundaries are enforced</pre><h3>6) Systematic Refactoring</h3><p>Good refactoring keeps code clean, modular, and evolution-ready.<br> AI-generated code is fast, but speed without structure leads to technical debt. Refactoring ensures long-term maintainability without changing observable behavior.</p><p><strong>Refactoring should always:</strong></p><ul><li>Preserve behavior (tests must stay green)</li><li>Improve clarity and cohesion</li><li>Reduce duplication</li><li>Enforce Clean Architecture boundaries</li><li>Strengthen SOLID compliance</li></ul><p>Refactoring is not rewriting. It is structured improvement backed by tests.</p><p><strong>Before refactoring, ensure:</strong></p><ul><li>Unit tests exist</li><li>Behavior is well defined</li><li>Edge cases are covered</li></ul><p><strong>Common Refactoring Goals in Mobile Projects:</strong></p><ul><li>Extract business logic from UI</li><li>Break large ViewModels into smaller collaborators</li><li>Replace conditionals with polymorphism</li><li>Introduce interfaces for dependency inversion</li><li>Extract reusable mappers</li><li>Improve naming for clarity</li><li>Reduce coroutine misuse inside UI</li><li>Separate side effects from state updates</li></ul><p><strong>Refactor Prompt Example (Architecture-Enforced)</strong></p><pre>Refactor the Login feature implementation.<br><br>Goals:<br>- Preserve existing behavior (all tests must pass).<br>- Improve adherence to Clean Architecture.<br>- Enforce SOLID principles.<br>- Reduce duplication and improve readability.<br><br>Refactoring Requirements:<br><br>1. Extract Responsibilities<br>   - Move validation logic out of ViewModel into a dedicated Validator.<br>   - Ensure ViewModel only orchestrates use cases and state.<br><br>2. Strengthen Dependency Inversion<br>   - Replace any concrete repository usage with domain interface.<br>   - Ensure constructor injection is used everywhere.<br><br>3. Improve State Modeling<br>   - Replace boolean flags with sealed classes / enums.<br>   - Ensure UI state is immutable.<br><br>4. Reduce Complexity<br>   - Split large methods into small, focused functions.<br>   - Eliminate nested conditionals where possible.<br><br>5. Improve Error Handling<br>   - Map technical errors into domain or UI-friendly error types.<br>   - Avoid exposing raw exceptions to presentation layer.<br><br>Return:<br>- List of refactor steps performed<br>- Updated file paths<br>- Before/After summary<br>- Confirmation that architectural boundaries remain intact<br>- Notes on which SOLID principles were improved</pre><h3>7) Documentation Generation + Azure DevOps Wiki</h3><p>One of AI’s most valuable capabilities is generating <strong>human-readable documentation that accurately reflects your code and architecture</strong>.</p><p>AI Coding Assistant can generate documentation from:</p><ul><li>Actual source files</li><li>Architectural rules and context files</li><li>Feature plans</li><li>Test coverage</li></ul><p>This eliminates outdated wiki pages and keeps documentation aligned with implementation.</p><p><strong>Azure DevOps Wiki:</strong></p><ul><li>Uses <strong>Markdown</strong></li><li>Can be backed by a <strong>Git repository</strong></li><li>Supports diagrams (including Mermaid)</li><li>Updates automatically when Markdown files are committed</li></ul><p>This makes it ideal for AI-generated documentation workflows.</p><p>You can generate Markdown locally under a /docs directory and either:</p><ul><li>Publish the repo as a Wiki</li><li>Or connect a dedicated Wiki repo and push updates</li></ul><p>Documentation becomes versioned, reviewable, and traceable just like code.</p><p><strong>This Should Be Generated Automatically:</strong></p><p><strong>For each feature, generate:</strong></p><ul><li>Architecture overview</li><li>Layer boundaries explanation</li><li>Data flow diagrams</li><li>API contracts</li><li>Test coverage summary</li><li>Dependency mapping</li><li>State transition diagrams</li></ul><p>Documentation should describe <strong>why</strong> the structure exists, not just what the code does.</p><p><strong>Documentation Prompt Example (Architecture-Aware)</strong></p><pre>Generate Markdown documentation for the Login feature.<br><br>Requirements:<br><br>1. Architecture Overview<br>   - Explain Clean Architecture layers:<br>     Presentation → Domain → Data<br>   - Describe dependency direction.<br>   - Confirm Domain layer has no framework dependencies.<br><br>2. Data Flow<br>   - Show login request flow from UI to API.<br>   - Show state propagation back to UI.<br>   - Include a Mermaid sequence diagram.<br><br>3. Domain Layer<br>   - List entities and use cases.<br>   - Describe business rules.<br>   - Explain repository interface responsibilities.<br><br>4. Data Layer<br>   - Describe API interaction.<br>   - Document DTO → Entity mapping.<br>   - Explain error transformation.<br><br>5. Presentation Layer<br>   - Describe ViewModel responsibilities.<br>   - Document UI state model.<br>   - Explain state transitions (loading → success → error).<br><br>6. Testing<br>   - List unit tests for UseCase.<br>   - List ViewModel state transition tests.<br>   - Describe integration test strategy.<br><br>7. File Structure<br>   - Provide directory tree.<br>   - Show clear separation of layers.<br><br>Output:<br>- Multiple Markdown files<br>- Organized under:<br><br>docs/<br>  Architecture/LoginFeature.md<br>  API/LoginContract.md<br>  Testing/LoginTests.md<br>  Diagrams/LoginFlow.mmd<br><br>Ensure formatting is compatible with Azure DevOps Wiki.<br>Use proper Markdown headings and fenced code blocks.</pre><h3>8) Secure Coding Prompts</h3><p>AI can produce functional code quickly, but <strong>security does not emerge automatically</strong>.<br><strong> If you do not explicitly require secure practices, the model may:</strong></p><ul><li>Skip input validation</li><li>Expose raw errors</li><li>Leak sensitive information</li><li>Mishandle authentication tokens</li><li>Ignore timeout and retry strategies</li></ul><p>Security must be stated as a first-class requirement in your prompts.</p><p><strong>When working with mobile applications, you must enforce:</strong></p><ul><li>Input validation</li><li>Secure networking</li><li>Safe error handling</li><li>Proper token storage</li><li>No hardcoded secrets</li><li>Defensive programming</li></ul><p>Security belongs in architecture, not as an afterthought.</p><p><strong>Enforce Explicitly:</strong></p><p><strong>For Android (Compose + Hilt + Coroutines):</strong></p><ul><li>Validate inputs in ViewModel or domain layer</li><li>Use HTTPS only</li><li>Handle network timeouts explicitly</li><li>Avoid logging sensitive information</li><li>Store tokens securely (EncryptedSharedPreferences or secure storage abstraction)</li><li>Map technical errors into domain-safe errors</li></ul><p><strong>For iOS (SwiftUI + Combine + async/await):</strong></p><ul><li>Validate inputs in ViewModel or domain layer</li><li>Use HTTPS only</li><li>Handle network timeouts explicitly</li><li>Avoid logging sensitive information</li><li>Store tokens securely (Keychain abstraction)</li><li>Map technical errors into domain-safe errors</li></ul><p><strong>Secure Coding Prompt Example (Architecture-Enforced)</strong></p><pre>Implement Login Feature with explicit security requirements.<br><br>Security Constraints:<br><br>1. Input Validation<br>   - Validate email format.<br>   - Validate password length.<br>   - Reject invalid input before calling UseCase.<br><br>2. Networking Security<br>   - Use HTTPS endpoints only.<br>   - Implement request timeout handling.<br>   - Handle network failures explicitly.<br><br>3. Error Handling<br>   - Do not expose raw exceptions to UI.<br>   - Map technical errors to domain-level error types.<br>   - UI must display user-friendly messages only.<br><br>4. Sensitive Data Handling<br>   - Do not log passwords or tokens.<br>   - Abstract token storage behind a SecureStorage interface.<br>   - Do not hardcode secrets in source code.<br><br>5. Clean Architecture Alignment<br>   - Security logic must not violate layer boundaries.<br>   - Domain remains framework-independent.<br>   - Secure storage implemented in Data layer behind interface.<br><br>Return:<br>- Updated architecture diagram<br>- Secure repository implementation<br>- Token storage abstraction<br>- Security-focused unit tests</pre><h3>9) Structured Prompt Engineering</h3><p>When working with AI Coding Assistant in an agentic workflow, the quality of output depends directly on how well you structure your prompt.<br>Unstructured prompts lead to vague, inconsistent, or tightly coupled code. Structured prompts guide the model to reason step by step, respect architecture, and enforce constraints.</p><p>Instead of: <em>“Implement login feature”</em></p><p>You should design prompts that help the agent think like a senior engineer.</p><h4>Core Prompt Structure</h4><p><strong>Use</strong> a consistent structure that forces reasoning:</p><pre>Role:<br>Context:<br>Goal:<br>Architecture Constraints:<br>Security Constraints:<br>Testing Requirements:<br>Refactoring Expectations:<br>Acceptance Criteria:<br>Output Format:</pre><p><strong>Structured prompts:</strong></p><ul><li>Reduce hallucinated assumptions</li><li>Enforce Clean Architecture boundaries</li><li>Make SOLID requirements explicit</li><li>Encourage test-first workflows</li><li>Make outputs predictable and reusable</li><li>Improve multi-step agent planning</li></ul><p>They also make it easier to review the AI’s reasoning before it writes code.</p><p><strong>Fully Structured Login Prompt Example</strong></p><pre>Role:<br>You are a senior mobile architect.<br><br>Context:<br>- Android uses MVVM with Compose, Hilt, and StateFlow.<br>- iOS uses SwiftUI with strict MVVM and Combine.<br>- Project follows Clean Architecture.<br><br>Goal:<br>Implement a secure Login feature.<br><br>Architecture Constraints:<br>- Follow Clean Architecture (Presentation → Domain → Data).<br>- Domain must not depend on framework code.<br>- Use constructor injection.<br>- Repository interfaces must live in Domain.<br><br>Security Constraints:<br>- Validate inputs before use case execution.<br>- Do not expose raw errors to UI.<br>- Abstract secure token storage.<br><br>Testing Requirements:<br>- Generate unit tests for LoginUseCase.<br>- Generate ViewModel state transition tests.<br>- Cover success, failure, and edge cases.<br>- Tests must be written before implementation.<br><br>Refactoring Expectations:<br>- Keep ViewModels small.<br>- Extract validation into separate component.<br>- Use sealed classes / enums for UI state.<br><br>Acceptance Criteria:<br>- All tests pass.<br>- Domain has zero framework imports.<br>- UI contains no business logic.<br>- Dependency direction is inward only.<br><br>Output Format:<br>1. Markdown checklist with file paths.<br>2. Layer dependency diagram.<br>3. Test scaffolding.<br>4. Implementation code.</pre><p><strong>Key Principles of Structured Prompt Engineering:</strong></p><ol><li>Always define role</li><li>Always define architecture</li><li>Always define constraints</li><li>Always define test expectations</li><li>Always define output format</li><li>Separate planning from implementation</li><li>Validate before generating</li></ol><h3>10) Code Review Automation</h3><p>AI should not only generate code. It should review it.</p><p>AI Coding Assistant can act as an automated reviewer that validates architecture, enforces SOLID, checks state management correctness, verifies security practices, and detects structural drift before a human ever opens the pull request.</p><p>Used correctly, this creates a repeatable quality gate.</p><p><strong>AI can systematically check:</strong></p><ul><li>Clean Architecture violations</li><li>Dependency direction errors</li><li>Domain layer framework leaks</li><li>Improper coroutine or Combine usage</li><li>Missing test coverage</li><li>State modeling issues</li><li>Security risks</li><li>Excessive ViewModel responsibility</li></ul><p>This makes reviews more architectural and less cosmetic.</p><p><strong>AI Should Validate:</strong></p><p><strong>For Android:</strong></p><ul><li>No business logic inside Composables</li><li>ViewModels expose immutable StateFlow</li><li>Domain layer contains no Android imports</li><li>Repository implementations conform to interfaces</li><li>Coroutines launched correctly</li><li>No blocking calls on Main thread</li></ul><p><strong>For iOS:</strong></p><ul><li>Views contain no business logic</li><li>ViewModels properly use @Published</li><li>Domain layer does not import SwiftUI or Combine</li><li>Async work executed safely</li><li>Combine chains handled inside ViewModel</li></ul><p><strong>Cross-platform:</strong></p><ul><li>Dependency direction is inward only</li><li>SOLID principles respected</li><li>Tests cover success and failure paths</li><li>Error mapping prevents raw exception leakage</li></ul><p><strong>Code Review Prompt Example</strong></p><pre>Perform a comprehensive architectural code review for the Login feature.<br><br>Check for:<br><br>1. Clean Architecture Compliance<br>   - Are layers properly separated?<br>   - Does Domain layer import any framework code?<br>   - Is dependency direction correct?<br><br>2. SOLID Principles<br>   - Are classes single-responsibility?<br>   - Are interfaces small and focused?<br>   - Is dependency inversion respected?<br><br>3. State Management<br>   - Is UI state immutable?<br>   - Are ViewModels exposing only read-only state?<br>   - Are state transitions explicit?<br><br>4. Coroutine / Async Handling<br>   - Are suspend functions used correctly?<br>   - Is main thread never blocked?<br>   - Are errors handled properly?<br><br>5. Security<br>   - Input validation present?<br>   - No hardcoded secrets?<br>   - Errors mapped safely?<br><br>6. Testing<br>   - Are UseCases tested?<br>   - Are ViewModel state transitions tested?<br>   - Are edge cases covered?<br><br>Return:<br>- Violations grouped by severity (High / Medium / Low)<br>- Suggested fixes<br>- Refactored code snippets where necessary<br>- Confirmation of architectural integrity score (0–10)</pre><p><strong>Without automated review:</strong></p><ul><li>ViewModels slowly become god objects</li><li>Domain starts importing framework types</li><li>State modeling becomes inconsistent</li><li>Security holes appear</li><li>Architecture degrades over time</li></ul><p><strong>With AI code review automation:</strong></p><ul><li>Architecture stays enforceable</li><li>SOLID remains measurable</li><li>Tests remain meaningful</li><li>Refactors stay safe</li><li>Technical debt becomes visible early</li></ul><h3>Ready-to-Paste Project Templates</h3><p>The following templates provide a <strong>complete base repository structure</strong> you can clone and open in any AI Coding Assistant. The .ai/ directory is a placeholder name, rename it to match your AI Coding Assistant’s convention (.cursor/, .claude/, .github/, etc.).</p><p>You can copy these structures directly into new repositories.</p><h3>Android Project Template</h3><p><strong>Compose + Hilt + Coroutines + Clean Architecture</strong></p><pre>MyAndroidApp/<br>├── app/<br>│   ├── src/main/java/com/example/app/<br>│   │   ├── di/<br>│   │   │   └── AppModule.kt<br>│   │   ├── presentation/<br>│   │   │   ├── login/<br>│   │   │   │   ├── LoginScreen.kt<br>│   │   │   │   ├── LoginViewModel.kt<br>│   │   │   │   └── LoginUiState.kt<br>│   │   └── MainActivity.kt<br>│   └── src/test/java/com/example/app/<br>│       ├── presentation/LoginViewModelTest.kt<br>│<br>├── domain/<br>│   ├── entities/User.kt<br>│   ├── repository/AuthRepository.kt<br>│   ├── usecase/LoginUseCase.kt<br>│   └── test/LoginUseCaseTest.kt<br>│<br>├── data/<br>│   ├── network/LoginApi.kt<br>│   ├── dto/LoginResponse.kt<br>│   ├── mapper/UserMapper.kt<br>│   └── repository/AuthRepositoryImpl.kt<br>│<br>├── docs/<br>│   ├── Architecture/LoginFeature.md<br>│   ├── API/LoginContract.md<br>│   ├── Testing/LoginCoverage.md<br>│   └── Diagrams/login_flow.mmd<br>│<br>├── .ai/<br>│   ├── rules/<br>│   │   ├── android-core.mdc<br>│   │   ├── android-compose.mdc<br>│   │   └── android-tests.mdc<br>│   └── prompts/<br>│       ├── feature-plan.md<br>│       ├── test-first.md<br>│       ├── refactor.md<br>│       └── code-review.md<br>│<br>├── build.gradle.kts<br>└── settings.gradle.kts</pre><h3>iOS Project Template</h3><p><strong>SwiftUI + Combine + Clean Architecture</strong></p><pre>MyiOSApp/<br>├── Sources/<br>│   ├── Domain/<br>│   │   ├── Entities/User.swift<br>│   │   ├── Repositories/AuthRepository.swift<br>│   │   └── UseCases/LoginUseCase.swift<br>│   │<br>│   ├── Data/<br>│   │   ├── Network/LoginAPI.swift<br>│   │   ├── DTO/LoginResponse.swift<br>│   │   ├── Mappers/UserMapper.swift<br>│   │   └── Repositories/AuthRepositoryImpl.swift<br>│   │<br>│   └── Presentation/<br>│       ├── ViewModels/LoginViewModel.swift<br>│       └── Views/LoginView.swift<br>│<br>├── Tests/<br>│   ├── DomainTests/LoginUseCaseTests.swift<br>│   └── PresentationTests/LoginViewModelTests.swift<br>│<br>├── docs/<br>│   ├── Architecture/LoginFeature.md<br>│   ├── API/LoginContract.md<br>│   ├── Testing/LoginCoverage.md<br>│   └── Diagrams/login_flow.mmd<br>│<br>├── .ai/<br>│   ├── rules/<br>│   │   ├── ios-core.mdc<br>│   │   └── ios-tests.mdc<br>│   └── prompts/<br>│       ├── feature-plan.md<br>│       ├── test-first.md<br>│       ├── refactor.md<br>│       └── code-review.md<br>│<br>└── MyiOSApp.xcodeproj</pre><h3>Conclusion</h3><p>The AI Coding Assistant you use matters less than how you use it. Cursor, Claude Code, GitHub Copilot, Windsurf, they all respond to the same fundamentals: precise planning, engineering context, explicit architectural constraints, and test-first discipline.<br>To get the most out of any AI Coding Assistant:</p><ul><li>Start with detailed Feature Plans</li><li>Use persistent rule files</li><li>Write tests first</li><li>Apply Clean Architecture + SOLID</li><li>Refactor continuously</li><li>Generate and publish docs to Azure DevOps Wiki</li><li>Structure prompts for AI reasoning</li><li>Automate reviews with quality gates</li></ul><p>That discipline is what turns AI from a code completion shortcut into a <strong>collaborative engineering partner</strong> that helps you build reliable, well-documented mobile apps.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de335e9234f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin Ktor for Backend Development]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-kotlin-ktor-for-backend-development-8c4e5573ee72?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4e5573ee72</guid>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 10:34:41 GMT</pubDate>
            <atom:updated>2026-10-20T15:26:20.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Mck9YkBqQsqD2pVWDkXAw.png" /></figure><p>Kotlin has grown into one of the most popular languages among modern developers, and its role in server-side development is expanding quickly. At the heart of this growth is Ktor, a lightweight, Kotlin-native framework designed for building asynchronous servers and clients. It’s a powerful option for developers who want to create fast, reliable backend services without the heavy overhead of more traditional frameworks.</p><p>What makes Ktor stand out is its simplicity and flexibility. With a clean design and an intuitive routing system, it gives developers the tools to build everything from small APIs to full-scale microservices.</p><p>In this article, we’ll walk through the core concepts of Ktor for backend development and look at practical code examples to help you get up and running.</p><h3>Why Choose Ktor?</h3><p>One of the biggest strengths of Ktor is its flexibility, which makes it just as suitable for building small REST APIs as it is for powering large-scale microservices. Here are a few reasons why many developers choose Ktor for backend work:</p><ul><li><strong>Asynchronous by nature</strong>: Built on Kotlin coroutines, Ktor makes it easy to write efficient, non-blocking code that performs well under heavy load.</li><li><strong>Lightweight and modular</strong>: You only include the features you need, which keeps your application lean and avoids unnecessary bloat.</li><li><strong>Smooth integration</strong>: Ktor plays nicely with widely used libraries like Koin for dependency injection, giving you plenty of flexibility in structuring your projects.</li><li><strong>Non-blocking I/O</strong>: Thanks to its non-blocking design, Ktor can handle high traffic without sacrificing responsiveness.</li></ul><p>With those advantages in mind, let’s take a closer look at the core building blocks of Ktor and how to get the most out of them.</p><h3>Setting Up a Ktor Project</h3><p>Start by creating a new Ktor project. You can use IntelliJ IDEA’s Ktor project generator or set it up manually using Gradle. Below is a simple build.gradle.kts configuration:</p><pre>plugins {<br>    kotlin(&quot;jvm&quot;) version &quot;2.0.20&quot; // or kotlin(&quot;multiplatform&quot;) or any other kotlin plugin<br>    kotlin(&quot;plugin.serialization&quot;) version &quot;2.0.20&quot;<br>    id(&quot;io.ktor.plugin&quot;) version &quot;3.0.0-rc-2&quot;<br>}<br><br>group = &quot;com.michaelavoyan&quot;<br>version = &quot;0.0.1&quot;<br><br>application {<br>    mainClass.set(&quot;com.michaelavoyan.ApplicationKt&quot;)<br><br>    val isDevelopment: Boolean = project.ext.has(&quot;development&quot;)<br>    applicationDefaultJvmArgs = listOf(&quot;-Dio.ktor.development=$isDevelopment&quot;)<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation(&quot;io.ktor:ktor-server-core-jvm&quot;)<br>    implementation(&quot;io.ktor:ktor-server-netty-jvm&quot;)<br>    testImplementation(&quot;io.ktor:ktor-server-test-host-jvm&quot;)<br><br>    implementation(&quot;io.ktor:ktor-server-cors:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-server-netty:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-server-core:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-client-auth:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-client-apache:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-server-request-validation:$ktor_version&quot;)<br>    implementation(&quot;io.ktor:ktor-server-content-negotiation:$ktor_version&quot;)<br><br>    implementation(&quot;io.insert-koin:koin-core:$koin_version&quot;)<br>    implementation(&quot;io.insert-koin:koin-ktor:$koin_version&quot;)<br>    implementation(&quot;io.insert-koin:koin-logger-slf4j:$koin_version&quot;)<br><br>    implementation(&quot;ch.qos.logback:logback-classic:$logback_version&quot;)<br><br>    implementation(&quot;io.ktor:ktor-serialization-kotlinx-json:$ktor_serialization_version&quot;)<br><br>    implementation(&quot;org.litote.kmongo:kmongo:$kmongo_version&quot;)<br>    implementation(&quot;org.litote.kmongo:kmongo-coroutine:$kmongo_version&quot;)<br><br>    implementation(&quot;org.apache.kafka:kafka-clients:$kafka_version&quot;)<br><br>    testImplementation(&quot;junit:junit:$junit_version&quot;)<br>    testImplementation(&quot;org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version&quot;)<br>    testImplementation(&quot;io.ktor:ktor-server-tests:$ktor_version&quot;)<br>    testImplementation(&quot;io.ktor:ktor-serialization-kotlinx-json:$ktor_version&quot;)<br>    testImplementation(&quot;io.mockk:mockk:$mockk_version&quot;)<br>    testImplementation(&quot;io.insert-koin:koin-test:$koin_version&quot;)<br>    testImplementation(&quot;io.insert-koin:koin-test-junit5:$koin_version&quot;)<br>}</pre><p>Run the project, and you’re ready to build your first API.</p><h3>Structuring Your Ktor Application</h3><p>As your application grows, organizing your code by grouping related components can help maintain clarity and scalability. Here’s a suggested structure:</p><ul><li>routes/ : Contains route definitions for each module (e.g., UserRoutes.kt).</li><li>services/ : Houses business logic, like UserService.</li><li>config/ : Contains Koin dependency injection modules and configuration settings.</li><li>data/: Include data access logic, possibly using repository classes (UserRepository.kt).</li><li>plugins/: Configure reusable features like json parser, authentication, logging, CORS, etc.</li></ul><p>This modular approach not only improves readability but also simplifies testing and debugging, making your application easier to manage.</p><h3>Initializing the Server and Adding Plugins</h3><p>Ktor uses plugins to add middleware-like functionality. Here’s how to initialize a Ktor server with basic configurations, including the ContentNegotiation plugin for JSON parsing:</p><pre>import io.ktor.server.application.*<br>import io.ktor.server.engine.*<br>import io.ktor.server.netty.*<br>import io.ktor.server.response.*<br>import io.ktor.server.routing.*<br>import io.ktor.server.plugins.contentnegotiation.*<br>import io.ktor.serialization.kotlinx.json.*<br><br>fun main() {<br>    embeddedServer(Netty, port = 5000, host = &quot;0.0.0.0&quot;, module = Application::module)<br>        .start(wait = true)<br>}<br><br>fun Application.module() {<br>        install(Koin) {<br>        slf4jLogger()  // Optional logging<br>        modules(Modules)<br>    }<br><br>    // Install ContentNegotiation before routing and security configurations<br>    install(ContentNegotiation) {<br>        json(Json {<br>            prettyPrint = true<br>            isLenient = true<br>            ignoreUnknownKeys = true<br>        })<br>    }<br><br>    install(CORS) {<br>        allowMethod(HttpMethod.Options)<br>        allowMethod(HttpMethod.Put)<br>        allowMethod(HttpMethod.Delete)<br>        allowMethod(HttpMethod.Patch)<br>        allowHeader(HttpHeaders.Authorization)<br>//        allowHeader(&quot;MyCustomHeader&quot;)<br>//        anyHost() // @TODO: Don&#39;t do this in production if possible. Try to limit it.<br>    }<br>}</pre><h3>Routing in Ktor</h3><p>Routing is a fundamental part of any web server, and Ktor makes it intuitive and flexible. Routes define paths that your server responds to, allowing you to structure your application into manageable sections.</p><h4>Organizing Routes</h4><p>To keep routes organized, split them into functions or files:</p><pre>fun Application.registerRoutes() {<br>    routing {<br>        route(&quot;/api&quot;) {<br>            get(&quot;/items&quot;) { call.respondText(&quot;Listing all items&quot;) }<br>            post(&quot;/items&quot;) { call.respondText(&quot;Adding a new item&quot;) }<br>        }<br>    }<br>}</pre><p>Grouping related routes under /api improves maintainability.</p><h4>Working with Parameters</h4><p>Handle both query and path parameters easily:</p><pre>get(&quot;/user/{id}&quot;) {<br>    val userId = call.parameters[&quot;id&quot;] ?: &quot;unknown&quot;<br>    call.respondText(&quot;User ID: $userId&quot;)<br>}</pre><p>In this snippet, {id} is a dynamic segment of the URL.</p><h4>Using Route Extensions</h4><p>To keep routing logic clean, use extension functions:</p><pre>fun Route.userRoutes() {<br>    get(&quot;/user/{id}&quot;) {<br>        val id = call.parameters[&quot;id&quot;] ?: &quot;unknown&quot;<br>        call.respondText(&quot;User with ID: $id&quot;)<br>    }<br>}</pre><pre>fun Application.registerUserRoutes() {<br>    routing { userRoutes() }<br>}</pre><p>userRoutes() keeps route definitions modular.</p><h4>Route Order Matters</h4><p>Routes are processed in the order they are defined. Place specific routes before general ones:</p><pre>routing {<br>    get(&quot;/item/special&quot;) { call.respondText(&quot;Special item&quot;) }<br>    get(&quot;/item/{id}&quot;) {<br>        val id = call.parameters[&quot;id&quot;] ?: &quot;unknown&quot;<br>        call.respondText(&quot;Item with ID: $id&quot;)<br>    }<br>}</pre><p>Ensure /item/special is defined before /item/{id}.</p><h4>CRUD Operations in Ktor</h4><p>Ktor makes it easy to create CRUD (Create, Read, Update, Delete) operations. Below is an example of how to implement basic CRUD operations for an Item resource:</p><pre>data class Item(val id: String, val name: String)<br>val items = mutableListOf&lt;Item&gt;()<br>fun Application.registerCrudRoutes() {<br>    routing {<br>        route(&quot;/items&quot;) {<br>            // Create<br>            post {<br>                val item = call.receive&lt;Item&gt;()<br>                items.add(item)<br>                call.respondText(&quot;Item added&quot;, status = HttpStatusCode.Created)<br>            }<br>            // Read all<br>            get {<br>                call.respond(items)<br>            }<br>            // Read one<br>            get(&quot;/{id}&quot;) {<br>                val id = call.parameters[&quot;id&quot;] ?: return@get call.respondText(&quot;Missing ID&quot;, status = HttpStatusCode.BadRequest)<br>                val item = items.find { it.id == id } ?: return@get call.respondText(&quot;Not Found&quot;, status = HttpStatusCode.NotFound)<br>                call.respond(item)<br>            }<br>            // Update<br>            put(&quot;/{id}&quot;) {<br>                val id = call.parameters[&quot;id&quot;] ?: return@put call.respondText(&quot;Missing ID&quot;, status = HttpStatusCode.BadRequest)<br>                val updatedItem = call.receive&lt;Item&gt;()<br>                val index = items.indexOfFirst { it.id == id }<br>                if (index == -1) {<br>                    return@put call.respondText(&quot;Not Found&quot;, status = HttpStatusCode.NotFound)<br>                }<br>                items[index] = updatedItem<br>                call.respondText(&quot;Item updated&quot;, status = HttpStatusCode.OK)<br>            }<br>            // Delete<br>            delete(&quot;/{id}&quot;) {<br>                val id = call.parameters[&quot;id&quot;] ?: return@delete call.respondText(&quot;Missing ID&quot;, status = HttpStatusCode.BadRequest)<br>                if (items.removeIf { it.id == id }) {<br>                    call.respondText(&quot;Item deleted&quot;, status = HttpStatusCode.OK)<br>                } else {<br>                    call.respondText(&quot;Not Found&quot;, status = HttpStatusCode.NotFound)<br>                }<br>            }<br>        }<br>    }<br>}</pre><ul><li><strong>Create</strong>: Adds a new item to the list.</li><li><strong>Read</strong>: Retrieves all items or a specific item by ID.</li><li><strong>Update</strong>: Updates an existing item by ID.</li><li><strong>Delete</strong>: Deletes an item by ID.</li></ul><h4>Best Practices for Routing in Ktor</h4><ol><li><strong>Use Nested Routes:</strong> Group related routes with route() for readability.</li><li><strong>Use Constants for Paths:</strong> Avoid hardcoding strings to reduce bugs.</li><li><strong>Separate Logic from Routing:</strong> Delegate complex operations to service classes or helper functions.</li><li><strong>Error Handling:</strong> Implement error handling using status pages or exception middleware.</li><li><strong>Use HTTP Methods Correctly:</strong> Use appropriate HTTP methods (GET, POST, PUT, DELETE).</li></ol><h3>Error Handling and Custom Responses</h3><p>To provide a consistent user experience and facilitate debugging, create custom error handling and response wrappers. Install the StatusPages plugin to manage exceptions and return meaningful HTTP status codes:</p><pre>import io.ktor.http.*<br>import io.ktor.server.plugins.statuspages.*<br>import io.ktor.server.response.*<br><br>install(StatusPages) {<br>    exception&lt;Throwable&gt; { cause -&gt;<br>        call.respond(HttpStatusCode.InternalServerError, &quot;An error occurred: ${cause.localizedMessage}&quot;)<br>    }<br>    status(HttpStatusCode.NotFound) {<br>        call.respond(HttpStatusCode.NotFound, &quot;Resource not found&quot;)<br>    }<br>}</pre><p>This setup ensures clients receive clear responses for errors, improving the user experience while keeping sensitive backend information secure.</p><h3>Authentication and Authorization</h3><p>Authentication and authorization are critical in backend services. Ktor supports various authentication methods, including JWT and OAuth. Here’s a setup for JWT authentication:</p><ul><li>Add required dependency:</li></ul><pre>implementation(&quot;io.ktor:ktor-server-auth:$ktor_version&quot;)</pre><ul><li>Configure JWT Authentication:</li></ul><pre>install(Authentication) {<br>    jwt(&quot;auth-jwt&quot;) {<br>        verifier(JwtProvider.verifier)<br>        validate { credentials -&gt;<br>            if (credentials.payload.audience.contains(&quot;your-audience&quot;)) JWTPrincipal(credentials.payload) else null<br>        }<br>    }<br>}</pre><ul><li><strong>Protect Routes</strong>: Use authenticate(&quot;auth-jwt&quot;) to secure specific routes, ensuring only authorized users access sensitive areas.</li></ul><p>This configuration offers flexibility, allowing you to add secure authentication for APIs without sacrificing performance.</p><h3>Asynchronous Tasks with Coroutines</h3><p>Ktor’s non-blocking architecture, powered by coroutines, enables efficient handling of asynchronous tasks in high-concurrency environments. Here’s how to effectively manage asynchronous tasks:</p><ul><li><strong>Avoid Using GlobalScope</strong>: Use launch or async within the Application scope to tie tasks to requests.</li></ul><pre>get(&quot;/data&quot;) {<br>    val result = async { dataService.fetchData() }.await()<br>    call.respond(result)<br>}</pre><ul><li><strong>Exception Handling in Coroutines</strong>: Wrap asynchronous calls in try-catch blocks to handle errors gracefully and prevent resource leaks.</li></ul><p>By following these practices, you can handle asynchronous operations efficiently without blocking the main thread.</p><h3>Dependency Injection with Koin</h3><p>Ktor integrates well with Koin for Dependency Injection (DI), allowing you to manage your services and objects in a clean, testable way.</p><p>First, add the necessary dependencies in your build.gradle.kts:</p><pre>implementation(&quot;io.insert-koin:koin-core:$koin_version&quot;)<br>implementation(&quot;io.insert-koin:koin-ktor:$koin_version&quot;)</pre><h4>Setting Up Koin Modules</h4><p>A good practice is to create separate Koin modules for different parts of your application:</p><pre>import org.koin.dsl.module</pre><pre>val serviceModule = module {<br>    single { UserService() }<br>}</pre><pre>val repositoryModule = module {<br>    single { UserRepository() }<br>}</pre><h4>Using Dependency Injection in Routes</h4><p>With Koin, injecting dependencies like UserService in Ktor routes is straightforward:</p><pre>import org.koin.ktor.plugin.Koin<br>import org.koin.ktor.ext.inject</pre><pre>class UserService {<br>    fun getUserGreeting(name: String) = &quot;Hello, $name!&quot;<br>}</pre><pre>fun Application.module() {<br>    install(Koin) {<br>        modules(serviceModule)<br>    }</pre><pre>    routing {<br>        get(&quot;/greet/{name}&quot;) {<br>            val userService: UserService by inject()<br>            val name = call.parameters[&quot;name&quot;] ?: &quot;Guest&quot;<br>            call.respondText(userService.getUserGreeting(name))<br>        }<br>    }<br>}</pre><h3>Testing and Mocking in Ktor</h3><p>Testing is crucial to maintain high-quality code. Ktor’s testApplication API simplifies unit testing for routes and services. For DI, you can mock services using Koin.</p><ul><li>Setup Test Modules:</li></ul><pre>val testModule = module {<br>    single&lt;UserService&gt; { mockk() }<br>}</pre><ul><li>Write Route Tests:</li></ul><pre>@Test<br>fun testUserRoute() = testApplication {<br>    application { module() }<br>    client.get(&quot;/user&quot;).apply {<br>        assertEquals(HttpStatusCode.OK, status)<br>        assertEquals(&quot;Hello, World!&quot;, bodyAsText())<br>    }<br>}</pre><ul><li><strong>Mock External Services</strong>: Using Koin’s mockk library allows you to mock external dependencies, ensuring tests are reliable and isolated.</li></ul><h3>Conclusion</h3><p>Ktor has quickly established itself as one of the most flexible and powerful frameworks for backend development with Kotlin. Its native support for coroutines, modular design, and smooth integration with tools like Koin make it a strong choice for building modern microservices.</p><p>If you take the time to structure your application well, handle errors cleanly, and follow best practices around dependency injection and authentication, Ktor will give you everything you need to deliver scalable, high-performance backend services.</p><h3>Additional Resources</h3><p><a href="https://kotlinlang.org/docs/home.html">Kotlin Documentation</a></p><p><a href="https://ktor.io/docs/welcome.html">Ktor Documentation</a></p><p><a href="https://insert-koin.io/docs/reference/koin-ktor/ktor">Koin Documentation</a></p><p><a href="https://jwt.io/introduction/">JWT Introduction</a></p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4e5573ee72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Fastify]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-fastify-be9b59892da0?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/be9b59892da0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[fastify]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[servers]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 18:40:08 GMT</pubDate>
            <atom:updated>2026-10-20T15:26:35.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQURaKW1gv9FVEX0TiXUCg.png" /></figure><p>Fastify is a lightweight and high-performance web framework for Node.js. It’s designed with speed and efficiency in mind, while also offering a flexible plugin system that makes it easy to extend. Whether you’re putting together a small API or building out a larger, more complex application, Fastify can help you write cleaner code, ship faster, and get better performance out of your server.</p><p>In this guide, we’ll cover everything from the fundamentals to more advanced techniques, with plenty of practical code examples along the way to help you become confident in using Fastify.</p><h3>Why Choose Fastify?</h3><p>Before we jump into the code, it’s worth looking at what makes Fastify stand out from the crowd.</p><ul><li><strong>Performance:</strong> Fastify is built for speed. Its optimized core makes it one of the fastest Node.js frameworks you can use today.</li><li><strong>Schema-based validation:</strong> With built-in support for JSON Schema, you can validate requests upfront and keep your API reliable and predictable.</li><li><strong>Extensibility:</strong> Thanks to its plugin architecture, you can extend Fastify in a clean and modular way, no matter how simple or complex your project is.</li><li><strong>Developer experience:</strong> From clear error messages to a straightforward API, Fastify is designed to make development smoother and less painful.</li></ul><h3>Setting Up Fastify</h3><p>Start by setting up a new Fastify project. Ensure you have Node.js installed, then follow these steps:</p><pre># Create a new project directory<br>mkdir fastify-project<br>cd fastify-project<br><br># Initialize a new Node.js project<br>npm init -y<br><br># Install Fastify<br>npm install fastify --save</pre><h3>Basic Server Setup</h3><p>Create a file named server.js and set up a basic Fastify server:</p><pre>// server.js<br>const fastify = require(&#39;fastify&#39;)({ logger: true });<br><br>fastify.get(&#39;/&#39;, async (request, reply) =&gt; {<br>  return { hello: &#39;world&#39; };<br>});<br><br>const start = async () =&gt; {<br>  try {<br>    await fastify.listen({ port: 3000 });<br>    console.log(`Server listening at http://localhost:3000`);<br>  } catch (err) {<br>    fastify.log.error(err);<br>    process.exit(1);<br>  }<br>};<br><br>start();</pre><p>Run your server with node server.js, and you should see your Fastify server running at <a href="http://localhost:3000.">http://localhost:3000.</a></p><h3>Adding Routes</h3><p>Fastify makes it easy to add routes. Here’s how you can add a POST route with JSON schema validation:</p><pre>// server.js (continued)<br><br>fastify.post(&#39;/data&#39;, {<br>  schema: {<br>    body: {<br>      type: &#39;object&#39;,<br>      required: [&#39;name&#39;, &#39;age&#39;],<br>      properties: {<br>        name: { type: &#39;string&#39; },<br>        age: { type: &#39;number&#39; }<br>      }<br>    },<br>    response: {<br>      200: {<br>        type: &#39;object&#39;,<br>        properties: {<br>          status: { type: &#39;string&#39; },<br>          data: { type: &#39;object&#39; }<br>        }<br>      }<br>    }<br>  }<br>}, async (request, reply) =&gt; {<br>  const { name, age } = request.body;<br>  return { status: &#39;success&#39;, data: { name, age } };<br>});</pre><h3>Middleware and Plugins</h3><p>Fastify’s plugin system is one of its most powerful features. You can create reusable plugins for tasks like authentication, logging, and more.</p><p><strong>Creating a Plugin:</strong></p><pre>const fp = require(&#39;fastify-plugin&#39;);<br><br>// plugins/logger.js<br>async function loggerPlugin(fastify, options) {<br>  fastify.addHook(&#39;onRequest&#39;, async (request, reply) =&gt; {<br>    console.log(`Incoming request: ${request.method} ${request.url}`);<br>  });<br>}<br><br>module.exports = {<br>  loggerPlugin: fp(loggerPlugin, {<br>    fastify: &#39;&gt;=2.0.0&#39;,<br>    name: &#39;logger-plugin&#39;,<br>  }),<br>};</pre><p><strong>Registering a Plugin:</strong></p><pre>// server.js (continued)<br>const loggerPlugin = require(&#39;./plugins/logger&#39;);<br><br>fastify.register(loggerPlugin);</pre><h3>Error Handling</h3><p>Fastify provides a robust error handling mechanism. You can define a global error handler to catch and process errors:</p><pre>// server.js (continued)<br>fastify.setErrorHandler((error, request, reply) =&gt; {<br>  reply.status(error.statusCode || 500).send({ error: error.message });<br>});</pre><h3>Advanced Techniques</h3><p>Now that you have a grasp of the basics, let’s dive into some advanced techniques to fully harness the power of Fastify.</p><h3>Custom Decorators</h3><p>Decorators in Fastify allow you to add custom functionality to your application. Let’s create a custom decorator for caching:</p><pre>// plugins/cache.js<br>const fp = require(&#39;fastify-plugin&#39;);<br><br>async function cacheDecorator(fastify, options) {<br>  const cache = new Map();<br><br>  fastify.decorate(&#39;cache&#39;, {<br>    get(key) {<br>      return cache.get(key);<br>    },<br>    set(key, value) {<br>      cache.set(key, value);<br>    },<br>    delete(key) {<br>      cache.delete(key);<br>    }<br>  });<br>}<br><br>module.exports = fp(cacheDecorator);</pre><p>Register the custom decorator in your server:</p><pre>// server.js (continued)<br>const cacheDecorator = require(&#39;./plugins/cache&#39;);<br>fastify.register(cacheDecorator);<br><br>fastify.get(&#39;/cache-example&#39;, async (request, reply) =&gt; {<br>  const key = &#39;example&#39;;<br>  let value = fastify.cache.get(key);<br><br>  if (!value) {<br>    value = { message: &#39;This is a cached response&#39; };<br>    fastify.cache.set(key, value);<br>  }<br><br>  reply.send(value);<br>});</pre><h3>Advanced Schema Validation</h3><p>Fastify uses JSON Schema for validation, which can be extended with custom formats and keywords:</p><pre>fastify.addSchema({<br>  $id: &#39;userSchema&#39;,<br>  type: &#39;object&#39;,<br>  properties: {<br>    username: { type: &#39;string&#39; },<br>    password: { type: &#39;string&#39;, minLength: 6 }<br>  },<br>  required: [&#39;username&#39;, &#39;password&#39;]<br>});<br><br>fastify.route({<br>  method: &#39;POST&#39;,<br>  url: &#39;/login&#39;,<br>  schema: {<br>    body: { $ref: &#39;userSchema#&#39; },<br>    response: {<br>      200: {<br>        type: &#39;object&#39;,<br>        properties: {<br>          token: { type: &#39;string&#39; }<br>        }<br>      }<br>    }<br>  },<br>  handler: async (request, reply) =&gt; {<br>    const { username, password } = request.body;<br>    // Perform login logic<br>    const token = fastify.jwt.sign({ username });<br>    reply.send({ token });<br>  }<br>});</pre><h3>Lifecycle Hooks</h3><p>Fastify provides lifecycle hooks to run code at different stages of the request/response cycle:</p><pre>// server.js (continued)<br>fastify.addHook(&#39;onRequest&#39;, async (request, reply) =&gt; {<br>  // Perform actions before the request is processed<br>  console.log(&#39;Request received:&#39;, request.url);<br>});<br><br>fastify.addHook(&#39;preHandler&#39;, async (request, reply) =&gt; {<br>  // Perform actions before the route handler is called<br>  console.log(&#39;Before handler:&#39;, request.url);<br>});<br><br>fastify.addHook(&#39;onSend&#39;, async (request, reply, payload) =&gt; {<br>  // Modify the response payload<br>  console.log(&#39;Response payload:&#39;, payload);<br>  return payload;<br>});<br><br>fastify.addHook(&#39;onResponse&#39;, async (request, reply) =&gt; {<br>  // Perform actions after the response is sent<br>  console.log(&#39;Response sent:&#39;, request.url);<br>});</pre><h3>Authentication with JWT</h3><p>Adding JWT authentication to your Fastify application is straightforward with fastify-jwt and fastify-auth:</p><pre>// server.js (continued)<br>const fastifySwagger = require(&#39;fastify-swagger&#39;);<br>const fastifyAuth = require(&#39;fastify-auth&#39;);<br>const fastifyJwt = require(&#39;fastify-jwt&#39;);<br><br>// Register plugins<br>fastify.register(fastifySwagger, {<br>  routePrefix: &#39;/documentation&#39;,<br>  swagger: {<br>    info: {<br>      title: &#39;Fastify API&#39;,<br>      description: &#39;Advanced Fastify API documentation&#39;,<br>      version: &#39;1.0.0&#39;<br>    },<br>    host: &#39;localhost:3000&#39;,<br>    schemes: [&#39;http&#39;],<br>    consumes: [&#39;application/json&#39;],<br>    produces: [&#39;application/json&#39;],<br>  },<br>  exposeRoute: true<br>});<br><br>fastify.register(fastifyAuth);<br>fastify.register(fastifyJwt, { secret: &#39;supersecret&#39; });<br><br>// JWT Authentication Hook<br>fastify.decorate(&#39;authenticate&#39;, async function (request, reply) {<br>  try {<br>    await request.jwtVerify();<br>  } catch (err) {<br>    reply.send(err);<br>  }<br>});<br><br>// Routes<br>fastify.post(&#39;/signup&#39;, async (request, reply) =&gt; {<br>  const token = fastify.jwt.sign({ user: request.body.username });<br>  reply.send({ token });<br>});<br><br>fastify.get(&#39;/protected&#39;, { preHandler: [fastify.auth([fastify.authenticate])] }, async (request, reply) =&gt; {<br>  reply.send({ message: &#39;This is a protected route&#39; });<br>});</pre><h3>Testing Your Application</h3><p>Testing is crucial for any professional application. Fastify integrates well with testing libraries like tap and jest.</p><p><strong>Example with Tap:</strong></p><pre>// test/routes.test.js<br>const { test } = require(&#39;tap&#39;);<br>const buildFastify = require(&#39;../server&#39;);<br><br>test(&#39;requests the &quot;/&quot; route&#39;, async (t) =&gt; {<br>  const fastify = buildFastify();<br><br>  const response = await fastify.inject({<br>    method: &#39;GET&#39;,<br>    url: &#39;/&#39;<br>  });<br><br>  t.equal(response.statusCode, 200);<br>  t.same(JSON.parse(response.payload), { hello: &#39;world&#39; });<br>});</pre><h3>Deploying with Docker</h3><p>To deploy your Fastify application, you can use Docker for containerization:</p><pre># Dockerfile<br>FROM node:18<br><br>WORKDIR /usr/src/app<br><br>COPY package*.json ./<br>RUN npm install<br><br>COPY . .<br><br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;server.js&quot;]</pre><p>Build and run your Docker container:</p><pre>docker build -t fastify-advanced .<br>docker run -p 3000:3000 fastify-advanced</pre><h3>Conclusion</h3><p>Fastify isn’t just fast, it’s also flexible and packed with features that can make your Node.js applications both powerful and maintainable. With tools like custom decorators, advanced schema validation, lifecycle hooks, and rich error handling, you have everything you need to build applications that are both high-performing and reliable.</p><p>The best way to master Fastify is to experiment. Try out these advanced techniques, push the framework a little further, and see how it fits into your projects. With practice, you’ll not only unlock the full potential of Fastify but also level up your skills as a Node.js developer.</p><p>Happy coding!</p><h3>Additional Resources</h3><ul><li><a href="https://fastify.dev/docs/latest/">Fastify Documentation</a></li><li><a href="https://nodejs.org/docs/latest/api/">Node.js Documentation</a></li><li><a href="https://json-schema.org/docs">JSON Schema Documentation</a></li></ul><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be9b59892da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Role of a Multidisciplinary Software Development Manager]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-the-role-of-a-multidisciplinary-software-development-manager-a95125c31993?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/a95125c31993</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[multidisciplinary-team]]></category>
            <category><![CDATA[tech-manager]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <category><![CDATA[career-growth]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 15:25:59 GMT</pubDate>
            <atom:updated>2026-10-20T15:26:49.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z8g37kUjgj513IOss4a1Q.png" /></figure><p>Today’s tech landscape moves fast, and users expect smooth, consistent experiences no matter what device or platform they’re on. Meeting those expectations doesn’t happen by accident, it requires strong leadership that understands how to bring different technologies together.</p><p>As a multidisciplinary software development manager, your job is to connect the dots between frontend and backend, align people around shared goals, and make sure your team delivers software that feels seamless to the end user. That means more than just knowing the technology stack; it involves contributing to API design, shaping frontend architecture, and guiding the collaboration between specialists.</p><p>Here’s what it takes to grow into a well-rounded leader who can thrive in this role.</p><h3>1. Embrace the Multidisciplinary Mindset</h3><p>The foundation of being an effective manager in multidisciplinary development is mindset. You need to see the bigger picture, recognizing both the challenges and the opportunities that come with building for mobile, web, and backend systems. Each platform has its own strengths and constraints, and your job is to weave them together into a single, seamless user experience.</p><p>Start with the frontend. Work closely with your team to understand the nuances of UI and UX design, and get involved in architectural discussions. When you can speak the same language as your frontend developers, you bridge gaps and make better decisions that directly impact usability and design consistency.</p><p>On the backend side, your involvement is just as critical. The way APIs are designed determines how well the entire system holds together. Collaborate with your backend team to define clear, scalable APIs that are easy to implement, follow standards like REST or GraphQL, and are properly documented and versioned. These aren’t just technical details, they’re the glue that makes cross-platform experiences possible.</p><p>By actively engaging in both frontend and backend processes, you foster a culture of collaboration and ensure that every part of your application works in harmony. The result is software that’s not only functional, but also intuitive, efficient, and polished.</p><h3>2. Master the Necessary Technologies</h3><p>Leading a multidisciplinary team means having enough technical depth to guide, support, and challenge your developers. You don’t need to be the top expert in every framework, but you should understand the tools your team uses and why they matter.</p><p>On the frontend, that might mean staying familiar with frameworks like React, Vue, or React Native, and keeping an eye on emerging approaches such as Kotlin Multiplatform (KMM/KMP). Each comes with tradeoffs in performance, scalability, and cross-platform support. Knowing these differences helps you steer your team toward the right choice for the project.</p><p>On the backend, the same principle applies. Whether your stack involves Node.js with Fastify or Express, or more enterprise-focused options like Spring, you should understand how these frameworks shape development speed, scalability, and maintainability.</p><p>This breadth of knowledge allows you to make sound architectural decisions, challenge assumptions when necessary, and ensure your team isn’t just building quickly, but building sustainably.</p><h3>3. Cultivate a Collaborative Culture</h3><p>Multidisciplinary development only works when collaboration is at the center. As a manager, you’re not just coordinating tasks, you’re creating an environment where designers, backend developers, QA testers, and other stakeholders can work together seamlessly.</p><p>Encourage open communication and make it clear that every perspective matters. When team members feel comfortable sharing ideas and raising concerns, you’ll catch issues earlier and often arrive at more creative solutions.</p><p>Leverage collaboration tools to keep everyone aligned, like Slack or Twist for quick communication, Jira and Confluence for tracking and documentation, and platforms like HackMD for knowledge sharing. These tools are only effective if you pair them with the right culture: one where transparency, respect, and feedback are the norm.</p><p>When collaboration becomes second nature, you eliminate many of the friction points that often slow down multidisciplinary teams and instead create space for real innovation.</p><h3>4. Prioritize Code Quality and Consistency</h3><p>When you’re managing development across multiple platforms, consistency is everything. Without clear standards, codebases quickly drift apart, making collaboration harder and introducing avoidable bugs.</p><p>Set coding guidelines that apply across frontend and backend, and make sure your team follows them. Code reviews should be a non-negotiable part of the workflow, not just for catching errors, but also for sharing knowledge and aligning on best practices.</p><p>Complement this with strong automation. Invest in CI/CD pipelines and automated testing to spot issues early, reduce manual overhead, and maintain confidence in every release. The earlier problems are caught, the easier (and cheaper) they are to fix.</p><p>By holding a high bar for quality and consistency, you ensure your software isn’t just functional, it’s maintainable, scalable, and reliable over time.</p><h3>5. Focus on User Experience</h3><p>At the end of the day, the success of any product comes down to the user experience. No matter how elegant the architecture or how clean the code, if the application feels clunky or confusing, users won’t stick around.</p><p>Work hand in hand with your UX and UI designers to create interfaces that are intuitive, responsive, and visually engaging. Don’t treat design as an afterthought, it should be part of the conversation from the start.</p><p>Go beyond assumptions by collecting real-world feedback. Use analytics, user testing, and direct input from customers to understand how people actually interact with your application. Pair that insight with a strong backend foundation: services should be reliable, performant, and built to support smooth experiences on the frontend.</p><p>When frontend polish and backend strength work together, you deliver products that not only function well but truly delight users.</p><h3>6. Stay Updated with Industry Trends</h3><p>Technology never stands still, and neither can you. Frameworks, tools, and best practices evolve quickly, and staying current is critical if you want your team to remain competitive and effective.</p><p>Keep an eye on industry news, join professional communities, and attend conferences or workshops where new ideas are shared. Online forums and developer networks can also be valuable for spotting emerging trends before they become mainstream.</p><p>Encourage your team to do the same and make continuous learning part of the culture. Whether it’s experimenting with a new frontend framework, adopting a backend performance optimization, or trying out updated CI/CD practices, a learning mindset keeps your team sharp and adaptable.</p><p>By staying informed and open to change, you position your team to take advantage of new opportunities and deliver better results, faster.</p><h3>7. Manage Resources Effectively</h3><p>Strong leadership isn’t just about guiding the technology, it’s also about managing resources wisely. In multidisciplinary development, that means knowing your team’s strengths and aligning tasks with the right people. When developers are working in areas where they excel, productivity rises and the quality of work improves.</p><p>Make sure the infrastructure and tools your team relies on are up to the task. From version control and CI/CD pipelines to testing environments and monitoring tools, the right setup reduces friction and keeps projects moving smoothly.</p><p>Project timelines should never be static. Review progress regularly, adjust priorities, and reallocate resources when necessary to avoid bottlenecks. Just as importantly, balance the workload between frontend and backend tasks so one side of the team doesn’t get overloaded.</p><p>By treating resource management as an ongoing process, you keep your team aligned, motivated, and on track to deliver high-quality results.</p><h3>8. Foster a Growth Mindset</h3><p>Great teams don’t just deliver, they grow. As a leader, one of the most valuable things you can do is cultivate a growth mindset within your team. Encourage developers to see challenges not as roadblocks, but as opportunities to sharpen their skills and find better solutions.</p><p>Support this mindset with regular feedback that’s constructive and actionable. Celebrate wins, big and small, so your team feels recognized and motivated. At the same time, provide clear paths for professional development, whether that’s workshops, online courses, certifications, or opportunities to take on new responsibilities.</p><p>A team that’s motivated to keep learning will adapt faster, overcome obstacles more effectively, and consistently push the quality of its work higher. Over time, that culture of growth becomes a competitive advantage.</p><h3>9. Lead by Example</h3><p>As a manager, your behavior sets the tone for the entire team. If you want your team to be proactive, collaborative, and solution-oriented, you need to model those qualities yourself.</p><p>Be approachable and willing to step in when challenges arise. Show that you’re not just giving directions from the sidelines, you’re ready to roll up your sleeves and work alongside your team when it matters.</p><p>Your grasp of both frontend and backend technologies, as well as your active involvement in API design, demonstrates the value of being well-rounded. By leading through action, you’ll inspire your team to expand their own skills and grow into more versatile engineers.</p><p>When your team sees you living the standards you set, they’re far more likely to follow.</p><h3>10. Celebrate Successes</h3><p>Amid deadlines and deliverables, it’s easy to overlook one of the most powerful motivators: Recognition. Taking time to celebrate your team’s wins, both big and small, goes a long way in building morale and reinforcing a sense of shared purpose.</p><p>Celebrate achievements in ways that feel authentic to your team. That might mean team outings, shoutouts during meetings, or even a simple message of appreciation. What matters most is that people feel seen and valued for their contributions.</p><p>By acknowledging success, you not only boost motivation but also strengthen camaraderie. A team that feels appreciated is more engaged, more resilient, and more committed to doing great work together.</p><h3>Conclusion</h3><p>Leading a multidisciplinary software development team is as challenging as it is rewarding. It’s a role that demands both technical breadth and strong leadership, balancing frontend and backend expertise with the ability to guide people, processes, and priorities.</p><p>By embracing these principles, cultivating collaboration, staying current with industry trends, setting high standards for quality, and leading by example, you create an environment where your team can thrive. When everyone is aligned around a shared vision, the result is more than just functional software, it’s applications that delight users, strengthen your organization, and stand the test of time.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a95125c31993" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kotlin’s Coroutine Flows]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-koltins-coroutine-flows-383d55a4857a?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/383d55a4857a</guid>
            <category><![CDATA[andorid]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 21:45:11 GMT</pubDate>
            <atom:updated>2026-10-20T15:27:17.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2fc4u2gGvGA2ewBE0nkwg.png" /></figure><p>Asynchronous programming often feels tricky to manage, but Kotlin’s coroutine flows provide a clean and powerful way to work with it. In this article, we’ll break down what flows are, how they work, and the best practices for using them effectively.</p><p>If you’re new to Kotlin coroutines, I recommend starting with my earlier article, <a href="https://medium.com/@michael.avoyan/making-the-first-steps-in-learning-kotlin-coroutines-653d89034ff8"><strong>Making the First Steps in Learning Kotlin Coroutines</strong></a>. It introduces the basics and will give you a solid foundation before diving into flows.</p><h3>Introduction to Coroutine Flows</h3><p>Coroutine flows in Kotlin are built to handle streams of data that are produced asynchronously. They’re part of Kotlin’s coroutine framework, which helps developers replace messy callback chains with clear, sequential-looking code that’s much easier to read and maintain.</p><h3>What are Coroutine Flows?</h3><p>A coroutine flow is a cold stream, meaning it won’t start producing values until an active collector is consuming them. This behavior sets flows apart from hot streams, which begin emitting data as soon as they’re created, regardless of whether anyone is listening.</p><h3>Basic Example</h3><pre>import kotlinx.coroutines.*<br>import kotlinx.coroutines.flow.*<br><br>fun simpleFlow(): Flow&lt;Int&gt; = flow {<br>    for (i in 1..3) {<br>        delay(100) // Pretend we are doing something useful here<br>        emit(i) // Emit the next value<br>    }<br>}<br>fun main() = runBlocking {<br>    simpleFlow().collect { value -&gt; println(value) }<br>}</pre><p>In this example, we define a simple flow that emits three numbers with a delay. The collect method is used to gather the emitted values.</p><h3>Key Concepts and Operators</h3><h3>Flow Builders</h3><p>In Kotlin, Flow builders are used to create instances of Flow which is a type that represents a cold asynchronous data stream that sequentially emits values and completes normally or with an exception. Here&#39;s an overview of some commonly used flow builders along with code examples.</p><ul><li>flow { } The most basic and commonly used flow builder. This is used to emit a sequence of values:</li></ul><pre>val numberFlow = flow {<br>    for (i in 1..3) {<br>        emit(i) // Emit numbers 1 to 3<br>        delay(100) // Suspend for 100ms<br>    }<br>}</pre><ul><li>flowOf(...) Creates a flow that emits a fixed set of values. This is used to create a flow from a fixed set of values:</li></ul><pre>val fixedFlow = flowOf(1, 2, 3) // Emits 1, 2, 3</pre><ul><li>channelFlow { } Creates a flow that is conceptually a bridge to the callback-based world. This flow builder is useful when you want to emit values from different coroutine contexts. It’s more complex but offers greater flexibility:</li></ul><pre>val numberChannelFlow = channelFlow {<br>    launch {<br>        for (i in 1..3) {<br>            send(i) // Send numbers 1 to 3<br>            delay(100) // Suspend for 100ms<br>        }<br>    }<br>}</pre><ul><li>asFlow Converts various collections and sequences into a flow. This is used for integrating with existing data structures:</li></ul><pre>val list = listOf(1, 2, 3)<br>val listFlow = list.asFlow() // Converts list to flow</pre><ul><li>stateIn and sharedIn - These are not exactly flow builders but are used to convert a regular flow into a stateful flow (stateIn) or a shared flow (sharedIn):</li></ul><pre>val stateFlow = numberFlow.stateIn(coroutineScope)<br>val sharedFlow = numberFlow.sharedIn(coroutineScope)</pre><h3>Intermediate Operators</h3><p>In Kotlin flows, intermediate operators are like checkpoints that let you reshape or filter the data before it reaches the end of the pipeline. You can use them to transform values, remove unwanted items, or adjust how the stream behaves.</p><p>One important thing to know: these operators are <em>lazy</em>. That means they don’t actually run until the flow is collected. You can chain together as many as you want, and nothing happens until you finally start collecting the flow.</p><p>Here are some of the most commonly used intermediate operators, with simple examples to illustrate how they work.</p><ul><li>map - Transforms each element emitted by the flow:</li></ul><pre>flowOf(1, 2, 3)<br>    .map { it * it } // Squares each element<br>    .collect { println(it) } // Output: 1, 4, 9</pre><ul><li>filter - Emits only those elements that satisfy a given condition:</li></ul><pre>flowOf(1, 2, 3)<br>    .filter { it % 2 != 0 } // Filters out even numbers<br>    .collect { println(it) } // Output: 1, 3</pre><ul><li>take - Takes the first n elements from the flow:</li></ul><pre>flowOf(1, 2, 3, 4, 5)<br>    .take(3) // Takes only the first 3 elements<br>    .collect { println(it) } // Output: 1, 2, 3</pre><ul><li>drop - Drops the first n elements and emits the rest:</li></ul><pre>flowOf(1, 2, 3, 4, 5)<br>    .drop(2) // Drops the first 2 elements<br>    .collect { println(it) } // Output: 3, 4, 5</pre><ul><li>flatMapConcat - Transforms each element into a flow and concatenates these flows sequentially:</li></ul><pre>(1..3).asFlow()<br>    .flatMapConcat { value -&gt; <br>        flow { <br>            emit(value) <br>            emit(value + 10) <br>        } <br>    }<br>    .collect { println(it) } // Output: 1, 11, 2, 12, 3, 13</pre><ul><li>flatMapMerge - Transforms each element into a flow and merges these flows:</li></ul><pre>(1..3).asFlow()<br>    .flatMapMerge { value -&gt; <br>        flow { <br>            emit(value) <br>            delay(100) <br>            emit(value + 10) <br>        }<br>    }<br>    .collect { println(it) } // Output: 1, 2, 3, 11, 12, 13</pre><ul><li>flatMapLatest - Transforms each element into a flow and emits from the latest flow:</li></ul><pre>(1..3).asFlow()<br>    .onEach { delay(100) } // Emits 1, then 2, then 3<br>    .flatMapLatest { value -&gt; <br>        flow { <br>            emit(value)<br>            delay(200) <br>            emit(value + 10) <br>        }<br>    }<br>    .collect { println(it) } // Might only output 3, 13</pre><ul><li>buffer - Buffers emitted values:</li></ul><pre>flowOf(1, 2, 3)<br>    .buffer() // Buffer elements<br>    .collect { value -&gt;<br>        delay(100)<br>        println(value) // Output: 1, 2, 3<br>    }</pre><ul><li>conflate - Skips intermediate values if the collector is slow:</li></ul><pre>flow {<br>    for (i in 1..3) {<br>        delay(100)<br>        emit(i)<br>    }<br>}<br>.conflate() // Skip intermediate values<br>.collect { value -&gt;<br>    delay(300)<br>    println(value) // Output: 1, 3<br>}</pre><ul><li>collectLatest - Cancels the collection of the current element if a new element is emitted.</li></ul><pre>flow {<br>    for (i in 1..3) {<br>        delay(100)<br>        emit(i)<br>    }<br>}<br>.collectLatest { value -&gt;<br>    println(&quot;Collecting $value&quot;) // Output: Collecting 1, Collecting 2, Collecting 3<br>    delay(300) // Simulate work<br>    println(&quot;Done $value&quot;) // Output: Done 3<br>}</pre><h3>Terminal Operators</h3><p>In Kotlin, coroutine flows have several terminal operators which are used to collect the values emitted by the flow. These terminal operators are essential for processing the data in the flow. Here’s a brief overview of some commonly used terminal operators along with code examples.</p><ul><li>collect - Collects all values emitted by the flow and performs an action on each of them:</li></ul><pre>flowOf(1, 2, 3)<br>    .collect { value -&gt; println(value) } // Prints 1, 2, 3</pre><ul><li>toList and toSet: Converts the flow into a list or set:</li></ul><pre>val intList = flowOf(1, 2, 3).toList() // list contains [1, 2, 3]<br>val intSet = flowOf(1, 2, 2, 3).toSet() // set contains [1, 2, 3]</pre><ul><li>reduce and fold - Used for aggregating flow values. reduce requires at least one value in the flow, while fold can handle empty flows as it takes an initial value.</li></ul><pre>val sum = flowOf(1, 2, 3).reduce { accumulator, value -&gt; accumulator + value } // sum is 6<br><br>val sumWithInitial = flowOf(1, 2, 3).fold(10) { accumulator, value -&gt; accumulator + value } // sumWithInitial is 16</pre><ul><li>first and firstOrNull - Returns the first element of the flow, or null if the flow is empty (firstOrNull):</li></ul><pre>val firstValue = flowOf(1, 2, 3).first() // firstValue is 1<br>val firstOrNullValue = emptyFlow&lt;Int&gt;().firstOrNull() // firstOrNullValue is null</pre><ul><li>single and singleOrNull - Returns the single element from the flow, or throws an exception if the flow does not contain exactly one element (single). The singleOrNull variant returns null for empty flows or flows with more than one element:</li></ul><pre>val singleValue = flowOf(1).single() // singleValue is 1<br>val singleOrNullValue = flowOf(1, 2).singleOrNull() // singleOrNullValue is null</pre><ul><li>count - Counts the number of elements in the flow:</li></ul><pre>val count = flowOf(1, 2, 3).count() // count is 3</pre><ul><li>onEach - Performs an action on each element of the flow and passes the flow further downstream:</li></ul><pre>flowOf(1, 2, 3)<br>    .onEach { value -&gt; println(&quot;Received $value&quot;) }<br>    .collect() // Prints &quot;Received 1&quot;, &quot;Received 2&quot;, &quot;Received 3&quot;</pre><ul><li>launchIn - Launches the collection of the flow in a given coroutine scope without blocking the current thread:</li></ul><pre>flowOf(1, 2, 3)<br>    .onEach { value -&gt; println(value) }<br>    .launchIn(CoroutineScope(Dispatchers.Default)) // Collection happens in a background thread</pre><h3>Handling Errors</h3><p>Handling errors in coroutine flows in Kotlin is an important aspect of building robust and reliable applications. Here are some key strategies for error handling in coroutine flows, along with code examples.</p><ul><li>catch Operator - The catch operator is used to handle exceptions that occur in the upstream flow. It&#39;s similar to the catch block in a try-catch statement. If an exception is thrown, the catch block will execute:</li></ul><pre>flow {<br>    emit(1)<br>    throw RuntimeException(&quot;Something went wrong&quot;)<br>}.catch { e -&gt;<br>    emit(-1) // Emit a fallback value or handle the exception<br>}.collect {<br>    println(it) // Output: 1, -1<br>}</pre><ul><li>onCompletion Operator - The onCompletion operator is used for executing side-effects such as logging or cleanup operations. It has a nullable Throwable parameter which indicates whether the flow completed normally or exceptionally:</li></ul><pre>flow {<br>    emit(1)<br>    throw RuntimeException(&quot;Error&quot;)<br>}.onCompletion { cause -&gt;<br>    if (cause != null) println(&quot;Flow completed exceptionally&quot;)<br>}.catch { e -&gt;<br>    println(&quot;Caught exception: ${e.message}&quot;)<br>}.collect {<br>    println(it)<br>}<br>// Output: 1, Flow completed exceptionally, Caught exception: Error</pre><ul><li>retry Operator - The retry operator is used to retry the flow when an exception occurs. You can specify the number of retries and also add a condition to decide whether to retry or not based on the exception type:</li></ul><pre>flow {<br>    emit(doSomethingRisky())<br>}.retry(3) { e -&gt;<br>    e is IOException // Retry only for IOException<br>}.collect {<br>    doSomethingElse(it)<br>}</pre><ul><li>retryWhen Operator - Similar to retry, but it provides more control. You can decide whether to retry and also modify the flow based on the exception:</li></ul><pre>flow {<br>    emit(doSomethingRisky())<br>}.retryWhen { cause, attempt -&gt;<br>    delay(1000) // Wait before retrying<br>    attempt &lt; 3 &amp;&amp; cause is IOException<br>}.collect {<br>    doSomethingElse(it)<br>}</pre><ul><li>flatMapConcat and catch Combination - You can use flatMapConcat along with catch for more complex error handling scenarios where you want to switch to a different flow upon an error:</li></ul><pre>flow {<br>    emit(doSomethingRisky())<br>}.flatMapConcat { value -&gt;<br>    flowOf(value)<br>}.catch { e -&gt;<br>    emit(-1) // Fallback value<br>}.collect {<br>    doSomethingElse(it)<br>}</pre><h3>Combining Flows</h3><p>Combining multiple coroutine flows in Kotlin is a powerful feature that allows you to merge, transform, and manipulate data streams asynchronously. Here are some common ways to combine flows, along with code examples.</p><ul><li>combine Operator - This operator is used to combine the latest values of multiple flows. It emits a value every time any of the source flows emit a value:</li></ul><pre>val flow1 = flowOf(1, 2, 3)<br>val flow2 = flowOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br><br>flow1.combine(flow2) { i, s -&gt; &quot;$i$s&quot; }<br>    .collect { value -&gt; println(value) } // Output: 1a, 2a, 3a, 3b, 3c</pre><ul><li>zip Operator - This operator combines the corresponding values of two flows. It waits until both flows have emitted a value before emitting a combined value:</li></ul><pre>val numberFlow = flowOf(1, 2, 3)<br>val stringFlow = flowOf(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)<br><br>numberFlow.zip(stringFlow) { number, string -&gt; &quot;$number$string&quot; }<br>    .collect { value -&gt; println(value) } // Output: 1a, 2b, 3c</pre><ul><li>flatMapConcat - This operator is used to transform each value of a flow into another flow and then flatten these flows into a single flow:</li></ul><pre>val requestFlow = flowOf(&quot;Request1&quot;, &quot;Request2&quot;)<br><br>requestFlow.flatMapConcat { request -&gt;<br>    flow {<br>        emit(&quot;$request: Response1&quot;)<br>        delay(100) // Simulating delay<br>        emit(&quot;$request: Response2&quot;)<br>    }<br>}.collect { response -&gt; println(response) } <br>// Output: Request1: Response1, Request1: Response2, Request2: Response1, Request2: Response2</pre><ul><li>flatMapMerge - Similar to flatMapConcat, but the transformation flows are collected concurrently:</li></ul><pre>val requestFlow = flowOf(&quot;Request1&quot;, &quot;Request2&quot;)<br><br>requestFlow.flatMapMerge { request -&gt;<br>    flow {<br>        emit(&quot;$request: Response1&quot;)<br>        delay(100) // Simulating delay<br>        emit(&quot;$request: Response2&quot;)<br>    }<br>}.collect { response -&gt; println(response) }<br>// Output: Request1: Response1, Request2: Response1, Request1: Response2, Request2: Response2</pre><ul><li>flatMapLatest - When a new value is emitted by the source flow, the current transformation flow is cancelled, and a new transformation flow is started for the new value:</li></ul><pre>val requestFlow = flowOf(&quot;Request1&quot;, &quot;Request2&quot;)<br><br>requestFlow.flatMapLatest { request -&gt;<br>    flow {<br>        emit(&quot;$request: Processing&quot;)<br>        delay(100) // Simulating processing delay<br>        emit(&quot;$request: Complete&quot;)<br>    }<br>}.collect { response -&gt; println(response) }<br>// Output: Request1: Processing, Request2: Processing, Request2: Complete</pre><h3>Conclusion</h3><p>Coroutine flows are an essential part of modern Kotlin development, especially when dealing with asynchronous streams of data. By understanding and utilizing the various operators and concepts, developers can write more readable and efficient asynchronous code.</p><p>This article provides a comprehensive overview of coroutine flows, but remember, there’s always more to explore and learn in Kotlin’s continually evolving landscape.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383d55a4857a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JWT with Nimbus JOSE library]]></title>
            <link>https://medium.com/@michael.avoyan/mastering-jwt-with-nimbus-jose-library-981b98747e36?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/981b98747e36</guid>
            <category><![CDATA[jose]]></category>
            <category><![CDATA[elliptic-curve]]></category>
            <category><![CDATA[nimbus]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[ecdsa]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 23:51:38 GMT</pubDate>
            <atom:updated>2026-10-20T15:27:33.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnRiZsTZ9RBNTj9BXI_F3w.png" /></figure><h3><strong>Mastering JWT with the Nimbus JOSE Library</strong></h3><p>JSON Web Tokens (JWT) have become a standard way of handling authentication and authorization in modern applications. In this article, we’ll take a closer look at JWTs and explore how the Nimbus JOSE + JWT library (com.nimbusds:nimbus-jose-jwt) makes working with them easier in Java and Kotlin projects. For demonstration, we’ll use Kotlin examples, but the concepts apply equally well to Java.</p><h3>What is JWT?</h3><p>A JSON Web Token (JWT) is a lightweight, URL-safe way of representing information (called claims) that can be securely transmitted between two parties. JWTs are most commonly used in web development for tasks like authentication and secure data exchange, especially in REST APIs and modern web applications.</p><p>At its core, a JWT has a few key characteristics worth understanding:</p><h3>Structure of JWT</h3><p>A JWT consists of three parts, each separated by a dot (.):</p><h4><strong>Header:</strong></h4><p>The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.</p><pre>// The JWT header example:<br>{<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;alg&quot;: &quot;ES256K&quot;,<br>  &quot;jwk&quot;: {<br>    &quot;kty&quot;: &quot;EC&quot;,<br>    &quot;use&quot;: &quot;sig&quot;,<br>    &quot;crv&quot;: &quot;secp256k1&quot;,<br>    &quot;kid&quot;: &quot;de08767b-2a96-47c4-a3dc-6436ed81b443&quot;,<br>    &quot;x&quot;: &quot;EsC1PCwICiR3Uzh86uzo9jFpILU-uaDuCcY09mQ8kqE&quot;,<br>    &quot;y&quot;: &quot;5Dr1uQOerNksufJJaJ-HfV_ZB2LQfy5En4BcWXK3RaA&quot;<br>  }<br>}</pre><h4><strong>Payload:</strong></h4><p>The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.</p><ul><li><em>Registered claims:</em> These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.</li><li><em>Public claims:</em> These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision-resistant namespace.</li><li><em>Private claims:</em> These are the custom claims created to share information between parties that agree on using them and are neither registered nor public claims.</li></ul><pre>// The JWT pyload example:<br>{<br>  &quot;sub&quot;: &quot;some subject&quot;,<br>  &quot;aud&quot;: &quot;some audience&quot;,<br>  &quot;p1&quot;: &quot;something 1&quot;,<br>  &quot;p2&quot;: &quot;something 2&quot;,<br>  &quot;nbf&quot;: 1701477857,<br>  &quot;iss&quot;: &quot;https://yourdomain.com&quot;,<br>  &quot;exp&quot;: 1702082657,<br>  &quot;iat&quot;: 1701477857,<br>  &quot;jti&quot;: &quot;some id&quot;<br>}</pre><h4><strong>Signature:</strong></h4><p>To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. The signature is used to verify the message wasn’t changed along the way, and in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.</p><pre>// The JWT signature example:<br>M4_DproZ5wA9BRJa5m_oDlmuj_mAq3kTrEs0dAts2DauChJYPt4wyZJaQujARXsUfaHLAIkRp9DQJMHGf1R_nw</pre><pre>// The whole JWT example:<br>eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksiLCJqd2siOnsia3R5IjoiRUMiLCJ1c2UiOiJzaWciLCJjcnYiOiJzZWNwMjU2azEiLCJraWQiOiJkZTA4NzY3Yi0yYTk2LTQ3YzQtYTNkYy02NDM2ZWQ4MWI0NDMiLCJ4IjoiRXNDMVBDd0lDaVIzVXpoODZ1em85akZwSUxVLXVhRHVDY1kwOW1ROGtxRSIsInkiOiI1RHIxdVFPZXJOa3N1ZkpKYUotSGZWX1pCMkxRZnk1RW40QmNXWEszUmFBIn19.eyJzdWIiOiJzb21lIHN1YmplY3QiLCJhdWQiOiJzb21lIGF1ZGllbmNlIiwicDEiOiJzb21ldGhpbmcgMSIsInAyIjoic29tZXRoaW5nIDIiLCJuYmYiOjE3MDE0Nzc4NTcsImlzcyI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJleHAiOjE3MDIwODI2NTcsImlhdCI6MTcwMTQ3Nzg1NywianRpIjoic29tZSBpZCJ9.M4_DproZ5wA9BRJa5m_oDlmuj_mAq3kTrEs0dAts2DauChJYPt4wyZJaQujARXsUfaHLAIkRp9DQJMHGf1R_nw</pre><h3>How JWT works</h3><ul><li><em>Authentication:</em> After the user signs in using their credentials, a JWT will be returned. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.</li><li><em>Information Exchange:</em> JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed for example, using public/private key pairs , you can be sure the senders are who they say they are and the content hasn’t been tampered with.</li></ul><p>JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. They are less verbose than XML-based standards like SAML, making JWT more suitable for usage in scenarios where bandwidth is a concern.</p><h3><strong>Setting up Nimbus JOSE + JWT</strong></h3><p>Importing Nimbus JOSE + JWT library to a Java/Kotlin project using Maven or Gradle.</p><p>Maven:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.nimbusds&lt;/groupId&gt;<br>    &lt;artifactId&gt;nimbus-jose-jwt&lt;/artifactId&gt;<br>    &lt;version&gt;[version]&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Gradle:</p><pre>implementation &#39;com.nimbusds:nimbus-jose-jwt:[version]&#39;</pre><h3>Generating a secret</h3><pre>import com.nimbusds.jose.jwk.Curve<br>import com.nimbusds.jose.jwk.ECKey<br>import com.nimbusds.jose.jwk.KeyUse<br>import com.nimbusds.jose.jwk.gen.ECKeyGenerator<br><br>fun generateSecret(): ECKey {<br>    val ecKey = ECKeyGenerator(Curve.SECP256K1)<br>        .keyUse(KeyUse.SIGNATURE)<br>        .keyID(UUID.randomUUID().toString())<br>        .generate()<br>    return ecKey<br>}</pre><h3>Generating a signed JWT</h3><p>Create a JWT, including setting claims and signing the token:</p><pre>import com.nimbusds.jose.jwk.Curve<br>import com.nimbusds.jose.jwk.ECKey<br>import com.nimbusds.jose.jwk.KeyUse<br>import com.nimbusds.jose.jwk.gen.ECKeyGenerator<br><br>// Generating a Secret<br>val ecKey = generateSecret()<br><br>// Generating a Signed JWT<br>val headerBuilder = JWSHeader.Builder(JWSAlgorithm.ES256K)<br>    .type(JOSEObjectType(&quot;JWT&quot;))<br>    .jwk(ecKey.toPublicJWK()) // public key<br><br>val curDate = Date()<br>val claimsSetBuilder = JWTClaimsSet.Builder()<br>    .subject(&quot;some subject&quot;)<br>    .audience(&quot;some audience&quot;)<br>    .issuer(&quot;https://yourdomain.com&quot;)<br>    .jwtID(&quot;some id&quot;) // jti<br>    .issueTime(curDate) // iat<br>    .notBeforeTime(curDate) // nbf<br>    .expirationTime(curDate.addDays(7)) // exp  <br>    .claim(&quot;p1&quot;, &quot;something 1&quot;)<br>    .claim(&quot;p2&quot;, &quot;something 2&quot;)  <br><br>val signedJWT = SignedJWT(<br>    headerBuilder.build(),<br>    claimsSetBuilder.build()<br>)<br>signedJWT.sign(ECDSASigner(ecKey))</pre><h3>Generating a stringified JWT</h3><pre>// Get a stringified JWT<br>val jwtString: String = signedJWT.serialize()</pre><h3>Parsing and validating a JWT</h3><p>Demonstrate how to parse a JWT string and validate its signature and data.</p><pre>import com.nimbusds.jose.crypto.ECDSAVerifier<br>import com.nimbusds.jose.jwk.ECKey<br>import com.nimbusds.jose.jwk.JWK<br>import com.nimbusds.jwt.JWTClaimsSet<br><br>val verifier = ECDSAVerifier(ECKey.parse(&quot;your-public-key&quot;))<br>if (signedJwt.verify(verifier)) {<br>    // Process the claims...<br>    val claims: JWTClaimsSet? = signedJwt?.jwtClaimsSet<br>}</pre><h3>Supported algorithms by Nimbus JOSE + JWT</h3><p>The Nimbus JOSE + JWT library offers extensive support for various cryptographic algorithms. Understanding these algorithms is crucial for implementing secure token-based authentication and encryption in your applications. Below, we explore the key algorithms supported by the library.</p><h3>JWS (JSON Web Signature) Algorithms</h3><p>JWS algorithms are used for signing JWTs to ensure their integrity and authenticity. Nimbus supports a range of JWS algorithms:</p><ul><li>HS256, HS384, HS512: HMAC using SHA-256, SHA-384, and SHA-512. These are symmetric algorithms, meaning the same key is used for both signing and verification.</li></ul><pre>// Use JWSAlgorithm.HS256 for HS256<br>val signer: JWSSigner = MACSigner(&quot;your-secret&quot;)</pre><ul><li>ES256, ES384, ES512: ECDSA using P-256, P-384, and P-521 curves. These are asymmetric algorithms using Elliptic Curve keys.</li></ul><pre>// Use JWSAlgorithm.ES256 for ES256<br>val signer: JWSSigner = ECDSASigner(privateECKey)</pre><ul><li>RS256, RS384, RS512: RSASSA-PKCS1-v1_5 using SHA-256, SHA-384, and SHA-512. These are asymmetric algorithms using RSA keys.</li></ul><pre>// Use JWSAlgorithm.RS256 for RS256<br>val signer: JWSSigner = RSASSASigner(privateKey)</pre><ul><li>PS256, PS384, PS512: RSASSA-PSS using SHA-256, SHA-384, and SHA-512. Variants of RSA signatures with additional security properties.</li></ul><h3>JWE (JSON Web Encryption) Algorithms</h3><p>For encrypting JWTs, the Nimbus library supports several JWE algorithms:</p><ul><li>RSA-OAEP, RSA-OAEP-256: RSAES OAEP using SHA-1 and SHA-256. These are used for key encryption with RSA keys.</li><li>A128KW, A192KW, A256KW: AES Key Wrap with default initialization vector.</li><li>dir: Direct use of a shared symmetric key.</li><li>ECDH-ES: Elliptic Curve Diffie-Hellman Ephemeral Static key agreement using Concat KDF.</li><li>A128GCM, A192GCM, A256GCM: AES GCM using 128, 192, and 256-bit keys for content encryption.</li></ul><h3>JWT debugger</h3><p><a href="https://jwt.io/"><strong>JWT.IO</strong></a> allows you to decode, verify and generate JWT.</p><h3>Conclusion</h3><p>The Nimbus JOSE + JWT library is a powerful tool for Java and Kotlin developers working with JSON Web Tokens. In this article, we walked through setting up the library, creating and validating tokens, and applying different cryptographic algorithms, giving you a practical foundation for building secure, token-based authentication and data exchange.</p><p>What makes Nimbus stand out is its full support for both JSON Web Signatures (JWS) and JSON Web Encryption (JWE), along with a wide range of cryptographic algorithms. This flexibility allows it to adapt to many different security requirements.</p><p>That said, while the library simplifies JWT handling, security is never “set-and-forget.” Staying current with best practices and library updates is essential.</p><p>Overall, Nimbus strikes a strong balance between ease of use and robust security, making it an excellent choice for integrating JWTs into your Java or Kotlin applications. Hopefully, this guide helps you take the first steps toward building more secure and efficient systems.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=981b98747e36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making the First Steps in Learning Kotlin Coroutines]]></title>
            <link>https://medium.com/@michael.avoyan/making-the-first-steps-in-learning-kotlin-coroutines-653d89034ff8?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/653d89034ff8</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 20:53:03 GMT</pubDate>
            <atom:updated>2026-10-20T15:27:50.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2fc4u2gGvGA2ewBE0nkwg.png" /></figure><p>Coroutines have reshaped how Kotlin handles asynchronous work. If you are new to them, they might look intimidating at first, but a simple step-by-step path makes everything click. This guide introduces the core concepts behind Kotlin coroutines and provides practical examples that you can use right away.</p><h3>What Are Coroutines?</h3><p>Coroutines are a Kotlin feature designed to simplify asynchronous programming. They let you write code that looks and feels sequential, while still running efficiently in the background. Instead of juggling callbacks or dealing with complicated thread management, coroutines give you a cleaner, more readable way to handle tasks that happen asynchronously.</p><h3>Core Concepts</h3><ul><li><strong>Suspension:</strong> A coroutine can pause its work without blocking the thread it runs on. This makes room for other tasks to continue, improving efficiency.</li><li><strong>Lightweight:</strong> Unlike traditional threads, coroutines use far fewer resources. This means you can run thousands of them at the same time without overwhelming the system.</li></ul><h3>Setting Up</h3><p>To use coroutines in a Kotlin project, you need to add the coroutine library to your build.gradle file:</p><pre>dependencies {<br>    implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0&quot;<br>}</pre><h3>Basic Coroutine Example</h3><p>Let’s start with a basic example. Suppose you want to perform a network request, which is a common asynchronous operation:</p><pre>import kotlinx.coroutines.*<br><br>fun main() {<br>    GlobalScope.launch { // Launch a coroutine in the background<br>        val data = fetchData()<br>        println(data)<br>    }<br>    Thread.sleep(2000) // Wait for coroutine to finish<br>}<br><br>suspend fun fetchData(): String {<br>    delay(1000) // Simulate a long-running task<br>    return &quot;Data fetched&quot;<br>}</pre><p>In this example, fetchData is a suspend function, which can be paused and resumed, with delay simulating a task.</p><h3>Structured Concurrency with Coroutine Builders</h3><p>Using GlobalScope is not recommended for real-world applications as it can lead to resource leaks. Instead, use structured concurrency:</p><pre>fun main() = runBlocking { // Creates a new coroutine scope<br>    launch { // Launch a new coroutine in the scope<br>        val data = fetchData()<br>        println(data)<br>    }<br>}</pre><p>runBlocking creates a coroutine scope and doesn’t complete until all coroutines within it are finished.</p><h3>Coroutine Builders: launch vs async</h3><p><strong>launch</strong>: It starts a new coroutine without blocking the current thread and returns a Job. The launch builder is used for fire-and-forget coroutines, where you don&#39;t need the result of the operation.</p><pre>val job = launch {<br>    // Coroutine code here<br>}</pre><p><strong>async:</strong> It starts a coroutine that computes a result and returns a Deferred object, which is a non-blocking future. Use async when you need to compute a result that will be used later.</p><pre>val deferred = async {<br>    // Compute a result<br>}<br>val result = deferred.await() // Wait for the result</pre><h3>Example with async</h3><pre>fun main() = runBlocking {<br>    val deferredData = async { fetchData() }<br>    println(&quot;Waiting for data...&quot;)<br>    println(&quot;Received: ${deferredData.await()}&quot;)<br>}<br><br>suspend fun fetchData(): String {<br>    delay(1000)<br>    return &quot;Async Data&quot;<br>}</pre><h3>Handling Exceptions</h3><p>Exception handling in coroutines can be done using try/catch blocks.</p><pre>fun main() = runBlocking {<br>    val job = launch {<br>        try {<br>            fetchData()<br>        } catch (e: Exception) {<br>            println(&quot;Error: ${e.message}&quot;)<br>        }<br>    }<br>    job.join()<br>}<br><br>suspend fun fetchData() {<br>    delay(500)<br>    throw Exception(&quot;Error occurred&quot;)<br>}</pre><h3>Conclusion</h3><p>Getting comfortable with Kotlin coroutines and builders, like launchand async, is an essential step in modern Kotlin development. They’re the key to building apps that stay responsive while handling work in the background. This guide has given you a foundation to start with, and from here you can dive into coroutine contexts, structured concurrency, and more advanced patterns.</p><p>Coroutines cover a wide range of possibilities, and mastering them takes both time and practice. But with these basics in place, you’re already on the right path to making the most of one of Kotlin’s most powerful features.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653d89034ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Most Popular Architectures In Mobile Applications Development]]></title>
            <link>https://medium.com/@michael.avoyan/the-most-popular-architectures-in-mobile-applications-development-e35e6b8b5c6a?source=rss-7c4072671c12------2</link>
            <guid isPermaLink="false">https://medium.com/p/e35e6b8b5c6a</guid>
            <category><![CDATA[viper-architecture]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[mvi-architecture]]></category>
            <category><![CDATA[mvc-architecture]]></category>
            <dc:creator><![CDATA[Michael Avoyan]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 19:39:36 GMT</pubDate>
            <atom:updated>2026-10-20T15:28:05.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/443/0*0U9N7BChP4BLFwf7" /></figure><p>When building a mobile app, one of the first big decisions is choosing the right architecture. There isn’t a single “best” approach that fits every project — the right choice depends on your team’s experience, the complexity of the app, and long-term goals like scalability and maintainability. In this article, I’ll walk through some of the most widely used architectural patterns in mobile development and highlight when each one makes sense.</p><p><strong>Model-View-Controller (MVC)</strong></p><p>MVC is one of the oldest and most widely recognized architectural patterns in software development. The idea is simple: split your app into three interconnected parts so that each one has a clear responsibility. This separation makes the codebase easier to maintain and less tangled over time.</p><ul><li><strong>Model:</strong> Handles the data and business logic — storing, fetching, and transforming information. It’s also responsible for notifying the other layers when something changes.</li><li><strong>View:</strong> Takes care of the user interface. Its job is to display information to the user and pass along any interactions (like taps or input) to the controller.</li><li><strong>Controller:</strong> Acts as the bridge between the view and the model. It processes user input, updates the model, and makes sure the view reflects the latest state.</li></ul><p><strong>Pros:</strong></p><ul><li><em>Clear separation of concerns:</em> Data, UI, and control logic live in their own places.</li><li><em>Reusable pieces: </em>Logic or UI components can often be reused in other projects.</li><li><em>Scales fairly well:</em> The modular design makes it easier to grow the app as requirements expand.</li><li><em>Flexible:</em> Because the components are loosely coupled, swapping one out doesn’t necessarily break the others.</li><li><em>Test-friendly:</em> Each piece can be tested in isolation, reducing the risk of unintended side effects.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Extra complexity:</em> Splitting everything out requires more boilerplate code.</li><li><em>“Massive View Controller” problem:</em> In practice, controllers often end up overloaded with responsibilities.</li><li><em>Not always worth it:</em> For small or simple apps, MVC can feel like overkill.</li><li><em>Performance overhead:</em> Communication between layers can slow things down if done poorly.</li><li><em>Harder debugging:</em> Multiple layers of abstraction sometimes make tracking down a bug trickier.</li></ul><p><strong>Model-View-Presenter (MVP)</strong></p><p>MVP is a close relative of MVC, but with a slightly different twist that gives developers a cleaner separation of responsibilities. Instead of one controller juggling multiple views, each view gets its own Presenter, which makes the structure easier to test and maintain.</p><ul><li><strong>Model:</strong> Contains the app’s data and business logic. It talks to the database or network and knows nothing about how the information will be displayed.</li><li><strong>View:</strong> Handles only the user interface. It shows data on the screen but avoids embedding business logic. Whenever the user interacts with the UI, the view passes those events to the presenter.</li><li><strong>Presenter:</strong> Acts as the middleman. It listens to user actions from the view, pulls or updates data through the model, and then updates the view accordingly. The presenter is where most of the decision-making and business logic lives.</li></ul><p><strong>Pros:</strong></p><ul><li><em>Clear separation of concerns:</em> Each piece has its own role, which makes the code easier to read, modify, and test.</li><li><em>Reusability:</em> Well-defined boundaries make it easier to pull out logic or UI components and reuse them elsewhere.</li><li><em>Scales nicely:</em> Adding new features usually means creating new presenters or views, without disturbing existing ones.</li><li><em>Modular collaboration: </em>Since components are decoupled, multiple developers can work on different parts of the app in parallel.</li><li><em>Maintainability:</em> The structure encourages cleaner, more maintainable code over time.</li><li><em>Test-friendly:</em> Business logic is concentrated in the presenter, which can be tested independently of the UI.</li></ul><p><strong>Cons:</strong></p><ul><li><em>More moving parts:</em> MVP introduces extra layers, which can feel overwhelming for beginners.</li><li><em>Slower setup:</em> Designing presenters for each view takes more upfront work compared to simpler patterns.</li><li><em>Overkill for small apps:</em> For lightweight projects, the added structure can become unnecessary overhead.</li><li><em>Learning curve:</em> Developers who haven’t used MVP before may need extra time to adapt.</li><li><em>Risk of duplication: </em>If not carefully designed, similar logic might end up repeated across different presenters.</li></ul><p><strong>Model–View–ViewModel (MVVM)</strong></p><p>MVVM takes ideas from MVC and MVP but adds a dedicated middle layer called the ViewModel. The goal is to make testing and maintenance simpler by keeping each piece as independent as possible. This pattern is especially popular in mobile development — in fact, Google strongly recommends it for Android apps.</p><ul><li><strong>Model:</strong> Manages the app’s data and business rules. It handles storing, fetching, and transforming information, and notifies other layers when the data changes.</li><li><strong>View:</strong> The user interface. It displays information on the screen and captures user actions, which are then handed off to the ViewModel.</li><li><strong>ViewModel: </strong>Sits between the View and the Model. It exposes data in a way that’s easy for the UI to consume, applies validation or transformations, and updates the Model when needed. It also ensures the View stays in sync with the latest state.</li></ul><p><strong>Pros:</strong></p><ul><li><em>Clear separation of concerns:</em> Data, UI, and logic live in different places, making the codebase easier to navigate and maintain.</li><li><em>Reusable components:</em> The modular structure makes it easier to reuse parts of the code across projects.</li><li><em>Scales well:</em> As the app grows, you can add new features without rewriting existing ones.</li><li><em>Loose coupling:</em> Because the pieces don’t depend heavily on each other, swapping or updating a component is less risky.</li><li><em>Data binding: </em>A key strength of MVVM is automatic data binding, which keeps the UI in sync with the underlying state with less boilerplate code.</li><li><em>Test-friendly:</em> With business logic living in the ViewModel, you can test it independently from the UI.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Added complexity:</em> Splitting the app into more layers introduces extra code and structure.</li><li><em>Steeper learning curve:</em> Developers new to MVVM often need time to get comfortable with data binding and ViewModel patterns.</li><li><em>Overkill for small apps:</em> For lightweight projects, MVVM may add unnecessary overhead.</li><li><em>Potential performance costs:</em> Frequent communication between layers can slow things down if not handled carefully.</li><li><em>Trickier debugging:</em> Multiple layers and binding mechanisms can sometimes obscure where issues are coming from.</li></ul><p><strong>MVI (Model-View-Intent)</strong></p><p>MVI is a pattern designed with reactive programming in mind, often used when building functional, event-driven user interfaces. At first glance, it appears similar to MVVM, but its key distinction lies in the emphasis on user intentions and unidirectional data flow. In other words, information always moves in a single direction: from the user’s intent → through the application logic → into the model → and finally back to the view. This predictable flow makes state management easier and helps reduce tricky bugs.</p><ul><li><strong>Model: </strong>Represents the state of the UI at any given time. It contains all the information needed to render the screen.</li><li><strong>View: </strong>Renders the user interface purely from the current state of the model. It doesn’t hold logic, its only job is to display data.</li><li><strong>Intent: </strong>Captures the user’s actions (like taps or inputs) and passes them into the system. The application logic processes these intents, updates the model, and triggers a new UI render.</li></ul><p><strong>Pros:</strong></p><ul><li><em>Clear separation of concerns:</em> UI logic and business logic live in different layers, which keeps complexity under control.</li><li><em>Predictable data flow:</em> Because everything moves in a single direction, it’s much easier to reason about how state changes over time.</li><li><em>Good for scaling:</em> The modular design makes it simpler to add new features or extend existing ones without breaking the app.</li><li><em>Test-friendly:</em> Since business logic is isolated and state changes are deterministic, writing unit tests becomes more straightforward.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Steeper learning curve:</em> MVI can feel unintuitive at first, especially for developers used to more traditional patterns.</li><li><em>Not always necessary:</em> For smaller, simpler apps, MVI may add unnecessary overhead compared to lighter patterns.</li><li><em>Lots of boilerplate:</em> Implementing intents, models, and view updates often means writing more setup code.</li><li><em>Debugging hurdles:</em> With many moving parts, tracking down where an issue starts can sometimes be frustrating.</li></ul><p><strong>Clean Architecture</strong></p><p>Clean Architecture, introduced by Robert C. Martin (better known as Uncle Bob), is all about keeping the core of your application independent from frameworks, databases, or UI layers. The focus is on business logic first, so the app can evolve over time without being tightly bound to specific technologies.</p><p>At its heart, Clean Architecture organizes an app into layers with strict rules about how they communicate. Dependencies always point inward, toward the core, never outward. That way, the most important part of your app, the business logic, is insulated from external changes like switching a database or updating a UI framework.</p><p>The layers are usually described as concentric circles:</p><ul><li><strong>Entities:</strong> The innermost layer. These are the core business objects or models, completely independent of any frameworks or libraries.</li><li><strong>Use Cases:</strong> Define the application-specific business rules. They describe what the system does and how entities should be manipulated. Use cases depend only on entities.</li><li><strong>Interface Adapters:</strong> Translate data between the use cases/entities and the outside world. This includes presenters, controllers, or view models that adapt the data for the UI.</li><li><strong>Frameworks and Drivers:</strong> The outermost layer. This includes the tools and technologies your app uses (databases, APIs, web servers, UI frameworks). These depend on the inner layers, but the inner layers know nothing about them.</li></ul><p>This layered approach makes the system easier to maintain, more testable, and more adaptable as technology inevitably changes.</p><p><strong>Pros:</strong></p><ul><li><em>Strong separation of concerns:</em> Each layer has a clear responsibility, which keeps the codebase easier to understand and maintain over time.</li><li><em>Scales with complexity:</em> The modular design helps projects grow without turning into an unmanageable mess.</li><li><em>Framework independence:</em> Business logic doesn’t depend on UI frameworks, databases, or platforms, making it easier to swap technologies when needed.</li><li><em>Flexible design: </em>You can change the UI or an external dependency without touching the core rules of the app.</li><li><em>Test-friendly: </em>Because business logic is isolated, you can test it on its own without heavy mocking or complicated test setups.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Extra complexity:</em> More layers mean more moving parts, which can feel heavy compared to simpler architectures.</li><li><em>Steep learning curve:</em> Developers unfamiliar with the pattern may need extra time to understand and apply it properly.</li><li><em>Risk of over-engineering: </em>For smaller apps, Clean Architecture can add unnecessary structure and slow things down.</li><li><em>Possible performance costs:</em> Multiple layers of communication can introduce overhead.</li><li><em>Higher development cost:</em> Building and maintaining this structure requires more time and resources, which can be a real concern for small teams or startups.</li></ul><p><strong>Flux</strong></p><p>Flux is an architecture introduced by Facebook to handle the challenges of building large, interactive UIs, especially ones with lots of data and frequent state changes. Its key idea is unidirectional data flow, which means information always moves in a single direction through the system. This makes it easier to reason about how data changes, reduces unexpected side effects, and helps keep apps predictable even as they grow in complexity.</p><p>In a Flux app, the pieces work together like this:</p><p><strong>Actions: </strong>Plain objects that describe something that happened (for example, “button clicked” or “item added to cart”).</p><p><strong>Dispatcher: </strong>A central hub that receives actions and passes them along to the right places.</p><p><strong>Stores: </strong>Hold the application’s state and business logic. When they receive an action, they update their state and notify whoever is listening.</p><p><strong>Views: </strong>The UI components. They listen to stores for updates and re-render when the data changes. Views can also trigger new actions when users interact with them.</p><p>Because the flow is strictly one-way action → dispatcher → store → view, debugging tends to be simpler, and performance can improve since you avoid unnecessary re-renders.</p><p>That said, Flux also comes with trade-offs: it introduces extra boilerplate, can feel more complex than other patterns, and isn’t always easy to retrofit into an app that started with a different architecture.</p><p><strong>Pros:</strong></p><ul><li><em>Predictable data flow: </em>With everything moving in one direction, it’s much easier to understand how state changes and to track down issues.</li><li><em>Clear separation of concerns: </em>Actions, stores, views, and the dispatcher each have distinct roles, which keeps the system organized.</li><li><em>Better performance:</em> By reducing unnecessary re-renders, Flux can help large, data-heavy UIs feel more responsive.</li><li><em>Test-friendly:</em> Since each part of the architecture is isolated, writing unit tests for them becomes more straightforward.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Added complexity:</em> Introducing a dispatcher and multiple stores can feel heavy compared to simpler patterns.</li><li><em>Lots of boilerplate:</em> Flux often requires writing repetitive code to wire everything together.</li><li><em>Different mental model:</em> Developers new to unidirectional data flow may need time to adjust to this way of thinking.</li><li><em>Not always worth it:</em> For smaller or less dynamic apps, the extra structure can feel like overkill.</li></ul><p><strong>VIPER (View-Interactor-Presenter-Entity-Router)</strong></p><p>VIPER is an architecture that came out of Mutual Mobile in 2013 and has since gained traction for building modular and highly maintainable apps. Its main strength lies in breaking an application into very specific roles, which makes the codebase more organized and easier to test. Because responsibilities are so well-defined, teams can collaborate more effectively, and new features can be added without disturbing existing ones.</p><p>Here’s how the pieces fit together:</p><ul><li><strong>View:</strong> Handles the UI and user input. In VIPER, the view is “dumb” — it doesn’t include any business logic.</li><li><strong>Interactor: </strong>Contains the business logic and works with the data layer to fetch or update information.</li><li><strong>Presenter: </strong>Manages presentation logic. It takes raw data from the interactor, prepares it for display, and updates the view.</li><li><strong>Entity: </strong>Represents the data models the app works with.</li><li><strong>Router:</strong> Takes care of navigation, deciding which screen to display based on input or state.</li></ul><p>By splitting responsibilities into these five distinct layers, VIPER creates a structure that’s both testable and scalable, making it especially appealing for larger projects with long-term maintenance in mind.</p><p><strong>Pros:</strong></p><ul><li><em>Strong separation of concerns:</em> Each layer has a clear role, which makes the overall structure easier to follow and maintain.</li><li><em>Scales well: </em>Adding new features often just means creating a new module without touching the rest of the app.</li><li><em>Highly modular: </em>Because everything is split into distinct parts, multiple developers can work on different areas in parallel.</li><li><em>Easier long-term maintenance: </em>The modular design helps prevent code from becoming tangled as the app grows.</li><li><em>Test-friendly: </em>With logic isolated into the interactor and presenter, writing unit tests becomes more straightforward.</li></ul><p><strong>Cons:</strong></p><ul><li><em>High complexity:</em> VIPER introduces a lot of layers, which can be intimidating for developers new to the pattern.</li><li><em>Slower development upfront:</em> Planning and wiring all the pieces together takes more time than simpler architectures.</li><li><em>Overkill for small apps:</em> If the project is lightweight, VIPER can add unnecessary structure and slow things down.</li><li><em>Learning curve:</em> New team members unfamiliar with VIPER may need extra onboarding time before they can contribute effectively.</li></ul><p><strong>Reactive Programming</strong></p><p>Reactive Programming isn’t a traditional architectural pattern like MVC, MVP, or MVVM — it’s more of a programming paradigm that shapes how apps handle data and events. The main idea is to treat data as a stream that can be observed, transformed, and combined over time. This approach makes apps more responsive, resilient, and scalable, especially when dealing with real-time scenarios like chat apps, social feeds, or multiplayer games.</p><p>At its core, Reactive Programming is about asynchronous data streams. Instead of waiting for events one by one, the app reacts to changes as they happen. Libraries such as Reactive Extensions (Rx) provide powerful operators that let developers filter, merge, or transform these streams declaratively.</p><p>Some key features include:</p><ul><li><strong>Asynchronous and event-driven: </strong>Built to handle data that arrives over time, making apps more responsive.</li><li><strong>Declarative style: </strong>Developers describe what should happen when data changes, rather than writing imperative step by step logic.</li><li><strong>Composable streams: </strong>Data can be combined, filtered, and transformed easily, leading to flexible designs.</li><li><strong>Backpressure handling: </strong>Deals with situations where the producer sends data faster than the consumer can process.</li><li><strong>Hot vs. cold observables:</strong> Hot observables emit values whether or not there are subscribers, while cold observables only start emitting once someone is listening.</li></ul><p>By shifting the mindset to thinking in streams, Reactive Programming helps reduce complexity in real-time applications, though it does require a different way of thinking compared to traditional patterns.</p><p><strong>Pros:</strong></p><ul><li><em>Highly scalable:</em> Built to handle large volumes of data and users without the app falling behind.</li><li><em>Great responsiveness:</em> Ideal for real-time apps where users expect instant updates and feedback.</li></ul><p><strong>Cons:</strong></p><ul><li><em>Steep learning curve: </em>Thinking in terms of streams and operators is very different from traditional programming, so it takes time to master.</li><li><em>Harder debugging: </em>Tracing issues through chains of streams can be tricky, especially in complex apps.</li><li><em>Added complexity:</em> The code can become harder to follow if the reactive style isn’t used carefully.</li><li><em>Performance overhead:</em> Some reactive libraries introduce extra cost at runtime, which can impact performance with very large datasets or heavy workloads.</li></ul><p><strong>Conclusion</strong></p><p>There’s no single “best” architecture for mobile development. MVC, MVP, MVVM, MVI, Clean Architecture, Flux, VIPER, and Reactive Programming all have their place, each with its own strengths and trade-offs. The right choice depends on the project’s specific needs.</p><p>When deciding, think about factors like the size and complexity of your app, the experience of your team, and how much emphasis you want to place on scalability, testability, or speed of development. A small prototype might benefit from a lightweight approach, while a long-term product with complex requirements may demand a more structured architecture.</p><p>In the end, the goal isn’t just to follow a pattern for its own sake, it’s to pick an approach that makes your app easier to build, maintain, and evolve over time.</p><p>If you found this article helpful, please consider <strong>clapping</strong>👏 and <strong>following</strong> me on <a href="https://www.linkedin.com/in/michael-avoyan/"><strong>LinkedIn</strong></a> &amp; <a href="https://github.com/michaelavoyan"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e35e6b8b5c6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>