<?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 Finn Christoffer Kurniawan on Medium]]></title>
        <description><![CDATA[Stories by Finn Christoffer Kurniawan on Medium]]></description>
        <link>https://medium.com/@dev.finnchristoffer?source=rss-4ef6aec12fbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ht2U8sVmYwEYoTkKj-eX2w.jpeg</url>
            <title>Stories by Finn Christoffer Kurniawan on Medium</title>
            <link>https://medium.com/@dev.finnchristoffer?source=rss-4ef6aec12fbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:52:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev.finnchristoffer/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[AI Didn’t 10x Engineering. It Exposed Who Was Already 10x.]]></title>
            <link>https://medium.com/@dev.finnchristoffer/ai-didnt-10x-engineering-it-exposed-who-was-already-10x-039e36f8f773?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/039e36f8f773</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 06:51:33 GMT</pubDate>
            <atom:updated>2026-06-12T06:51:33.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*yWOH5FIZzL4oyYQO.jpeg" /><figcaption>from Google Image</figcaption></figure><p><strong>The AI conversation in 2026 is being held by people who don’t write code.</strong></p><p>Founders posting carousels about 10x productivity. Executives announcing “AI-first” mandates from three reorgs away from the codebase. Newsletter writers who used Cursor for a weekend and now have a thesis. VCs whose fund depends on the answer being <em>transformative</em> or <em>overhyped</em> — because the middle doesn’t make a headline.</p><p>The engineers shipping with AI every day are mostly quiet. Some because we’re busy. Most because both extremes — <em>AI will replace us all</em> and <em>AI is just a tool</em> — are embarrassing to engage with. We’ve watched these takes recycle for three years.</p><p>I’m done being quiet.</p><h3>Two takes, both wrong</h3><p>The first is the replacement take: <em>AI will replace engineers.</em> Same voices who said it about offshoring in 2005 and no-code in 2017. It’s wrong in a specific way — <strong>it confuses the commoditization of typing with the commoditization of thinking.</strong> AI can generate code. It cannot decide whether the code should exist.</p><p>The second is worse because it sounds reasonable: <em>AI is just a tool, use it well.</em> The humble-sounding refusal. Hammers don’t restructure which skills the market pays for. <strong>AI did.</strong> Calling it “just a tool” lets the speaker sound balanced without naming what got commoditized — because naming it has career consequences for whoever’s listening.</p><p>Both takes get retweeted. Neither describes what happens at a keyboard.</p><blockquote>Fred Brooks saw this coming forty years ago. In <em>No Silver Bullet</em> (1986), he argued that no single advance would produce a 10x gain in software productivity within a decade — because most of the cost lives in the <em>essential</em> complexity of the problem, not the <em>accidental</em> complexity of the tools.</blockquote><p><strong>AI is the most powerful attack on accidental complexity we’ve ever shipped. It does almost nothing to essential complexity.</strong> Brooks predicted the exact shape of this disappointment in 1986, and the loudest voices in our industry still haven’t caught up to him.</p><h3>What’s actually true</h3><p>Strip the hype and the dismissal. Here’s what AI actually does in 2026 — whether you ship web apps, backend, mobile, data pipelines, or infra:</p><ul><li><strong>AI autocompletes a function.</strong> It can’t tell you whether the function should exist.</li><li><strong>AI generates a hundred tests in seconds.</strong> Which five matter is on you.</li><li><strong>AI rewrites a legacy module flawlessly.</strong> Whether the old behavior was intentional or a load-bearing bug requires reading the history, the tickets, and the faces of the people who built it.</li><li><strong>AI scaffolds an MVP in an afternoon.</strong> Whether the MVP solves the right problem is a question it can’t ask.</li><li><strong>AI passes every code-review check.</strong> Whether those checks check the right things stays invisible to it.</li></ul><p>The pattern is consistent. <strong>AI commoditized <em>production</em> — typing, syntax recall, boilerplate. It did not touch <em>judgment</em> — what to build, what not to build, what the system actually does, what’s safe to ship.</strong></p><p>The discourse conflates the two. The replacement take treats production as judgment (“if AI can write code, AI can do the job”). The tool take treats judgment as production (“use the tool well and you’ll be fine”). Both miss the shift: <strong>the skills that look like engineering on a resume are not the skills that ship working software — and AI made that gap measurable for the first time.</strong></p><p>The most rigorous public test came in mid-2025, when METR (Model Evaluation &amp; Threat Research) measured experienced open-source developers doing real tasks with and without AI. They predicted they’d be ~20% <em>faster</em>. They were ~19% <em>slower</em>. <strong>Most didn’t notice.</strong> The time saved on typing was eaten by reviewing, correcting, and debugging code that looked plausible and wasn’t. The gap between <em>feels faster</em> and <em>measurably slower</em> was almost forty points. Read that twice.</p><p>I didn’t notice either, the first time. I spent a Saturday “pairing” with a model on a gnarly module, felt like a genius, shipped it Monday — then spent Wednesday unpicking the plausible nonsense it had talked me into. <strong>I’d have sworn I was faster. The commit history said otherwise.</strong></p><h3>The category error nobody names</h3><p>Take the example everyone talks about: unit tests.</p><p>Last year I watched a strong engineer generate forty-some tests for a checkout service in an afternoon. Coverage jumped from <strong>71% to 94%</strong>. The PR sailed through review. Three weeks later a one-line change to the auth flow took down checkout in production — and not one test caught it. <strong>Every assertion was on a mock. The coverage was real. The protection was imaginary.</strong></p><p>You’ve sat in the standup where someone says it — “AI handles tests now,” “coverage is cheap with AI,” “juniors can just generate the unit tests” — everyone nods, you feel what’s wrong with it, and the meeting moves on before you can name it. The <strong>90% coverage line</strong> was <strong>never</strong> a <strong>typing problem</strong>. <strong>It was a design problem. It still is.</strong> AI didn’t move that line. It made it obvious who could already cross it.</p><p>Writing a test and achieving meaningful coverage are two completely different costs:</p><ul><li><strong>Writing a test</strong>: 5 minutes, 10 tests, looks great in the PR.</li><li><strong>Getting 70% → 90%+ coverage on a tightly-coupled codebase</strong>: weeks. Sometimes never.</li></ul><p>AI made the first cheap. The second is where the real cost lives — and <strong>AI doesn’t reduce it. Sometimes it makes things worse</strong>, because AI-generated tests on bad code build a confident floor of green checkmarks over the rot.</p><p>GitClear’s analysis of millions of commits found the same pattern from another angle: <em>code churn</em> — lines rewritten or reverted within two weeks — has risen sharply alongside AI adoption, while copy-paste began to outpace refactoring. Translation: <strong>AI helps you write code fast, then helps you delete it shortly after.</strong> PR throughput looks healthy. The codebase quietly absorbs the cost.</p><p>This category error — <strong>confusing the cheap thing with the expensive thing</strong> — is the entire AI discourse compressed into one mistake. Every section below is a different angle on it.</p><h3>Pipe and sink</h3><p>After years of shipping production code, the frame that best predicts which code AI can test is older and simpler than any architectural pattern: <strong>pipes and sinks.</strong></p><p>A <strong>pipe</strong> is pure logic — input in, output out, nothing else moving. Pure functions, bounded methods, modules that do one thing.</p><p>A <strong>sink</strong> is where effects land: a database write, an API call, the system clock, a global someone mutated three files away. Every real system has them. The question isn’t whether they exist — it’s whether they sit at the edges or run through every pipe in the system.</p><p>Pipes isolated from sinks looks like this:</p><pre>input ──▶ [ pure fn ] ──▶ [ pure fn ] ──▶ output<br>                                  │<br>                                  ▼<br>                            [  sink  ]      ← one isolated edge<br>                            (DB / API)        mock here, once</pre><p>You can test every pipe directly. Feed input, assert output. The sink gets mocked once, at the boundary. <strong>AI handles this well</strong> — the context stays small and the output is deterministic enough to assert on. Coverage climbs naturally because each test verifies one real behavior.</p><p>Pipes and sinks tangled looks like this:</p><pre>input ──▶ [ fn ] ──▶ [ fn ] ──▶ [ fn ] ──▶ output<br>              │           │          │<br>              ▼           ▼          ▼<br>          [singleton] [global]   [DB write]   ← hidden sinks<br>              │           │          │           leaking everywhere<br>              ▼           ▼          ▼<br>          [API call]  [mutation] [file I/O]</pre><p>To test one function, you mock every hidden sink it secretly touches. AI has to load every dependency just to see them. Outcomes depend on mutable state nobody declared. Tests pass that verify nothing. <strong>This is the configuration most production codebases are actually in.</strong></p><p>That’s the debt of letting pipes and sinks fuse. Not line count. Not cyclomatic complexity. <strong>How many hidden effects you’d have to mock to test a single behavior.</strong></p><h3>TDD and BDD are the plumbing diagram</h3><p>Here’s what hasn’t changed in 2026, despite everything AI promised.</p><p>TDD predates AI by 25 years. BDD by 20. They exist because we learned the hard way that <strong>design-for-testability is the only thing that makes testing economical at scale.</strong> Red-green-refactor isn’t about tests — it’s about <em>pressure on your design.</em> <strong>The test you can’t write is the design problem you haven’t seen yet.</strong></p><p>BDD goes further: every test specifies one <em>real behavior</em> the system should have. If your function does eight things, there’s no real behavior to specify — and AI inherits that confusion. <strong>It can’t write a coherent spec for incoherent code.</strong> It generates eight weak tests that each verify a sliver and protect you from nothing.</p><blockquote>Michael Feathers wrote <em>Working Effectively with Legacy Code</em> in 2004 — mostly a catalog of techniques for extracting seams from tangled code, exactly the work AI cannot do for you. The book is 22 years old and has never been more relevant.</blockquote><p><strong>AI doesn’t replace TDD or BDD. It depends on them. A great typist on a bad foundation just builds a faster house of cards.</strong></p><h3>The clean pipe — what AI nails</h3><p>Here’s the kind of code AI tests beautifully:</p><pre>function formatPrice(amount, currency) -&gt; String {<br>    // pure transformation, no I/O, no globals<br>}</pre><p>A pure function. No singletons, no globals, no time, no I/O. The test writes itself:</p><pre>test &quot;formats USD with two decimals&quot; {<br>    result = formatPrice(99.5, &quot;USD&quot;)<br>    assert result == &quot;$99.50&quot;<br>}</pre><p>AI will generate fifty edge cases for this in seconds — negatives, zero, currency variants, locale boundaries. All <em>real</em> tests verifying <em>real</em> behavior. <strong>This is where the productivity story is true.</strong></p><p>It’s also where most engineers don’t actually need help.</p><h3>The tangled mess — what AI breaks on</h3><p>Now the kind of code most teams actually have:</p><pre>function submitCheckout() {<br>    analytics.track(&quot;checkout_started&quot;)               // global singleton<br>    token = globalStorage.read(&quot;auth_token&quot;)          // hidden state<br>    httpClient.post(buildRequest(token), data -&gt; {    // concrete client<br>        eventBus.publish(&quot;checkout_completed&quot;, data)  // global bus<br>    })<br>}</pre><p><strong>Four hidden sinks in five lines.</strong> To test it, AI has to:</p><ul><li>Mock the analytics singleton — a global, no interface, no seam.</li><li>Mock the storage layer — same problem.</li><li>Intercept the network call — but the HTTP client is concrete, nothing to substitute.</li><li>Verify an event fired — into a global bus shared with everything else.</li></ul><p>What AI generates here is <strong>mock soup</strong>: an elaborate scaffold of stubs that asserts on the stubs themselves and verifies nothing real. Coverage goes up. Confidence should go down. Nobody notices.</p><p>This is <strong>coverage theater</strong> — green checkmarks performing safety while the code underneath stays exactly as broken.</p><h3>The singleton family</h3><p>Singletons are the famous villain, but they’re one species. The full family — <strong>every pattern that hides where state, dependencies, or effects actually live</strong> — looks like this:</p><ol><li><strong>Hidden state.</strong> Singletons and getInstance() patterns. Global mutable variables and static fields. Global key-value stores (app preferences, browser localStorage, a shared config object, the Redis everyone reads from). Global event buses and pub/sub channels. Reactive subjects fired as side effects.</li><li><strong>Hidden dependencies.</strong> Concrete-typed properties instead of interface abstractions. Sealed or final classes blocking substitution. Dependencies constructed inside the constructor instead of injected. Static methods reaching outward into global config or logger instances.</li><li><strong>Hidden non-determinism.</strong> Direct calls to system time inside business logic (Date.now, time(), System.currentTimeMillis). UUID and randomness baked into core logic. Queue, thread, or async scheduler timing leaking into outputs.</li><li><strong>Hidden effects.</strong> I/O mixed with logic. UI side effects fired from business code. Logging and analytics baked into otherwise pure operations. Null/optional handling masking state assumptions.</li><li><strong>Structural offenders.</strong> God classes — service objects, view-models, controllers — that do eight things. Mixed-concern functions doing network + parse + persist + notify in one body. Long inheritance chains scattering behavior across ancestors.</li></ol><p>Evey item is the same disease: <em>the sink is hidden from the test boundary.</em> The vocabulary changes between Python, Java, Go, TypeScript, Kotlin, C#, Rust. <strong>The plumbing diagram doesn’t.</strong></p><h3>The AI tax</h3><p>Here’s the part the managers need to understand.</p><p><strong>Every hidden sink is now a measurable cost per AI query.</strong></p><p>To test the tangled checkout function above, AI loads the analytics module, the storage layer, the HTTP client, the event bus listeners, and half the auth flow — just to understand <em>one</em> function. Context burned. Tokens spent. Quality lost as the model’s attention spreads thinner across irrelevant code.</p><p>A 200-line testable module fits in ~3K tokens. The same logic fused into a 1,500-line service class with five hidden dependencies costs ~25K tokens just to load — and produces measurably worse output. <strong>That’s not a metaphor. That’s an invoice.</strong></p><p>This is <strong>the AI tax</strong>: invoiced in tokens, paid in flopped completions, settled in shallow tests that pass CI and leak bugs to production. Tight coupling used to be a vague “tech debt” complaint. <strong>In 2026 it has a per-query price tag your CFO can read</strong> — if anyone bothers to show them.</p><p><strong>The companies that win the next five years won’t be the ones using more AI. They’ll be the ones whose codebases let AI work without resistance.</strong></p><h3>But won’t AI just get better at this?</h3><p>Context windows are growing. Models are improving. The argument is real. It’s also a trap.</p><p><strong>Bigger context doesn’t fix hidden state — it just lets AI fail more confidently across more code.</strong> A 2M-token window reading a tangled codebase doesn’t suddenly understand which mutations matter. It has more places to hallucinate. The problem isn’t model capacity. It’s that hidden behavior is undecidable from source — <em>for humans too.</em> That’s why we invented dependency injection forty years before AI showed up.</p><p>This isn’t theoretical. Stanford’s <em>Lost in the Middle</em> paper (Liu et al., 2023) measured what happens inside long context: performance degrades sharply when the relevant information sits in the middle of the input — even on models trained and marketed for long context. <strong>The model loads everything and pays attention to far less. A 2M-token window isn’t 2M tokens of working memory. It’s more room to lose the thread.</strong></p><p>“AI will figure it out eventually” is the same bet teams have made about tech debt for twenty years. Same track record.</p><h3>What actually does get cheaper</h3><p>To be fair, AI makes some things genuinely cheaper:</p><ul><li>Edge case enumeration on pure functions.</li><li>Parametrized and table-driven test variants.</li><li>Fixture and mock generation for code that already has clean seams.</li><li>Boilerplate scaffolding around already-testable code.</li></ul><p>The pattern never changes. <strong>AI is cheap on clean pipes, expensive — and often quietly wrong — on tangled ones.</strong></p><h3>The inversion</h3><p>Here’s what’s actually happening in our industry right now.</p><p>Engineers with clean codebases are getting <strong>5–10x leverage</strong> from AI. Their tests write themselves because their pipes were already isolated. Their coverage climbs because every pipe was already a real behavior. <strong>They look like wizards.</strong></p><p>Engineers with tangled codebases are getting nothing — or worse, accumulating coverage theater that collapses the first time a real refactor lands. <strong>They look like they’re failing to “use AI properly.”</strong></p><p>We’re mistaking the second group for unskilled. They’re not. They inherited plumbing debt, and AI is exposing it. <strong>The wizards aren’t wizards. They were sitting on a clean substrate when the tide came in.</strong></p><p>This is what the loud takes refuse to name — because both crowds need a story where the <em>engineer</em> is the variable. The replacement crowd needs you replaceable. The tool crowd needs you in charge. Neither can sell the actual answer: <strong>the substrate you inherited matters more than the skills you bring to it</strong> — and the people loudest about AI productivity are usually the ones who’ve never tested either claim against a real codebase under deadline.</p><h3>Open your codebase</h3><p>The diagnostic is simple, and it doesn’t care what you build. Open your repo this week and search:</p><ul><li>getInstance(), INSTANCE, .shared, .instance, module-level globals, static factory accessors — your <strong>singletons</strong>.</li><li>Global storage, app preferences, env vars read mid-flow, global event buses — your <strong>hidden state channels</strong>.</li><li>Direct system time, UUID, or random calls inside business logic — your <strong>non-determinism</strong>.</li><li>Classes with concrete-typed dependencies instead of interfaces — your <strong>missing seams</strong>.</li><li>Service classes over 500 lines touching DB, network, queue, and UI in one body — your <strong>god objects</strong>.</li></ul><p><strong>Every hit is an AI tax line item. Every hit is a future test you’ll fight to write — with or without AI.</strong></p><p>Run that search in a Rails monolith, a Go service, a React front end, a Spark job, a Terraform module — the names change, the diagnosis doesn’t. The mindset of engineering hasn’t changed. <strong>AI just turned the lights on — and the people loudest about what they see are mostly describing rooms they’ve never been in.</strong></p><p><strong>AI didn’t make testing cheap. It made bad design fatal.</strong></p><p><strong>AI didn’t 10x engineering. It exposed who was already 10x.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=039e36f8f773" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is MVVM Still relevant in SwiftUI Era?]]></title>
            <link>https://medium.com/@dev.finnchristoffer/i-built-the-same-ios-app-in-mvvm-mv-and-tca-heres-when-each-one-earns-its-keep-c90bf7e6aea1?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/c90bf7e6aea1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Mon, 04 May 2026 02:19:15 GMT</pubDate>
            <atom:updated>2026-05-07T08:19:10.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*IF9QAQt9wOdKr-UkDRsePw.jpeg" /></figure><h3>TL;DR</h3><ul><li>I built the same GitHub user search app three times: once in <strong>MVVM</strong>, once in <strong>MV</strong> (@Observable), and once in <strong>TCA</strong>.</li><li>The MVVM and MV implementations are <em>nearly identical at the code level</em>. The “ViewModel” suffix is the difference; the code isn’t.</li><li>TCA is genuinely different — different in kind, not just style. It costs more (~5x clean build time, ~18% more app source code), but what you’re paying for is explicit: exhaustive testability, structured state composition, and a refactoring-safe action/state coupling that catches drift cheaply.</li><li>My recommendation: <strong>start with MV. Apply KISS. Migrate to TCA when scale, complexity, or testing requirements outgrow what MV can carry comfortably.</strong></li><li>Repo: <a href="https://github.com/finnchristoffer/MV-vs-MVVM-vs-TCA">github.com/finnchristoffer/MV-vs-MVVM-vs-TCA</a>. Clone it and judge for yourself.</li></ul><h3>Why I Bothered</h3><p>There are already a hundred “compare SwiftUI architectures” blog posts. Most of them conclude “it depends.” I wanted something better than that — actual measurements, real code, and an opinion I can defend.</p><p>So I built the same feature, three times, in one Xcode project. Same shared layer (API client, persistence, design system). Same test cases at parity. Same Swift 6 strict concurrency settings. Three target schemes (MVVMApp, MVApp, TCAApp), each independently runnable.</p><p>The feature: search GitHub users (debounced 400ms), tap into a detail screen that fetches profile and top repos in parallel, favorite/unfavorite users, persist favorites across app launches. It’s deliberately small, but it stresses the things architectures actually differ on — async loading with cancellation, error states, shared state across screens, navigation, side effects.</p><p>After three implementations and a parity test suite of 14 tests per target, I have data. Here’s what it says.</p><p><strong>Setup details, for reproducibility:</strong> MacBook Pro M1, Xcode 26.2, iOS 17 deployment target, SWIFT_STRICT_CONCURRENCY=complete across all three targets. All measurements are from this environment; your numbers will vary on different hardware, but the relative gaps should hold.</p><p>A note on deployment targets: this article assumes iOS 17+ as a baseline, which covers roughly 95% of active iOS devices as of early 2026. If you’re maintaining a legacy enterprise app with an iOS 15 or 16 floor, @Observable isn&#39;t available to you yet, and the choice between MV and MVVM collapses into &quot;use ObservableObject.&quot; Once you can drop iOS 16, migrate.</p><h3>Surprise #1: MVVM and MV Are the Same Code Wearing Different Clothes</h3><p>This was the moment that changed the article I thought I was writing.</p><p>After both implementations were done, I diffed the search “brain” of each architecture — the file that owns search state, manages cancellation, and orchestrates the API call.</p><pre>$ diff MV/Search/SearchModel.swift MVVM/Search/SearchViewModel.swift<br>0a1<br>&gt; import Combine<br>2d2<br>&lt; import Observation<br>5,8c5,7<br>&lt; @Observable<br>&lt; final class SearchModel {<br>&lt;     private(set) var query = &quot;&quot;<br>&lt;     private(set) var state: SearchViewState = .idle<br>---<br>&gt; final class SearchViewModel: ObservableObject {<br>&gt;     @Published private(set) var query = &quot;&quot;<br>&gt;     @Published private(set) var state: SearchViewState = .idle<br>10,12c9,11<br>&lt; @ObservationIgnored private let apiClient: APIClient<br>&lt; @ObservationIgnored private let searchDelay: SearchDelay<br>&lt; @ObservationIgnored private var searchTask: Task&lt;Void, Never&gt;?<br>---<br>&gt; private let apiClient: APIClient<br>&gt; private let searchDelay: SearchDelay<br>&gt; private var searchTask: Task&lt;Void, Never&gt;?</pre><p>That’s it. Six lines of “difference,” none of which are logic.</p><p>The 30+ lines of actual search behavior — debounced query handling, task cancellation on each new keystroke, trimming, error mapping, state transitions — are <strong>byte-for-byte identical</strong> in both files.</p><blockquote><em>The MVVM-vs-MV debate, at the code level, is a debate about which import statements you write and where you sprinkle property wrappers.</em></blockquote><p>This isn’t an indictment of either pattern. It’s a clarification. When you migrate from ObservableObject + @Published to @Observable:</p><ul><li>Your storage class barely changes shape.</li><li>Your views need slightly less boilerplate (no more @StateObject / @ObservedObject ceremony — @State is enough).</li><li>Your fine-grained observation gets faster (Apple’s @Observable is more performant for property-level updates).</li></ul><p>But the <em>pattern</em> — “a class that owns state and exposes methods the view calls” — is exactly the same. If your team has been writing SomethingViewModel for years, you can rename your @Observable classes SomethingViewModel and ship. If you find that confusing, you can call them SomethingModel and also ship. The architecture police won&#39;t show up.</p><p><strong>What this means for the discourse:</strong> stop arguing about MVVM vs MV. Argue about state ownership, testability, and how much logic belongs outside the view. Those are the questions that actually matter.</p><h3>Surprise #2: TCA Is Genuinely Different — and the Tests Prove It</h3><p>If MV and MVVM are cosmetic variations of the same idea, TCA is a different idea entirely. The clearest place to see this is in the tests.</p><p><strong>If I had to pick one feature of TCA that justifies its cost on its own, it would be the testing model.</strong> Not the architecture. The tests.</p><p>Here’s the MV test for “search debounces and fetches users”:</p><pre>func test_searchQueryChange_debouncesAndFetchesUsers() async {<br>    // Arange<br>    let apiClient = MockAPIClient(searchUsersResult: .success([TestFixtures.user]))<br>    let searchDelay = ManualSearchDelay()<br>    let model = SearchModel(apiClient: apiClient, searchDelay: searchDelay)<br><br>    model.searchQueryChanged(&quot;octocat&quot;)<br><br>    // Act<br>    await waitForPendingDelay(count: 1, in: searchDelay)<br>    await searchDelay.resumeAll()<br>    await waitForSearchState(.loaded([TestFixtures.user]), in: model)<br>    let searchedQueries = await apiClient.searchedQueries<br>    <br>    // Assert<br>    XCTAssertEqual(searchedQueries, [&quot;octocat&quot;])<br>}</pre><p>To make this work, I had to write three pieces of custom test infrastructure: a ManualSearchDelay actor that exposes continuations, a waitForPendingDelay helper that polls with Task.yield(), and a waitForSearchState helper that polls the model&#39;s published state. The MVVM test is identical except for the viewModel variable name.</p><p>Here’s the same test in TCA:</p><pre>func test_searchQueryChange_debouncesAndFetchesUsers() async {<br>    // Arange<br>    let clock = TestClock()<br>    let recorder = QueryRecorder()<br>    let store = TestStore(initialState: SearchFeature.State()) {<br>        SearchFeature()<br>    } withDependencies: {<br>        $0.continuousClock = clock<br>        $0.apiClient.searchUsers = { query in<br>            await recorder.append(query)<br>            return [TestFixtures.user]<br>        }<br>    }<br><br>    // Act<br>    await store.send(.searchQueryChanged(&quot;octocat&quot;)) {<br>        $0.query = &quot;octocat&quot;<br>        $0.searchState = .loading<br>    }<br>    await clock.advance(by: .milliseconds(400))<br>    await store.receive(.searchResponse(.success([TestFixtures.user]))) {<br>        $0.searchState = .loaded([TestFixtures.user])<br>    }<br><br>    // Assert<br>    let searchedQueries = await recorder.queries<br>    XCTAssertEqual(searchedQueries, [&quot;octocat&quot;])<br>}</pre><p>Look at what’s happening. The TCA test asserts the <em>exact</em> state transition after each step. After searchQueryChanged(&quot;octocat&quot;), the test verifies the query updates <em>and</em> the state immediately becomes .loading. After the clock advances and the response arrives, it asserts the state becomes .loaded with the exact users. If a future refactor accidentally introduces an intermediate state, or skips one, the test fails — pointing at the exact transition that drifted.</p><p>The MV/MVVM tests can’t easily do this. They only assert <em>eventual</em> state (“eventually the model becomes .loaded&quot;). Whether it passed through .loading first, or skipped straight to .loaded, or briefly held some other intermediate state — the test doesn&#39;t know and doesn&#39;t care.</p><p><strong>The TCA test is also shorter.</strong> No ManualSearchDelay actor. No waitForPendingDelay helper. No polling.</p><p>But the deeper win is what TestStore + TestClock eliminate: <strong>flaky async tests</strong>. The MV polling helpers (waitForPendingDelay, waitForSearchState) work most of the time, but they&#39;re racing the test runtime. Slow CI machine? Different scheduler? GitHub Actions runner under load? Eventual-state assertions are exactly the kind of test that goes green locally and red intermittently in CI — and intermittent failures are how teams stop trusting their test suite. TCA&#39;s testing model deletes this entire category of failure mode by making the clock and the dependencies synchronous and deterministic.</p><p>This is what I mean by “different in kind.” The MV/MVVM testing model is “make the thing happen, wait for it to settle, assert the final state.” The TCA testing model is “drive the state machine forward, assert each transition, fail loudly on drift, never wait for a real clock.” Those aren’t different styles of the same thing. They’re different beliefs about what tests should prove.</p><p>For most CRUD list/detail features, the MV/MVVM model is good enough. For features where exact behavior matters — payment flows, multi-step forms, anything where “we accidentally skipped a state” is a real bug — TCA’s model catches things the others miss. And in any codebase large enough that flaky tests start eroding team trust, the deterministic testing alone may be the reason to migrate.</p><h3>What You’re Paying For</h3><p>TCA is more expensive than MV. That’s not a bug. It’s the price of explicitness, and at the right scale, it’s worth paying. The question isn’t whether TCA is expensive — it is. The question is whether your app is paying that price for something it actually needs.</p><p>Here’s the bill, itemized.</p><h4><strong>Build time</strong></h4><p>I measured clean builds three times each, on the same machine (MacBook Pro M1, Xcode 26.2), with fresh DerivedData, Debug configuration, generic/platform=iOS Simulator, CODE_SIGNING_ALLOWED=NO, and SWIFT_STRICT_CONCURRENCY=complete:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*AObdqosor6r21o11nSULdw.png" /></figure><p>That’s a ~5x build time penalty for TCA. Most of it is dependency compilation (the TCA package, swift-navigation, swift-perception, swift-case-paths) and macro expansion (@Reducer, @ObservableState, @CasePathable).</p><p>This cost is most painful on cold builds and CI. Incremental builds during local development are dramatically better. If your CI pipeline runs on every PR and build minutes are billed, the TCA premium has a real dollar cost. If your team has invested in build caching, parallel CI runners, and incremental build optimization, the cost is much smaller.</p><p>Your absolute numbers will differ on different hardware (an M3 Max will cut these significantly), but the <em>ratio</em> between architectures should hold.</p><h4>Code size</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*net-1snQbFTK_0u1qDNxtA.png" /></figure><p>TCA is about 18% larger for the same behavior. The extra weight isn’t in features — per-feature, TCA is competitive (the SearchFeature reducer + view is actually a bit smaller than the MV equivalent). The overhead is in <strong>infrastructure</strong>: dependency definitions (TCAAPIClient, TCAFavoritesClient wrappers around the protocols), root composition (Scope + reducer plumbing), and explicit cancellation IDs.</p><p>This isn’t TCA being bloated. It’s the cost of being explicit about things MV/MVVM leaves implicit. The 18% becomes a much smaller percentage as the app grows, because the infrastructure cost is mostly fixed while feature code scales linearly.</p><h3>Toolchain friction</h3><p>I had to ship a <em>patched local copy</em> of swift-navigation because the macro-expanded CasePathsCore references didn&#39;t link cleanly through the resolved package graph on Xcode 26.2. A different pattern with no dependencies wouldn&#39;t have hit this.</p><p>Adopting TCA means adopting the entire Point-Free dependency graph: TCA itself, swift-navigation, swift-perception, swift-case-paths, plus their transitive macros. These are well-maintained packages, but you&#39;re trusting the upgrade cadence of an external team alongside Apple&#39;s. For most projects, that&#39;s fine. For long-lived enterprise codebases that pin dependencies tightly, this is a coordination cost worth being aware of.</p><h3>Learning curve</h3><p>Onboarding a mid-level iOS developer:</p><ul><li><strong>MV</strong>: about a day. They already understand @State and @Observable; they just need to see the patterns.</li><li><strong>TCA</strong>: one to two weeks before they’re productive without supervision. Reducers, actions, effects, dependencies, scoping, TestStore, @Bindable stores, cancellable(id:), the difference between .send and store.send. It&#39;s a real framework, and it has the learning curve of one.</li></ul><p>The cost compounds with team turnover. Every new hire pays the curve again. But it amortizes the other way too: once a team is fluent, the convention itself becomes a scaling tool — every engineer reads the same patterns, debugs the same way, tests the same way.</p><h3>Where TCA Earns Its Keep at Scale</h3><p>This is the part most “comparing architectures” articles skip, and it’s where TCA’s costs flip from prohibitive to obviously worth it.</p><p><strong>Test rigor compounds at scale.</strong> In a 5-screen app, eventual-state assertions are fine — bugs are easy to spot, the surface area is small, and integration tests catch most regressions. In a 100-screen app with cross-feature state coordination, “we accidentally skipped a state” becomes an actual bug class. Auth flows with subtle state ordering. Checkout funnels with race conditions between user input and async validation. Multi-step forms where step 4 silently doesn’t reset when the user navigates back to step 2. These bugs are expensive to find in production and nearly impossible to reproduce in eventual-state tests. TCA’s TestStore makes them cheap to catch in CI.</p><p><strong>Onboarding cost amortizes.</strong> A 1–2 week TCA learning curve sounds expensive for a 3-person team. For a 30-person team where new hires arrive every quarter, the curve pays back fast. After the second or third hire, the team has documented patterns, internal training, and code review heuristics that make ramp-up linear instead of bespoke. Convention is itself a scaling tool — and TCA enforces convention more strictly than MV does. In MV, every team invents their own conventions for “where does logic go?” and “how do we share state between screens?” In TCA, the framework answers both questions before you write a line of code.</p><p><strong>Refactoring confidence.</strong> Action/state coupling means a refactor that breaks behavior fails tests immediately, and the failure points at the exact action and state transition that drifted. At enterprise scale — where one team’s refactor lands in another team’s feature — this isn’t a luxury. It’s how you ship quarterly without regression. MV refactors can’t offer the same guarantee; eventual-state tests pass through behavior changes that should have failed.</p><p><strong>Centralized effect management.</strong> When the app has 50 in-flight async operations across 20 screens — pull-to-refresh, autosave, background sync, push-notification-triggered fetches — having a single, explicit cancellation model becomes valuable. TCA’s cancellable(id:) and effect cancellation are designed for this. MV&#39;s Task handles work fine in isolation, but at scale, every team builds slightly different cancellation patterns and the inconsistency becomes a source of bugs.</p><p>The honest version of “when does TCA earn its keep” is: <strong>when the costs of inconsistency, flaky tests, and silent behavior drift exceed the costs of build time, package weight, and onboarding.</strong> That crossover point lives somewhere between “small SwiftUI app” and “iOS app at a 50-engineer fintech.” Most teams underestimate when they’ve crossed it.</p><h3>So, Is MVVM Still Relevant in SwiftUI?</h3><p>This is the question that started the whole experiment. Here’s my answer.</p><p><strong>MVVM the <em>pattern</em> is still relevant.</strong> Putting presentation state and orchestration logic in a class that the view consumes is a perfectly good architecture. SwiftUI doesn’t kill it.</p><p><strong>MVVM the <em>Combine-era implementation</em> (</strong><strong>ObservableObject + </strong><strong>@Published) is obsolete in 2026</strong> if you can target iOS 17+. @Observable is a strict upgrade — same pattern, less ceremony, better performance, no @Published annotations needed. The only reason to keep using ObservableObject is iOS 16 support, and that&#39;s a backward-compatibility decision, not an architectural one.</p><p><strong>The “ViewModel” name is doing damage.</strong> I’ve seen teams adopt SwiftUI, rename their classes from ThingController to ThingViewModel, and declare themselves &quot;MVVM in SwiftUI&quot; — when in reality they&#39;re just storing state in @Observable classes and calling them ViewModels out of habit. That&#39;s fine. But pretending it&#39;s a different architecture from MV is a fiction that confuses the team and clutters the conversation.</p><p>If you’re doing MVVM in SwiftUI, you’re probably doing MV with a label. If you’re doing MV with a label, just call it MV.</p><h3>A Stage-Based Decision Framework</h3><p>I used to phrase this as “default to MV, justify TCA.” That’s still true, but it’s incomplete — it implies TCA is only ever a special case, when really it’s a destination most serious codebases eventually reach.</p><p>A better framing is stage-based. Architecture choice isn’t a one-time decision; it’s a function of where your app is in its lifecycle.</p><h3>Stage 1: Start with MV. Apply KISS.</h3><p>For a new project, a small team, or an app that hasn’t yet found product-market fit: <strong>use MV (</strong><strong>@Observable)</strong>. It&#39;s the lowest-ceremony architecture that gives you everything SwiftUI was designed for. State lives close to views. Shared state lives in @Observable classes injected through the environment or constructor. Async work uses structured concurrency directly. Tests use protocol-based mocks.</p><p>Don’t over-architect for problems you don’t have yet. The biggest mistake in this stage isn’t picking the wrong architecture — it’s picking an architecture too heavy for the problem you’re actually solving today. Most apps live their entire lifecycle in this stage. That’s fine.</p><h3>Stage 2: Notice the warning signs.</h3><p>As the app grows, watch for these signals. Any one of them on its own is a yellow flag. Two or more together is the cue that MV is starting to strain:</p><ul><li><strong>Flaky async tests in CI.</strong> Tests pass locally, fail intermittently in CI, and the team starts adding retries instead of fixing them. This is the canary; ignore it at your peril.</li><li><strong>Cross-feature state coordination is getting hard.</strong> You’re passing the same @Observable model through five layers of views, or you&#39;re starting to invent your own pub/sub system on top of @Observable.</li><li><strong>The team is large enough that conventions aren’t enforcing themselves.</strong> Different engineers solve the same async-cancellation problem three different ways. Code review is becoming an architecture argument every PR.</li><li><strong>Bug class: “we silently skipped a state.”</strong> Auth flows, multi-step forms, payment flows that worked yesterday and have a subtle ordering bug today. Eventual-state tests passed through it.</li><li><strong>Onboarding new hires is slow because the codebase has no conventions, only patterns each team invented.</strong></li></ul><h3>Stage 3: When the signals stack up, migrate to TCA.</h3><p>This is the stage most architecture articles get wrong. They treat migration as catastrophic. It isn’t — if the migration target is TCA and the source is MV.</p><p>Here’s why migration is more tractable than people think: <strong>the underlying domain logic transfers cleanly</strong>. The async work in your MV model becomes a TCA effect. The state stays the same. The dependencies stay the same. What changes is the orchestration layer — and in exchange, you get the testing rigor, the structured composition, and the convention enforcement that you needed anyway.</p><p>The mistake isn’t choosing the wrong architecture upfront. The mistake is staying on the wrong one too long, accumulating tests you don’t trust and bugs you can’t reproduce, until migration feels too expensive to justify.</p><h3>What “the right environment for TCA” actually means</h3><p>When I say a team is ready for TCA, I mean four things, concretely:</p><ol><li><strong>Team familiarity</strong> — at least one or two engineers who already understand reducer-driven architecture, who can mentor others through the curve.</li><li><strong>CI/CD that can absorb the build cost</strong> — adequate runner capacity, build caching, willingness to invest in incremental build performance.</li><li><strong>A test culture that demands rigor</strong> — the team treats flaky tests as bugs to fix, not annoyances to retry. Without this, TCA’s testing power is wasted.</li><li><strong>Leadership willing to invest in onboarding</strong> — the 1–2 week ramp-up is allocated explicitly for new hires; it isn’t squeezed into “learn it on Friday afternoons.”</li></ol><p>If you have all four, TCA is a strong choice for a serious codebase. If you have one or two, you can probably make TCA work but the ROI is lower. If you have none, MV is almost certainly the better choice — TCA without those preconditions is cargo-cult architecture, and you’ll get the costs without the benefits.</p><h3>A note for teams already on TCA</h3><p>If your team is already on TCA and shipping, this article isn’t a migration argument. Switching costs are real, “MV would be slightly simpler” isn’t a reason to throw away a working codebase, and the cost-benefit analysis I’m describing is for <em>new</em> projects making <em>new</em> decisions. Stay on what’s working. The framework’s overhead is paid up-front; you’ve already paid it.</p><h3>What This Experiment Didn’t Prove</h3><p>I want to flag the limits of my own findings, because the comments section will rightly push on these.</p><p><strong>Single-feature scope.</strong> I built one feature with four screens. A real app with 50 screens, 10 deep-linked flows, and complex cross-feature state coordination would shift the balance. TCA’s overhead amortizes better at scale; MV’s simplicity may strain. The “where TCA earns its keep at scale” arguments above are extrapolations from this experiment plus prior production experience, not direct measurements from this POC.</p><p><strong>No long-term maintenance signal.</strong> I built each architecture once and measured the result. I didn’t simulate six months of feature additions, refactors, and bug fixes. Some patterns hold up better than others under evolution, and a one-shot build doesn’t capture that.</p><p><strong>No team scaling signal.</strong> Solo work on a POC doesn’t tell you how the architecture feels with five engineers in the same codebase, code review cycles, and onboarding new hires. TCA’s explicitness can be a coordination win at team scale even when it’s a verbosity cost solo.</p><p><strong>No UI complexity stress test.</strong> The feature has standard list/detail navigation. I didn’t test deep-linking, multi-window, or document-based scenarios where TCA’s state composition really pays off.</p><p>So treat this as evidence, not proof. The numbers are real. The diffs are real. The recommendations are grounded. But the experiment is small, and the scale arguments are informed extrapolation — not measurement.</p><h3>The Repo</h3><p>If you got this far, you probably want to clone it:</p><p><a href="https://github.com/finnchristoffer/MV-vs-MVVM-vs-TCA"><strong>github.com/finnchristoffer/MV-vs-MVVM-vs-TCA</strong></a></p><p>Three target schemes. 14 parity tests in each. Same shared layer. Run them, read them, disagree with my conclusions. The point of publishing the code is so the conversation can be about evidence instead of opinions.</p><p>If you do the same exercise and reach a different conclusion, write that up too. The community needs more “I built it three ways and measured” and fewer “in my opinion, MVVM is dead.” Including from me.</p><h3>Closing Thought</h3><p>The most honest answer to “is MVVM still relevant?” is: <strong>the question is poorly framed</strong>. The real question is “what do I optimize my presentation layer for, given the size, complexity, and team I actually have <em>today</em> — and the size, complexity, and team I’ll have in two years?”</p><p>Start with MV. Apply KISS. Don’t over-architect for problems you don’t have yet. As your app grows in complexity, team size, or testing requirements, the cost-benefit of TCA flips. When that flip happens — and you’ll know, because the warning signs are clear — migrate. The underlying domain logic transfers; what changes is the orchestration around it.</p><p>The mistake isn’t choosing the wrong architecture upfront. The mistake is staying on the wrong one too long.</p><p>That’s the article. Argue with me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c90bf7e6aea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capital, Code, and the Calculus of Regret]]></title>
            <link>https://medium.com/@dev.finnchristoffer/capital-code-and-the-calculus-of-regret-1e72fe5f00f4?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e72fe5f00f4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[philosophy]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 11:03:49 GMT</pubDate>
            <atom:updated>2026-02-08T11:03:49.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CRY6pYevxeWvLDGXgW2X7Q.jpeg" /><figcaption>Image generated from Gemini</figcaption></figure><p>I spend my mornings submerged in macroeconomics podcasts and my afternoons refactoring logic. For a long time, I treated these as separate lives. One was about the cold mechanics of central banks, CPI, and GDP; the other was about compilers and syntax.</p><p>But the more I build, the more I see that a software engineer is just a fund manager whose primary capital is time.</p><p>Every decision we make — from choosing a framework to naming a variable — is a financial transaction with a measurable P&amp;L (Profit and Loss). We aren’t just writing instructions. We are managing assets, taking on debt, and hedging against a future that is inherently volatile.</p><p>To understand this, we have to stop looking at code as “art” and start auditing it like a balance sheet.</p><h4><strong>High-Interest Payday Loans: Real Cost of “Quick Fixes”</strong></h4><p>We’ve all done it: a “quick fix” that involves hard-coding a value of bypassing an architectural layer / pattern just to hit a Friday deadline. In the moment, it feels like efficiency. It feels like high velocity.</p><p>But let’s audit the actual numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*37rfldaypLiDPBiTLr91FA.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>I recently tracked the time cost of a specific bug fix in two different modules: one built with <strong>Clean Architecture</strong>, and one that was “<strong>messed code</strong>” (tightly coupled spaghetti logic).</p><p><strong>Asset (Clean Architecture):</strong></p><ul><li><strong>Upfront Cost (Q1):</strong> It took me <strong>30 minutes</strong> to build the initial feature properly — isolating the ViewModel and injecting dependencies.</li><li><strong>Maintenance Cost (Q2): </strong>When a bug appeared later, the isolation meant I found and fixed the issue in <strong>45 minutes</strong>.</li><li><strong>Total Time: </strong>1 hour, 15 minutes.</li></ul><p><strong>Debt (Messed Code):</strong></p><ul><li><strong>Upfront Cost (Q1): </strong>I could have hacked this together in <strong>10 minutes</strong>. In the moment, I “saved” 20 minutes.</li><li><strong>Maintenance Cost (Q2): </strong>Because the logic was tangled and devoid of tests, debugging the same issue took <strong>6 hours</strong>. I had to trace state changes across three different files and restart the simulator a dozen times.</li><li><strong>Total Time: </strong>6 hours, 10 minutes.</li></ul><p><strong>Calculus of Regret: </strong>To save <strong>20 minutes</strong> on Tuesday, I agreed to pay <strong>6 hours</strong> on Friday.</p><p>In financial terms, that is an interest payment of <strong>1,700%</strong>. If you managed money this way, you would be bankrupt by noon. Yet, in engineering, we call this “moving fast” and patch it over with another loan.</p><h4><strong>Feature Inflation: The Diminishing Returns of Code</strong></h4><p>In macroeconomics, if a centra bank prints money without a corresponding increase in goods, you get inflation. Your currency buys less.</p><p>Software suffers from <strong>Feature Inflation.</strong></p><p>We tend to believe that adding more features makes the product “richer.” But every new line of code is a new liability. Each feature adds of complexity to the navigation, a new branch in the testing logic, and a new cognitive hurdle for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_-m9GtJwu0qimOOkPdF-gA.png" /><figcaption>Image generated by Gemini</figcaption></figure><p>As the chart above illustrates, there is a <strong>Value Gap.</strong></p><ul><li><strong>Code Growth (Yellow): </strong>On a recent legacy project, we increased the codebase size by 40% (Linear growth).</li><li><strong>Value Realized (Blue): </strong>Despite the bloat, our Daily Active Users (DAU) only grew by 3%.</li></ul><p>This is the <strong>Law of Diminishing Marginal Returns</strong>. The first feature you build solves 80% of the user’s problem. The fiftieth feature solves 1% of the problem but adds <strong>20% more maintenance overhead</strong>.</p><p>If your “Feature Velocity” is high, but your “Value Realization” is flat, you are entering a recession. You are printing “code currency,” but its purchasing power — its ability to capture user attention — has plummeted.</p><h4><strong>Your Codebase is an Asset Class</strong></h4><p>If we view code through the lens of an investor, our architectural patterns look less like “clean code” and more like <strong>Risk Management:</strong></p><ul><li><strong>Modularization is Diversification:</strong> by breaking a monolith into <strong>6 distinct modules, </strong>we reduced our average incremental build time from <strong>140 seconds</strong> to <strong>35 seconds.</strong> That’s a <strong>75% reduction</strong> in “transaction fees” every time a developer hits CMD+B.</li><li><strong>Test Coverage as a Hedge:</strong> Writing unit tests increased our upfront development time by <strong>20%</strong>. However, it reduced our production crash rate from <strong>1.2% to 0.1%.</strong> That upfront premium saved us the catastrophic capital loss of a 1-star review bomb.</li><li><strong>Documentation as Liquidity: </strong>Undocumented code is an illiquid asset. It cannot be easily transferred to a new owner (developer). By implementing strict documentation standards, we reduced the “onboarding time to first commit” for new hires from <strong>10 days to 3 days.</strong> We increased the liquidity of our human capital.</li></ul><h4><strong>Myth of the Rational Actor</strong></h4><p>The hardest part about economics — and engineering — is that the market isn’t rational.</p><p>We often choose a new framework not because of <strong>ROI </strong>(Return of Investment) is positive, but because of <strong>FOMO</strong>. We over-engineer solutions, creating a “complexity premium” that no one asked for.</p><p>I once spent <strong>30 hours</strong> implementing a reactive programmign framework for a simple list view. The “maintenance cost” of that code was double that of the standard imperative approach. I treated the codebase like a casino rather than a savings account.</p><h3>Quotes</h3><blockquote>The most expensive line of code isn’t the one that takes a long time to write. It’s the one that saves you <strong>5 minutes today</strong> but costs you <strong>5 days next year.</strong></blockquote><blockquote>In the economy of software, there are no bailouts — only compile errors.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e72fe5f00f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Interview: Swift Closures Devil’s Advocate]]></title>
            <link>https://medium.com/is-a-code/ios-interview-swift-closures-devils-advocate-e1e749fbd7ef?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e749fbd7ef</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 07:38:49 GMT</pubDate>
            <atom:updated>2025-12-25T04:24:11.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxPtdaPtiJAAJc62xLBnGg.png" /><figcaption>Generated by Nano Banana Pro</figcaption></figure><p><em>You think you know </em><em>{ }. But can you explain the memory cost?</em></p><p>We use closures every day. We pass them to map, we store them in ViewModels, and we rely on them for concurrency.</p><p>But let me play the <strong>Devil’s Advocate</strong>.</p><p>If I asked you in an interview: <em>“Why is a closure exactly 16 bytes on a 64-bit system?”</em> or <em>“Why does Swift capture variables by reference instead of value?”</em> — could you answer?</p><p>To a Junior Engineer, a closure is just syntax. To a Principal Engineer, a closure is a specific memory structure with performance costs and architectural trade-offs.</p><p>If you want to master the interview (and the runtime), you need to look under the hood. Here is the deep dive into what actually happens when you type that curly brace.</p><h3>1. The Anatomy: What is a Closure Really?</h3><p>We often hear that “Functions are Reference Types” in Swift. That is partially true, but a Closure is actually a <strong>Fat Pointer</strong>.</p><p>On a 64-bit system, a closure takes up 16 bytes. It consists of two pointers:</p><pre>struct Closure {<br>    var functionPointer: UnsafeRawPointer // Where the code lives (Instructions)<br>    var contextPointer: AnyObject?        // Where the captured data lives (Heap)<br>}</pre><ul><li><strong>Function Pointer:</strong> This points to the static instructions (the code itself) inside the __TEXT segment of your binary.</li><li><strong>Context Pointer:</strong> This points to a hidden object on the Heap (the “Capture Box”) that stores the variables you used from the outside scope.</li></ul><p><strong>The Devil’s Detail:</strong> When you pass a closure around, you are just passing this tiny 16-byte struct. The heavy lifting (memory management) happens in the <em>Context</em>, which is reference-counted (ARC).</p><h3>2. The Trap: Variables vs. Values</h3><p>This is the most common “Gotcha” in interviews. <strong>Swift closures capture variables by reference, not by value.</strong></p><p>Let’s look at this quiz:</p><pre>var counter = 0<br>let closure = {<br>    print(counter)<br>}<br><br>counter = 10<br>closure() // What does this print?</pre><p><strong>Answer:</strong> It prints 10.</p><p>Many developers guess 0, thinking the closure copied the value 0 when it was created. <strong>But here is what really happens:</strong> The closure&#39;s context captures a <em>pointer</em> to the storage location of counter. When you run the closure later, it looks at that memory address and sees the new value (10).</p><h4>How to Fix It (Capture Lists)</h4><p>If you want to capture the <strong>value</strong> at the specific moment of creation (a snapshot), you must use a <strong>Capture List</strong>.</p><pre>var counter = 0<br>let closure = { [counter] in // &quot;Copy this value right now&quot;<br>    print(counter)<br>}<br><br>counter = 10<br>closure() // Prints: 0</pre><h3>3. The 4 Keywords: Real-World Problems Solved</h3><p>Swift doesn’t add keywords for fun. Each one solves a specific architectural problem. Here is how to use them to solve real issues in your codebase.</p><h3>A. Non-Escaping (The Default)</h3><p><strong>Problem:</strong> Heap allocations are slow. If I just want to transform an array or run a simple action immediately, I shouldn’t have to pay the cost of allocating memory on the Heap.</p><ul><li><strong>Misunderstanding:</strong> Thinking all closures are expensive.</li><li><strong>Reality:</strong> By default, closures are <strong>Non-Escaping</strong>. The compiler optimizes them to live on the <strong>Stack</strong>. They are virtually “free.”</li></ul><pre>func runNow(action: () -&gt; Void) {<br>    action() // executed immediately<br>}<br><br>// Usage<br>runNow { print(&quot;Hello&quot;) } // Zero allocation overhead.</pre><h3>B. @escaping (The &quot;Async&quot; Reality)</h3><p><strong>Problem:</strong> You need to execute code <em>after</em> a function returns (e.g., after a 2-second delay or a network response). The function’s stack frame will be destroyed immediately, so the closure needs to survive elsewhere.</p><ul><li><strong>Bad Practice:</strong> Trying to force async logic without understanding lifecycle. If you don’t mark it @escaping, the compiler stops you because it knows the memory would become invalid.</li><li><strong>Good Practice:</strong> Explicitly marking it @escaping to tell the compiler: <em>&quot;Move this closure to the Heap so it survives the function return.&quot;</em></li></ul><pre>// Good Practice<br>func runLater(action: @escaping () -&gt; Void) {<br>    // We hand &#39;action&#39; off to the system. <br>    // It stays in memory (Heap) until the timer fires 1 second later.<br>    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {<br>        action()<br>    }<br>}</pre><h3>C. @autoclosure (The &quot;Clean Code&quot; Hack)</h3><p><strong>Problem:</strong> You want <strong>Lazy Evaluation</strong> (don’t run expensive code unless needed) for performance, but you want <strong>Clean Syntax</strong> for readability.</p><ul><li><strong>Bad Practice (Performance Hit):</strong> Passing a regular value. The expensiveCalculation() runs every time, even if isDebug is false.</li></ul><pre>func log(_ message: String) {<br>    if isDebug { print(message) }<br>}<br>log(&quot;User: \(expensiveCalculation())&quot;) // Calculates even if log is ignored</pre><ul><li><strong>Bad Practice (Syntax Hit):</strong> Passing a closure. The performance is fixed, but the call site is ugly.</li></ul><pre>func log(_ message: () -&gt; String) {<br>    if isDebug { print(message()) }<br>}<br>log({ &quot;User: \(expensiveCalculation())&quot; }) // Ugly braces</pre><ul><li>G<strong>ood Practice:</strong> Using @autoclosure to get the best of both worlds.</li></ul><pre>func log(_ message: @autoclosure () -&gt; String) {<br>    if isDebug { print(message()) }<br>}<br><br>// Looks like a String, acts like a Closure.<br>// &#39;expensiveCalculation()&#39; is only run if isDebug is true.<br>log(&quot;User: \(expensiveCalculation())&quot;)</pre><h3>D. @Sendable (The Swift 6 Enforcer)</h3><p><strong>Problem:</strong> You accidentally captured a mutable class (like a ViewModel or User object) inside a background Task. The main thread is reading it while the background thread writes to it. This causes random crashes (Data Races).</p><ul><li><strong>Bad Practice:</strong> Capturing non-thread-safe reference types in a Task.</li></ul><pre>class MutableUser { var name = &quot;John&quot; }<br><br>func updateBackground() {<br>    let user = MutableUser()<br><br>    // Swift 6 Error: Capture of non-sendable type &#39;MutableUser&#39;<br>    Task {<br>        user.name = &quot;Alice&quot; // Race condition waiting to happen<br>    }<br>}</pre><ul><li><strong>Good Practice:</strong> Using Value Types (struct) or Actors, which are safe to pass across thread boundaries.</li></ul><pre>struct ImmutableUser { let name: String } // Structs are Sendable<br><br>func updateBackground() {<br>    let user = ImmutableUser(name: &quot;John&quot;)<br><br>    Task { @Sendable in<br>        print(user.name) // Safe to read from any thread<br>    }<br>}</pre><h3>4. The Retain Cycle: Why [weak self]?</h3><p>We all know we need [weak self] to fix leaks. But <strong>why</strong> does the leak happen physically?</p><p>It’s not magic. It’s a pointer cycle.</p><ol><li>self points to -&gt; Closure.</li><li>Closure (via its Context Box) points to -&gt; self.</li></ol><p>Neither side can let go.</p><p><strong>Opinion: The “Weak-Strong Dance”</strong> The guard let self = self dance isn&#39;t just boilerplate. It is a <strong>lifecycle upgrade</strong>.</p><pre>viewModel.onSuccess = { [weak self] in<br>    // 1. We start with a weak reference (safe).<br>    guard let self = self else { return }<br>    <br>    // 2. We upgrade to a STRONG reference for this scope only.<br>    // Why? To ensure &#39;self&#39; isn&#39;t deallocated while we are half-way through updating the UI.<br>    self.updateUI()<br>}</pre><h3>Conclusion &amp; Cheat Sheet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*EmBv4ev4ZETtjTee8Gr5yw.png" /></figure><p>Next time you write { }, remember what you are asking the machine to do. You are creating a custom struct that manages memory, pointers, and concurrency rules. Understanding this is what separates a coder from an engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e749fbd7ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/is-a-code/ios-interview-swift-closures-devils-advocate-e1e749fbd7ef">iOS Interview: Swift Closures Devil’s Advocate</a> was originally published in <a href="https://medium.com/is-a-code">Is a code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From E-Rank to S-Rank: How to “Arise” in Your Engineering Career]]></title>
            <link>https://medium.com/@dev.finnchristoffer/from-e-rank-to-s-rank-how-to-arise-in-your-engineering-career-a06eb9e1a817?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/a06eb9e1a817</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[growth-mindset]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 14:07:24 GMT</pubDate>
            <atom:updated>2025-12-16T14:07:24.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jkXY7Iv0qh6taBI8" /><figcaption>image from Screen Rant</figcaption></figure><p>In the world of <em>Solo Leveling</em>, Sung Jin-Woo starts as the “World’s Weakest Hunter.” He is an E-rank nobody who gets injured in the easiest dungeons. But by the end of the series, he is the Shadow Monarch, a being capable of challenging gods.</p><p>Most developers feel like the E-rank Jin-Woo when they write their first line of code. The error logs are red, the IDE is confusing, and the “bugs” hit harder than a dungeon boss.</p><p>But unlike the other hunters in the series who are stuck with their rank forever, software engineers have the unique ability of the “Player.” We can level up.</p><p>Here is how you can apply the philosophy of the Shadow Monarch to your engineering career.</p><h3>1. The Daily Quest: Consistency Over Intensity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OBx2dTEqZm0vwiEo" /><figcaption>image from GameRant</figcaption></figure><blockquote><strong><em>[QUEST INFO]</em></strong><em> </em><strong><em>Goal:</em></strong><em> 100 Push-ups, 100 Sit-ups, 10km Run.</em></blockquote><blockquote><strong><em>Reward:</em></strong><em> Status Recovery, Ability Points.</em></blockquote><blockquote><strong><em>Penalty:</em></strong><em> Transfer to the Penalty Zone.</em></blockquote><p>Before Jin-Woo became powerful, the “System” forced him to do the basics every single day. If he skipped a day, he was punished.</p><p>In engineering, we often look for shortcuts. We want to build the complex AI wrapper or the flashy UI animation before we understand how memory management works. We try to sprint before we can crawl.</p><p><strong>The Lesson:</strong> You cannot become a Senior Engineer in a single week of “crunch time.” You become one through the “Daily Quest.”</p><ul><li>Solving one LeetCode problem a day.</li><li>Start asking your self with why and how?</li><li>Reading one technical article with your morning coffee.</li><li>Refactoring one small piece of legacy code.</li></ul><p>Consistency is the only way to escape the “Penalty Zone” of technical debt and burnout.</p><h3>2. The Dungeon of Iteration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*eR99F8xN_26i36O0.gif" /></figure><p>Once Jin-Woo received his powers, he didn’t immediately challenge the Demon King. He went into “Instance Dungeons” — isolated environments where he could fight, fail, and fight again without real-world consequences. He repeated these dungeons until the mechanics became second nature.</p><p><strong>The Lesson:</strong> As engineers, we often fear repetition. We want to write the perfect code on the first try. But the best code is born from iteration.</p><ul><li><strong>E-Rank Mindset:</strong> Writes the code once, prays it works, and pushes it.</li><li><strong>S-Rank Mindset:</strong> Writes a solution (The MVP), realizes it’s inefficient (The Defeat), and refactors it immediately (The Awakening).</li></ul><p>Don’t be afraid to throw away code. Every time you delete a block of code and rewrite it cleaner, you have just cleared a dungeon floor.</p><h3>3. The “Arise” Protocol: Lean on Your Army</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*SzrrGa7b3y5lQj6r.gif" /><figcaption>gif from Sungsuhofyp</figcaption></figure><p>This is perhaps the biggest difference between a Junior Developer and a Staff/Principal Engineer.</p><p>When Sung Jin-Woo fights normal enemies (goblins, orcs, knights), he doesn’t swing his dagger. He simply says <strong>“Arise.”</strong> He summons his shadow army to handle the volume.</p><p>However, when he fights a monarch or a catastrophic threat, he recalls his army and fights the boss <strong>himself</strong>, 1-on-1.</p><p><strong>The Lesson:</strong> many engineers try to fight every battle manually. They manually test the app every time. They manually fix formatting errors. They manually deploy to the server. They are exhausted fighting goblins.</p><p>Senior engineers build an army to fight the goblins for them:</p><ul><li><strong>CI/CD Pipelines:</strong> Your shadow soldiers that deploy the app for you.</li><li><strong>Unit Tests:</strong> Your shadow assassins that checks for bugs fast so you don’t have to.</li><li><strong>Linters/Formatters:</strong> Your shadow guards that keep the code clean.</li></ul><p><strong>Automate the easy fights (the goblins) so you have the energy to fight the difficult problems (System Architecture, Scalability, Security) yourself.</strong></p><h3>4. Itemization: Don’t Be a “Weapon” Fanboy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*kPt9DvjS9Fsvzk6b.gif" /><figcaption>gif from pinterest</figcaption></figure><p>Throughout the series, Jin-Woo switches weapons based on the enemy he is fighting. He uses <em>Kasaka’s Venom Fang</em> when he needs paralysis and speed effects, but switches to the <em>Demon King’s Daggers</em> or raw magic when he needs brute force. He never forces a single weapon to work for every situation just because he likes it.</p><p><strong>The Lesson:</strong> Many developers fall into the trap of being a “Framework Fanboy.”</p><ul><li>“I only use React Native for everything.”</li><li>“I will use Clean Architecture even for a simple To-Do List app.”</li></ul><p>This is like using a legendary war hammer to kill a fly. It works, but it’s exhausting and inefficient.</p><p>An S-Rank Engineer is pragmatic. They choose the tool that fits the problem. Sometimes you need a complex microservices architecture (The Demon King’s Dagger), and sometimes you just need a simple script (The Basic Dagger).</p><p><strong>Don’t get attached to the tools. Focus on the victory.</strong></p><h3>Conclusion: You Are The Player</h3><p>In <em>Solo Leveling</em>, the tragedy is that most hunters cannot grow. An E-rank stays an E-rank.</p><p>In Software Engineering, that rule does not apply. You have the “System.” You have the ability to distribute your stats. You can put points into Intelligence (Backend), Agility (Frontend), or Wisdom (Architecture).</p><p>The dungeon is open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jbXXSJonfgY_Te69" /></figure><p><strong>Arise.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a06eb9e1a817" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Concurrency: The Parental Guide]]></title>
            <link>https://medium.com/is-a-code/swift-concurrency-the-parental-guide-b229886fc72e?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/b229886fc72e</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 10:29:57 GMT</pubDate>
            <atom:updated>2025-12-19T12:34:07.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HtYglZK2Syyhl5uNv1nnUg.png" /></figure><blockquote>Why your Tasks need a curfew, a chaperone, and a strict bedtime.</blockquote><p>For the last decade, iOS developers treated background threads like latchkey kids.</p><p>We used DispatchQueue.global().async, firing closures into the void. We didn’t know when they would finish. We didn’t know if they would crash. We just gave them a [weak self] — which is basically the engineering equivalent of handing a child a sandwich and saying, “Good luck, don’t die” — and hoped for the best.</p><p>This was the era of <strong>Unstructured Concurrency.</strong> It was the Wild West. It was the reason half your crash logs were “Index out of range” on a generic background thread.</p><p>Swift 5.5 (and now the draconian strictness of Swift 6) introduced <strong>Structured Concurrency.</strong> The keyword here isn’t “Concurrency”; it’s <strong>Structure</strong>.</p><p>Here is the mental model you need to master the modern runtime: <strong>You are no longer a Dispatcher. You are a Parent.</strong> And it’s time to start grounding your children.</p><h4>1. The Golden Rule: Children Cannot Outlive Parents</h4><p>In the old GCD world, if a ViewController was dismissed, its background network requests kept running. They wasted battery, parsed JSON for no reason, and then tried to update a label that no longer existed. This is called “The Zombie Apocalypse.”</p><p>In <strong>Structured Concurrency</strong>, the hierarchy is strict.</p><p>When a function (The Parent) spawns child tasks (using async let or TaskGroup), the function <strong>cannot return</strong> until all children have finished or have been cancelled.</p><p><strong>The Code Metaphor:</strong></p><pre>func loadUserProfile() async throws -&gt; Profile {<br>    // 1. Spawn two children. They run in parallel.<br>    async let userData = api.fetchUser()<br>    async let preferences = api.fetchPreferences()<br><br>    // 2. The Parent waits here. <br>    // It&#39;s like a Dad waiting in the car. <br>    // &quot;We are NOT leaving until your brother finishes his JSON parsing!&quot;<br>    return Profile(user: try await userData, prefs: try await preferences)<br>}</pre><p><strong>The Senior’s Take:</strong> This eliminates Zombie Tasks. If the user swipes back on the navigation stack, the system cancels the parent. This automatically propagates the signal to every child, grandchild, and HTTP request down the tree.</p><p>If Mom leaves the grocery store, she drags the kids with her. She doesn’t leave Timmy in the cereal aisle (Memory Leak) to fend for himself.</p><h4>2. Unstructured Tasks: The “Emancipated Teenagers”</h4><p>Sometimes, you need to start a task from a context that isn’t async, like a SwiftUI Button or viewDidLoad.</p><p>This is where Task { ... } comes in.</p><ul><li><strong>It inherits the context:</strong> If you call it from @MainActor, the code inside runs on the Main Actor.</li><li><strong>But it breaks the lifecycle: </strong>It is <strong>Unstructured</strong>. It does <em>not</em> wait the parent function to finish.</li></ul><pre>Button(&quot;Login&quot;) {<br>    // This is an emancipated task. <br>    // It lives on even if the Button is destroyed.<br>    Task { <br>        await viewModel.login()<br>    }<br>}</pre><p><strong>⚠️ The “Runaway” (Detached Tasks)</strong> Then there is Task.detached. This is the rebellious teenager who changes their name, moves to a commune, and refuses to answer your texts.</p><ul><li>It inherits <strong>nothing</strong> (no Actor, no Priority, no Local Variables).</li><li><strong>Senior’s Advice:</strong> 99% of the time, you don’t need this. If you think you need this, you are probably wrong. Use it only for analytics or logging that must survive a crash.</li></ul><p><strong>3. The </strong><strong>.task Modifier: The Automatic Leash</strong></p><p>In the early dats of SwiftUI, we used onAppear. onAppear is irresponsible. It starts a task, but it doesn’t stop it. If the user navigates away 0.5 seconds later, that task is still running, downloading data for a screen that no longer exists.</p><p>You had to manually cancel it in onDisappear. But let’s be honest: you forgot. We all forgot.</p><p>Enter the .task modifier.</p><p><strong>The Metaphor: </strong>This is a <strong>child on a leash</strong>. the .task modifier creates a task that matches the lifecycle of the View.</p><ul><li><strong>View Appears:</strong> The Task starts.</li><li><strong>View Disappears:</strong> The Task is automatically cancelled.</li></ul><pre>Text(&quot;Profile&quot;)<br>    .task {<br>        // This runs automatically when the view appears.<br>        // If the user swipes back, this line is cancelled immediately.<br>        await viewModel.loadData()<br>    }</pre><p><strong>The Senior’s Take: </strong>Stop using onAppear { Task { ... } }. It’s the “leaving your kid at the mall” of code. Use .task. It cleans up after itself.</p><h4>4. Actors: The Bathroom Door Strategy</h4><p>In the old days, we protected shared variables with NSLock or serial DispatchQueues. But developers are human, and humans forget to lock things.</p><p><strong>Actors</strong> are classes that lock their own doors automatically.</p><p><strong>The Metaphor: </strong>Imagine a bathroom (The Shared State).</p><ul><li><strong>Classes</strong> are like a public restroom with no lock. Two threads can walk in at the same time. This results in a “Data Race” (and a very awkward situation).</li><li><strong>Actors</strong> are bathroom with a heavy steel door and bouncer.</li><li>If Thread A is inside using the data, Thread B must wait outside (await).</li></ul><pre>actor BankAccount {<br>    private var balance: Double = 0<br>    <br>    func deposit(_ amount: Double) {<br>        // Only one thread can be running this line at a time.<br>        // The compiler guarantees it. <br>        // No more &quot;oops I accidentally gave you two million dollars.&quot;<br>        balance += amount<br>    }<br>}</pre><p><strong>The “Reentrancy” Prank: </strong>The bouncer lets you in. But if you say “Hold on, I need to check the network” (await), you <strong>give up your seat</strong>. While you are waiting for the network, the bouncer might let someone else in.</p><ul><li><strong>The Joke: </strong>You enter the bathroom, put your toothbrush down, and leave to get a towel (await), you <strong>give up your seat.</strong> When you come back, your toothbrush is gone and the walls are painted blue.</li><li><strong>The Rule:</strong> Never assume the state remains the same after an await.</li></ul><h4>5. AsyncStreams: The Child Who Won’t Stop Talking</h4><p>One of the most dangerous patterns in concurrency is the <strong>Infinite Loop.</strong></p><p>In the world of Combine, we had pipelines. In Swift Concurrency, we have AsyncSequence (or AsyncStream). You consume them with a for-await-in loop.</p><p><strong>The Metaphor: </strong>Imagine a child telling you a story that never ends. “<em>And then I went to the park, and then I saw a dog, and then…”</em></p><p>If you walk out of the room (Cancel the Task), you expect the child to stop talking. But if you aren’t careful, the child keeps talking to the empty wall (wasting CPU).</p><p><strong>The Cancellation Contract: </strong>Swift’s cancellation is <strong>cooperative.</strong> The system doesn’t kill your thread (that would be rude and unsafe). It just holds up a sign that says <em>“Please Stop.” </em>It is your job to look at the sign.</p><pre>AsyncStream { continuation in<br>    let token = externalSystem.startUpdates { data in<br>        continuation.yield(data)<br>    }<br>    <br>    // THE IMPORTANT PART:<br>    // When the listener walks away (Task cancelled), do this:<br>    continuation.onTermination = { _ in<br>        externalSystem.stopUpdates(token)<br>        print(&quot;Okay, I&#39;ll stop talking now.&quot;)<br>    }<br>}</pre><p><strong>The Rule:</strong> If you create a stream, clean it up. If you consume a stream, make sure your loop checks for cancellation. Don’t let your app talk to itself in the background.</p><h4>6. Sendable: The “TSA Agent”</h4><p>This is what causes the Swift 6 warnings that make grown men cry.</p><p>The runtime needs to know: <strong>“Is it safe to move this object from the Main Thread to a Background Thread?”</strong></p><ul><li><strong>Value Types (Structs/Enums):</strong> Safe. They are copies. If I give you a photocopy of my homework, you can’t scribble on my original.</li><li><strong>Reference Types (Classes): </strong>Unsafe. If I give you the address to my house, you might come over and rearrange my furniture while I’m sleeping.</li></ul><p><strong>The Rule:</strong> You can only pass “Safe” items (Sendable) across Actor boundaries.</p><ul><li><strong>Sendable:</strong> Int, String, struct, actor.</li><li><strong>Not Sendable: </strong>class ViewModel, var properties, closures that capture mutable state.</li></ul><p><strong>The Reality: </strong>If you try to pass a non-thread-safe class into a Task, the compiler acts like a TSA agent. It doesn’t care that “it’s just a small water bottle.” It doesn’t care that “you promise not to drink it.”</p><p>If it’s not on the list, it’s not flying.</p><h3>Summary: The New House Rules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKKIQYKIIt3g1_-eu38C1Q.png" /></figure><p><strong>The Takeaway:</strong> Swift Concurrency isn’t just a new syntax. It’s a parenting philosophy. Raise your Tasks right, and they won’t grow up to crash your app in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b229886fc72e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/is-a-code/swift-concurrency-the-parental-guide-b229886fc72e">Swift Concurrency: The Parental Guide</a> was originally published in <a href="https://medium.com/is-a-code">Is a code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Silent Killers: Why Logic Tests Are Not Enough]]></title>
            <link>https://medium.com/@dev.finnchristoffer/the-silent-killers-why-logic-tests-are-not-enough-218c66d1b191?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/218c66d1b191</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 10:32:11 GMT</pubDate>
            <atom:updated>2025-11-28T10:32:11.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*5xe4XnqwjdIanirV" /></figure><blockquote>you checked that 2 + 2 = 4, but you forgot to check if the “Buy” button is covered by the keyboard or if your app is slowly bleeding memory.</blockquote><p>In my previous post, I discusses how to write robust, behavior-driven logic tests.</p><p>But here is a hard truth: <strong>Users don’t care about your logic.</strong></p><p>Users don’t care that you used a perfectly abstract VIPER architecture / MVVM + Clean Architecture. They don’t care that your unit tests have 100% code coverage.</p><p>They care that the “Buy” button is actually visible and not covered by a tab bar. They care that the text doesn’t look broken on their old iPhone SE. And they <em>certainly</em> care if their phone gets hot enough to fry an egg because your app leaks memory like a sieve.</p><p>You can have perfect ViewModels and still ship a broken, crashing app.</p><p>To operate at a Next level, we need to move beyond XCTAssertEqual. We need to automate the verification of the <strong>Visual</strong> (Snapshot Testing) and the <strong>Invisible</strong> (Memory Leak Tracking).</p><p>Here is how to bake these into your workflow so you never ship a UI regression or a retain cycle again.</p><h3><strong>Part 1: Snapshot Testing (The “Eyeball” Check)</strong></h3><p>We’ve all been there.</p><p>You refactor a complex UIView. You run it on your iPhone 15 Pro simulator. It looks beautiful. You feel like a genius. You push the code.</p><p>Ten minutes later, your QA engineer (or worse, your boss) sends you a screenshot from an iPhone SE or an iPad in Split View. Your beautiful label is truncated to “Subm…”, the layout is shattered, and the button is un-clickable.</p><p><strong>Manual UI testing is a lie we tell ourselves.</strong> It is slow, boring and humans are terrible at spotting 1-pixel regressions.</p><p><strong>The Solution: Snapshot Testing</strong></p><p>A Snapshot Test renders a UI component, takes a screenshot, and save it as a “Golden Master” reference image on your disk. The next time the test runs, it takes a <em>new </em>screenshot and compares it pixel-by-pixel.</p><p>If they differ by even 1%, the test fails.</p><p><strong>The Minimalist Approach (Dependency-Free)</strong></p><p>You <em>can </em>use large 3rd-party libraries for this (like Point-Free’s excellent library). But as a Next level Engineer, I often advocate for <strong>dependency minimalism.</strong> You don’t always need a heavy package just to compare two images.</p><p>The mechanism is actually simple:</p><p><strong>Render Layer -&gt; Convert to PNG -&gt; Compare Byte Buffers.</strong></p><p>I use a lightweight, native extension that you can drop into any project without adding a package dependency.</p><p>👉🏻 <a href="https://gist.github.com/finnchristoffer/d5dd6e15869c5f5360d16625c4767df3">You can grab my 80-line Snapshot Extension here (GitHub Gist)</a> 👈🏻</p><h4>⚠️ Important Implementation Notes</h4><p>Before you copy-paste that code, be aware of two “Gotchas” that usually trip developers up:</p><ol><li><strong>You must disable Sandboxing </strong>By default, Xcode blocks Unit Tests from writing files to your project folder (where the snapshots need to live). You need to allow this:<br>- Go to <strong>Build Settings</strong> for your <strong>Test Target.<br>- </strong>Search for <strong>“User Script Sandboxing”</strong> (ENABLE_USER_SCRIPT_SANDBOXING).<br>- Set it to <strong>NO.</strong></li><li><strong>The Record vs. Assert Workflow</strong> You can’t test against a snapshot that doesn’t exist yet. The first time you write a test, you are in “Record Mode.”</li></ol><pre>func test_LoginView() {<br>    let view = LoginView()<br>    <br>    // STEP 1: Run this ONCE to save the &quot;Golden Master&quot; to disk.<br>    // This will fail the test but save the image to your folder.<br>    record(snapshot: view.asImage(), named: &quot;Login_Idle&quot;)<br>    <br>    // STEP 2: Comment out &#39;record&#39; and switch to &#39;assert&#39;.<br>    // assert(snapshot: view.asImage(), named: &quot;Login_Idle&quot;)<br>}</pre><blockquote>💡<em>Pro-Tip: When the design changes intentionally, just swap back to </em><em>record for one run to update the reference images.</em></blockquote><p><strong>The Strategy: Test <em>States</em>, Not Just Views</strong></p><p>Whether you use my extension or a library, the value comes from <strong>combinatorial testing</strong>.</p><pre>func test_LoginView_snapshots() {<br>    let view = LoginView(state: .idle)<br>    <br>    // 1. The Standard Check (The Happy Path)<br>    assert(snapshot: view.asImage(), named: &quot;Login_Idle&quot;)<br>    <br>    // 2. The &quot;Oh No&quot; Check (Long text, error state)<br>    // This catches the issues that break layouts on small screens.<br>    let errorView = LoginView(state: .error(&quot;Invalid credentials provided. Please try again.&quot;))<br>    assert(snapshot: errorView.asImage(), named: &quot;Login_Error&quot;)<br>    <br>    // 3. The &quot;Vampire&quot; Check (Dark Mode)<br>    // Ever seen black text on a black background? It happens.<br>    var darkTraits = UITraitCollection(userInterfaceStyle: .dark)<br>    assert(snapshot: view.asImage(traits: darkTraits), named: &quot;Login_Dark&quot;)<br>}</pre><p>Now, if a junior engineer accidentally changes the padding from 16 to 8, or breaks the layout constraints, the CI pipeline fails immediately. <strong>You don’t need to open the simulator.</strong> The robot did it for you.</p><h3><strong>Part 2: Memory Leak Tracking (The “Invisible” Check)</strong></h3><p>Memory leaks (Retain Cycles) are the silent killers of iOS apps.</p><p>They don’t crash the app while you’re debugging. They wait until the use has been scrolling their feed for 15 minutes, enjoying your app, and then — <em>BAM — </em>the OS kills the process.</p><p>The user thinks your app is buggy trash. The logs just say “Terminated due to memory pressure.” It’s a ghost story, and you’re the victim.</p><p><strong>The “Deadly Embrace”</strong></p><p>This usually happens because Object A holds a strong reference to Object B, and Object B holds a strong reference back to Object A. Neither will ever let go, and they will drag your app’s performance down to hell together.</p><p>Most developers rely on <strong>Instruments</strong> to find leaks. The problem? <strong>Instruments is reactive. </strong>You only open it <em>after</em> you suspect a problem.</p><p><strong>The Automated Solution</strong></p><p>We can add a check to the tearDown phase of every unit test. When a test finishes, the System Under Test (SUT) <em>should</em><strong><em> </em></strong>be deallocated. If it isn’t, something is holding onto it.</p><p>I add this helper to every project I develop:</p><pre>extension XCTestCase {<br>    func trackForMemoryLeaks(_ instance: AnyObject, file: StaticString = #filePath, line: UInt = #line) {<br>        // This block runs *after* the test finishes<br>        addTeardownBlock { [weak instance] in<br>            // If &#39;instance&#39; is still alive here, it leaked!<br>            XCTAssertNil(<br>                instance, <br>                &quot;Instance should have been deallocated. Potential memory leak.&quot;, <br>                file: file, <br>                line: line<br>            )<br>        }<br>    }<br>}</pre><p><strong>Applying It</strong></p><p>This is why I always use the makeSUT factory pattern mentioned in my previous article. It’s the perfect place to inject this check.</p><pre>func makeSUT() -&gt; (sut: LoginViewModel, service: MockAuthService) {<br>    let service = MockAuthService()<br>    let sut = LoginViewModel(service: service)<br>    <br>    // One line of code here protects the entire feature forever.<br>    trackForMemoryLeaks(sut)<br>    trackForMemoryLeaks(service)<br>    <br>    return (sut, service)<br>}</pre><p>Now, if you accidentally write self.service.onComplete = { self.doSomething() } without [weak self], <strong>your unit test will fail.</strong></p><p>You catch the leak milliseconds after writing it, not weeks later in production.</p><h3><strong>The “Holistic” Test Suite</strong></h3><p>If you combine these three pillars, you achieve true confidence:</p><ol><li>Behavior Tests (Unit): Does the feature work? (Logic is correct).</li><li>Snapshot Tests (UI): Does the feature look right? (Layout is correct).</li><li>Leak Tests (Memory): Is the feature clean? (Resource usage is correct).</li></ol><p>This is the difference between “Code Coverage” and “Product Quality.” Code coverage is a vanity metric. A test suite that guarantees your app won’t look broken or crash from OOMs is a competitive advantage.</p><p><strong>Next Steps:</strong> Now that we have the theory and the safety net, we are ready to speed up. In the next article, I will show you how to use <strong>AI</strong> to generate these tests for you — turning this rigorous quality standard into a lightning-fast workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=218c66d1b191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing Fragile Tests: A Senior’s Guide to Sustainable TDD]]></title>
            <link>https://medium.com/@dev.finnchristoffer/stop-writing-fragile-tests-a-seniors-guide-to-sustainable-tdd-47958f4e0d03?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/47958f4e0d03</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 07:09:10 GMT</pubDate>
            <atom:updated>2025-11-20T07:09:10.425Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How to write tests that document your code, catch bugs, and — most importantly — don’t break every time you refactor.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jO4lXEteQUAYVao6.png" /></figure><p>The biggest lie in software engineering is “I don’t have time to write tests.” The truth is, you don’t have time to debug the same regression for the third time.</p><p>However, there is a <em>“wrong way”</em> to do TDD.</p><p>I see many teams abandon testing not because the <em>concept</em> is bad, but because their <em>execution</em> makes the tests fragile, slow, and painful to maintain. If you spend more time fixing broken tests than writing new features, your test suite has become a liability, not an asset.</p><p>As a Senior Engineer, my goal isn’t just “code coverage.” It’s <strong>maintainability. </strong>Here are the battle-tested patterns I use to keep test suites robust, fast, and valuable.</p><h4><strong>1. The Golden Rule: Test Behavior, Not Implementation</strong></h4><p>This is the #1 mistake I see in code reviews.</p><ul><li><strong>Implementation Testing: </strong>Checking <em>how</em> the code works (private variables, specific internal method calls).</li><li><strong>Behavior Testing:</strong> Checking <em>what</em> the code does (public output, side effects).</li></ul><p><strong>The Trap:</strong> If you test that viewModel.dataArray has 3 items, and then you refactor dataArray to be a Set, your test breaks. The feature still works, but the test failed. This is a “Fragile Test.”</p><p><strong>The Fix: </strong>Test the<em> public outcome</em>.</p><pre>// ❌ BAD: Testing Implementation details<br>func test_loading_setsBoolean() {<br>    let vm = ViewModel()<br>    vm.loadData()<br>    <br>    // Fragile! We might rename this property or change how we store state.<br>    XCTAssertTrue(vm.isLoading) <br>}<br><br>// ✅ GOOD: Testing Behavior (State/Output)<br>func test_loading_emitsLoadingState() {<br>    let (sut, spy) = makeSUT()<br>    <br>    sut.loadData()<br>    <br>    // We don&#39;t care about internal booleans. <br>    // We care that the View was told to show a spinner.<br>    XCTAssertEqual(spy.receivedStates, [.loading]) <br>}</pre><p><strong>2. The </strong><strong>makeSUT Factory Pattern</strong></p><p>Never initialize your System Under Test (SUT) directly inside a test method.</p><p>If you write let vm = LoginViewModel(service: auth) in 50 different test, and then you add a new dependency to that ViewModel, <strong>you have to update 50 tests.</strong></p><p>Instead, use a factory helper method. This is also the perfect place to bake in <strong>automatic memory leak tracking.</strong></p><pre>// The &quot;Factory&quot; Helper<br>// Put this at the bottom of your XCTestCase<br>func makeSUT(file: StaticString = #filePath, line: UInt = #line) -&gt; (sut: LoginViewModel, service: MockAuthService) {<br>    let service = MockAuthService()<br>    let sut = LoginViewModel(service: service)<br>    <br>    // ✨ The Principal Trick: Automatic Leak Detection<br>    trackForMemoryLeaks(sut, file: file, line: line)<br>    trackForMemoryLeaks(service, file: file, line: line)<br>    <br>    return (sut, service)<br>}<br><br>// The Leak Tracking Helper (put this in a global XCTestCase extension)<br>func trackForMemoryLeaks(_ instance: AnyObject, file: StaticString, line: UInt) {<br>    addTeardownBlock { [weak instance] in<br>        // If the instance is not nil after the test finishes, it leaked.<br>        XCTAssertNil(instance, &quot;Instance should have been deallocated. Potential memory leak.&quot;, file: file, line: line)<br>    }<br>}</pre><h4>3. Naming is Documentation</h4><p>If a test fails, I shouldn’t have to read the code to know what broke. The name should tell me everything.</p><p><strong>Avoid:</strong> testLogin(), testFailure(), testWorks()</p><p><strong>Adopt: </strong>test_[Action]_[Condition]_[ExpectedResult]</p><ul><li>test_login_withEmptyPassword_showError()</li><li>test_fetchData_onNetworkError_showsRetryButton()</li><li>test_init_startsInIdleState()</li></ul><p>When you run your test suite in Xcode, these names form a readable list of requirements. It effectively becomes the documentation for your feature.</p><h4>4. Avoid “Mocking Everything”</h4><p>Mocks are necessary, but over-mocking creates a “fantasy world” where your tests pass but the app crashes.</p><ul><li><strong>Mock the Boundaries:</strong> Network, Database, Analytics, Location Service. (Things that are slow, flaky, or expensive).</li><li><strong>Use Real Objects for Logic:</strong> Entities, Value Objects (structs), Helpers, pure functions.</li></ul><p>If you are creating a Mock for a simple User struct or a DateFormatter helper, you are over-complicating things. Use the real thing. It’s faster, easier to debug, and more realistic.</p><h4>5. The “Spy” Pattern for Closures/Delegates</h4><p>Don’t use XCTestExpectation unless you are testing <em>actual</em> asynchronous code (like a real network delay). wait() slows down your test suite.</p><p>For closures, Combine publishers, or delegates, use a <strong>Spy</strong>.</p><pre>class ViewStateSpy {<br>    // Captures the history of what happened<br>    var receivedStates: [ViewState] = []<br>    <br>    func render(_ state: ViewState) {<br>        receivedStates.append(state)<br>    }<br>}<br><br>func test_flow() {<br>    let (sut, spy) = makeSUT()<br>    <br>    sut.load()<br>    sut.retry()<br>    <br>    // Verify the *sequence* of events instantly, without waiting.<br>    // This runs synchronously on the CPU.<br>    XCTAssertEqual(spy.receivedStates, [.loading, .error, .loading])<br>}</pre><h4>6. Structure: Given, When, Then (AAA)</h4><p>Visually separate your test into three distinct blocks. This makes them scannable and ensures you aren’t mixing setup with assertions.</p><pre>func test_selection_updatesService() {<br>    // 1. GIVEN (Arrange)<br>    let (sut, service) = makeSUT()<br>    let user = User(name: &quot;John&quot;)<br>    <br>    // 2. WHEN (Act)<br>    sut.select(user)<br>    <br>    // 3. THEN (Assert)<br>    XCTAssertEqual(service.selectedUserID, &quot;John&quot;)<br>}</pre><h4>7. refactoring is Part of the Cycle</h4><p>The TDD cycle is <strong>Red -&gt; Green -&gt; Refactor</strong>. Most engineers stop at Green.</p><p>The “Refactor” step applies to <strong>Test Code</strong> too.</p><ul><li>Do you have duplicated setup code? Move it to makeSUT.</li><li>Do you have complex assertions? Create a custom assertion: assert(sut, renders: .error).</li><li>Is the test hard to read? Simplify the mock data.</li></ul><p>Treat your test code with the same respect as your production code. It is the safety net that protects your product.</p><h4><strong>What’s Next?</strong></h4><p>Mastering these patterns is the prerequisite for modern iOS engineering. Once you understand <em>how </em>to structure a robust test, you open the door to massive efficiency gains.</p><p>In my next post, I will explore how we can feed these specific patterns-like makeSUT and Spy classes — into <strong>AI tools</strong> to generate high-quality, leak-proof test suites in seconds.</p><blockquote>But remember: AI can write the code, but only <em>you</em> can define the architecture.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47958f4e0d03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Class vs. Struct vs. Actor: A Senior Guide to State and Identity]]></title>
            <link>https://medium.com/@dev.finnchristoffer/class-vs-struct-vs-actor-a-senior-guide-to-state-and-identity-7dca6118c0db?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dca6118c0db</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 06:32:40 GMT</pubDate>
            <atom:updated>2025-11-17T06:32:40.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsGY2SKfkLdo7A11nHISAA.png" /></figure><p>If you ask a junior developer the difference between a class and struct, they’ll say, “One is a reference type, the other is a value type.”</p><p>They’re not wrong, but they’re missing the point.</p><p>That’s the <em>mechanism</em>. It’s not the <em>implication</em>. As a senior engineers, our job is to think about the architectural implications of our decisions. The choice between these three keywords in one of the most fundamental architectural decisions you’ll make in Swift.</p><blockquote>It’s not a question of <em>what </em>they are. It’s a question of <em>how you need your data to behave</em>.</blockquote><p>Let’s break this down from a systems-level perspective.</p><h3>1. The struct: <strong>The Power of Values</strong></h3><p>A struct is a value type. This means it has no <em>identity</em>.</p><p>Think of the number 5. If you have a 5 and I have a 5, are they different? No. They are indistinguishable. They are <em>values</em>. A struct is just a compound value. A CGPoint(x: 10, y: 10) is identical to every other CGPoint(x: 10, y: 10).</p><p>This simple fact has profound consequences.</p><p>Why You Should Default to struct</p><ul><li><strong>Zero Concurrency Risk:</strong> You cannot create a data race with a struct. It’s impossible. When you pass a struct to another thread (or another function), you are passing a <em>copy</em>. They have their own independent value. There is no shared memory to protect. This is the single safest, simplest, and highest-performance way to manage concurrent data.</li><li><strong>Predictable State (No Side Effects):</strong> When you pass a struct to a method, you are 100% guaranteed that the method cannot change <em>your</em> instance of it. It can only change its <em>copy</em>. This eliminates an entire, massive class of bugs related to “action at a distance” where one object unexpectedly changes another. This makes your code testable, verifiable, and easy to reason about.</li><li><strong>Performance (Stack vs. Heap):</strong> This is the big one. struct are typically allocated on the stack, which is computationally trivial (just moving a stack pointer). class are allocated on the heap, which is far more expensive. Heap allocation requires finding free memory, running malloc, and managing its lifecycle.</li><li><strong>No Reference Counting Overhead:</strong> Every time you pass a class instance around, Swift has to perform atomic increments/decrements on its reference count (ARC). This is a hidden performance cost that adds up. struct don’t have this. They are copied, which thanks to <strong>Copy-on-Write (CoW)</strong> for collections, is often just as fast (or faster) than ARC.</li></ul><p><strong>My Principle: Start with </strong>struct<strong> for everything. </strong>Your models, your view states, your configurations. Use it until you have a specific, <em>compelling </em>reason to use something else.</p><h3>2. The class: The Burden of Identity</h3><p>A class is a <strong>reference type</strong>. This means its <em>does</em> have <strong>identity.</strong></p><p>Think of a Person. If you and I are both referring to “Bob,” we are referring to the <em>same</em>, <em>unique individual. </em>If you change Bob’s last name, I see that change because we are <em>both looking at the same Bob</em>. A class is a pointer to a specific, unique “thing” on the heap.</p><p>This “shared mutability” is its single greatest feature and its single greatest danger.</p><p><strong>When to Use </strong>class <strong>(and Why It’s Dangerous)</strong></p><ul><li><strong>You Need Shared State: </strong>This is the main reason. You <em>want</em> multiple parts of your app to hold a pointer to the <em>exact same</em> <em>object</em>. When a NetworkService downloads new data, you <em>want</em> all the view models holding a reference to it to see that new data.</li><li><strong>You Need Identity:</strong> The object represents a unique entity. A UIViewController <em>must</em> be a class because its identity — its specific place in the view hierarchy and its lifecycle — is its entire purpose.</li><li><strong>The Concurrency Catastrophe:</strong> As soon as you have <em>identity</em>, you have <em>shared memory</em>. As soon as you have <em>shared memory</em> and <em>multiple threads</em>, you have data races.</li></ul><pre>// A classic data race<br>class Counter {<br>    var value = 0<br>    <br>    func increment() {<br>        // Thread A reads value (0)<br>        // Thread B reads value (0)<br>        // Thread A reads value + 1 (1)<br>        // Thread A reads value + 1 (1)<br>        // Result: value is 1, but it should be 2.<br>        value += 1<br>    }<br>}</pre><p>For decades, we solved this by hand. We wrapped value in a DispatchQueue (serial) or a DispatchBarrier (concurrent) or an NSLock. This is manual, error-prone, and hard to verify.</p><p><strong>My Principle: Use</strong> class <strong>only when you need identity, but no concurrency.</strong> The primary modern use case for class is interfacing with Objective-C or UIKit (e.g., UIViewController, UIView subclasses) which are inherently main-thread-only and don’t (or shouldn’t) face concurrent access.</p><h3>3. The actor: The Modern Solution to Identity</h3><p>An actor is a <strong>reference type with identity</strong>, just like a class. It lives on the heap. But it has one superpower: it is <strong>concurrency-safe by default.</strong></p><p>An actor solves the “shared identity” problem from the class section. It provides a built-in, language-level mechanism to protect its own state.</p><p><strong>How</strong> actor<strong> Changes Everything</strong></p><p>An actor is essentially a class that comes with its own private serial queue (or “mailbox”).</p><ol><li><strong>State Isolation: </strong><em>All </em>access to an actor&#39;s internal properties (like var value in our Counter) is isolated.</li><li><strong>External Access is Asynchronous:</strong> To access or modify an actor’s state from the “outside,” you <em>must </em>use await. This await is a <em>suspension point</em>. Your code yields the thread, and the actor schedules your request to be run as soon as it’s free.</li><li><strong>Guaranteed Safety: </strong>The complier <em>guarantees </em>that only one piece of code is running “inside” the actor at a time. Data races are <em>impossible.</em></li></ol><p>Let’s rewrite our broken Counter:</p><pre>actor Counter {<br>    var value = 0 // State is isolated<br>    <br>    // This function is &quot;inside&quot; the actor.<br>    // It can access `value` directly.<br>    func increment() {<br>        value += 1<br>    }<br><br>    // This function is also &quot;inside&quot;<br>    func getValue() -&gt; Int {<br>        return value<br>    }<br>}<br><br>// --- Somewhere else in your code ---<br>let counter = Counter()<br><br>Task {<br>    await counter.increment() // 1. Must use &#39;await&#39;<br>}<br><br>Task {<br>    await counter.increment() // 2. Must use &#39;await&#39;<br>}<br><br>Task {<br>    // 3. Must &#39;await&#39; to read the value<br>    print(await counter.getValue()) // Guaranteed to be 2<br>}</pre><p>All three tasks will safely line up, one after another, to access the counter. No locks, no queues, no races. It just <em>works</em>.</p><p><strong>My Principle: Use </strong>actor <strong>whenever you would have used a </strong>class <strong>to manage shared, mutable state. </strong>This is the new default for services, managers, repositories, and any object that needs identity <em>and</em> will be accessed from a concurrent environment (like a SwiftUI ViewModel firing off Task).</p><h3>My Decision Framework</h3><p><strong>Here is my mental model for choosing:</strong></p><ol><li><strong>START HERE: Can this be a </strong><strong>struct?</strong><br>- Is it data? A model? A configuration? A piece of transient state<br>- <strong>YES: </strong>Use a struct. Enjoy the performance, safety, and predictability. This is your default.</li><li><strong>If not, ask: Does this <em>need </em>a shared, mutable identity?</strong><br>- Is it a unique “thing” that multiple objects <em>must</em> reference (e.g., a NetworkService, a CacheManager, a CurrentUserService)?<br>- NO: Go back to struct. You’re overthinking it.<br>- Yes: Move to question 3.</li><li><strong>Ask: Will this shared “thing” be accessed from multiple threads?</strong><br>- Will it be called from a Task, a DispatchQueue, a Combine subscriber, or any async context?<br><strong>- NO:</strong> (e.g., it’s a UIViewController or a UIView that 100% main-thread-only). Use a class.<br><strong>- YES:</strong> (This is 99% of modern use cases for shared state). Use an actor. This is the robust, verifiable, and performant way to manage shared concurrent state.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dca6118c0db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond main.async: Deep Dive into GCD]]></title>
            <link>https://medium.com/@dev.finnchristoffer/beyond-main-async-deep-dive-into-gcd-32d7c12d5edb?source=rss-4ef6aec12fbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/32d7c12d5edb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Finn Christoffer Kurniawan]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 03:48:00 GMT</pubDate>
            <atom:updated>2025-11-03T03:48:00.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M010pMfeOvge2gGr1ck7Vw.jpeg" /></figure><p><strong>Why Swift Concurrency’s foundation is still one of your most powerful tools for performance and robustness.</strong></p><p>As iOS engineers, we live in an exciting era. Swift Concurrency (async/await) and Combine have given us incredible, declarative tools to manage complex asynchronous flows. It’s tempting to relegate Grand Central Dispatch (GCD) to the “legacy” bin, a tool we only touch when DispatchQueue.main.async is needed.</p><blockquote>That’s a mistake</blockquote><p>As engineer, my philosophy is that robust, high-performance system are built on a deep understanding of the full stack. Swift Concurrency is a powerful abstraction, but it’s built on top of GCD and its underlying Libdispath primitives.</p><p>Understanding GCD isn’t just for maintaining old code. It’s for debugging “impossible” race condition, for low-level performance optimization, and for making an <em>informed decision </em>about which tool is right for the job.</p><h3>Deep Dive: The Queues Themselves</h3><p>Not all queues are created equal. Where you dispatch your work is just as important as how.</p><ol><li><strong>The Main queue (</strong>dispatchQueue.main )</li></ol><p>This is the most famous queue. It is a <strong>globally available serial queue.</strong></p><ul><li><strong>Purpose: </strong>It’s the <em>only </em>queue that can safely execute UI-related code (updating UIKit or SwiftUI views).</li><li><strong>Behavior: </strong>Being <strong>serial</strong>, it executes one task at a time, in order. This is what guarantees that UI updates don’t conflict.</li><li><strong>QoS:</strong> its QoS is effectively .userInteractive .</li><li><strong>The Cardinal Sin: </strong>Never block the main queue. Don’t run sync on it, and don’t perform slow, synchronous work (like network calls or disk I/O) on it. This is what causes your app to freeze.</li></ul><p><strong>2. Global Queues </strong>(DispatchQueue.global(qos:) )</p><p>These are <strong>system-provided concurrent queues</strong> shared by your entire application (and-sometimes the whole system).</p><ul><li><strong>Purpose: </strong>This is your “work pool.” It’s where you dispatch any non-UI work.</li><li><strong>Behavior: </strong>You don’t create a global queue; you ask for one based on the <strong>QoS</strong> you need.</li><li>GCD manages a pool of thread for these queues. By providing the correct QoS, you are telling GCD <em>how</em> to prioritize your work relative to everything else.</li><li><strong>Pitfall: </strong>Never just use DispatchQueue.global(). This defaults to a QoS of .default , which is often not what you intend. Be <em>explicit</em> and choose the QoS that matches the <em>intent</em> of your work.</li></ul><p><strong>3. Custom Queues (</strong>DispatchQueue(label:...))</p><p>These are queues that <em>you</em> create, own and are responsible for. They are incredibly powerful for managing state and organizing your code. They are created <strong>serial by default.</strong></p><ul><li>Custom Serial Queues (Default)<br>- let serialQueue = DispatchQueue(label: &quot;com.myapp.dataManager&quot;) <br>- <strong>Purpose: </strong>This is the simplest, most robust way to protect a shared resource.<br><strong>- Use Case: </strong>Imagine you have an array var items: [Item] that can be accessed from multiple threads. Instead of complex locks, you can wrap all access in this serial queue.</li></ul><pre>class DataManager {<br>    private var items: [Item] = []<br>    private let queue = DispatchQueue(label: &quot;com.myapp.dataManager&quot;)<br><br>    func addItem(_ item: Item) {<br>        queue.async {<br>            // This is guaranteed to be the only code<br>            // accessing `self.items` at this time.<br>            self.items.append(item)<br>        }<br>    }<br>}</pre><p>Since all access is funneled through this single-file line (the serial queue), race conditions become impossible.</p><ul><li><strong>Custom Concurrent Queues</strong><br>- let concurrentQueue = DispatchQueue(label: &quot;com.myapp.imageLoader&quot;, attributes: .concurrent)<br><strong>- Purpose:</strong> This allows you to group related tasks and run them in parallel, but it’s most powerful when used as the foundation for the <strong>Readers-Writer pattern</strong> with barriers.<br>- <strong>Use Case:</strong> This is what we used in the ThreadSafeCache example further down. It provides the &quot;stage&quot; for multiple reads to happen at once.</li></ul><pre>class DataManager {<br>    private var items: [Item] = []<br>    private let queue = DispatchQueue(label: &quot;com.myapp.dataManager&quot;)<br><br>    func addItem(_ item: Item) {<br>        queue.async {<br>            // This is guaranteed to be the only code<br>            // accessing `self.items` at this time.<br>            self.items.append(item)<br>        }<br>    }<br>}</pre><h3>The Core Components: More Than Just Queues</h3><p>Let’s get past the “serial vs. concurrent” definitions and talk about the intent behind the tools.</p><ol><li><strong>Quality of Service (QoS): The “Why” That Governs Everything</strong></li></ol><p>This is the most critical and most-often-abused part of GCD. QoS <strong>is not just a “priority” level.</strong> It is a semantic tag that tells the system about the intent of the work. This single piece of information influences CPU scheduling, I/O priority, thread pool management, and power consumption.</p><p>Using the wrong QoS is a primary source of performance bugs.</p><ul><li>userInteractive : <strong>The “Right Now” Task. </strong>For work blocking the user from interacting, like event handling or UI-layer animations. This work <em>must</em> be tiny and “instant.”</li><li>userInitiated : <strong>The “User is Waiting” Task. </strong>The user tapped a button and is looking at a spinner. Opening a document, loading data for the next screen.</li><li>Utility : <strong>The “In-Progress” Task.</strong> A long-running task the user is <em>aware </em>of but not actively blocked by. A background download with a progress bar, importing data.</li><li>background : <strong>The “Cleanup” Task. </strong>Maintenance work the user doesn’t even know is happening. Database indexing, cache cleanup.</li></ul><blockquote>💡 Insight: Running a complex data-parsing task at .userInteractive will cause UI stutters (frame drops). Running a UI calculation at .background will make your app feel sluggish. Be precise with your intent.</blockquote><p><strong>2. Sync vs. Async: The Sharpest Tool in the Box</strong></p><ul><li>async : Submits work and return immediately. Non-blocking. Your “go-to” 99% of the time.</li><li>sync : Submits work, blocks the current thread, and waits for the work to complete.</li></ul><p>sync is a dangerous tool. It’s useful for safely retriving a value from a serial queue, but it’s also the source of the most classing deadlock:</p><pre>// THE CLASSIC DEADLOCK:<br>// You are currently on the main thread.<br>DispatchQueue.main.async {<br>   // This block won&#39;t run until the main thread is free.<br>   // But the main thread is blocked on line 3, waiting for *this block* to finish.<br>   // -&gt; Deadlock. App frozen.<br>   print(&quot;This will never print&quot;)<br>}</pre><h3>The Power Primitives for Robust Systems</h3><p>This is where GCD moves beyond simple background work and enables complex, thread-safe patterns.</p><ol><li><strong>DispatchGroup: The “Wait for N Things” Pattern</strong></li></ol><p>DispatchGroup is your tool for tracking the completion of multiple, independent task.</p><p><strong>Use Case: </strong>you need to make three network requests (get user profile, get messages, get settings) and only update the UI <em>after all three </em>have returned.</p><pre>let group = DispatchGroup()<br>var userProfile: UserProfile?<br>var messages: [Message]?<br><br>// Task 1<br>group.enter() // Increment the group&#39;s counter<br>api.fetchProfile { result in<br>    userProfile = try? result.get()<br>    group.leave() // Decrement the counter<br>}<br><br>// Task 2<br>group.enter()<br>api.fetchMessages { result in<br>    messages = try? result.get()<br>    group.leave()<br>}<br><br>// The &quot;all done&quot; callback.<br>// This is asynchronous and non-blocking.<br>group.notify(queue: .main) {<br>    // This is guaranteed to run after both tasks have called leave()<br>    self.updateUI(with: userProfile, messages: messages)<br>}</pre><blockquote>💡 Insight: Avoid group.wait() . This <em>blocks</em> the current thread until the group is empty. Blocking is an anti-pattern that can lead to <strong>thread explosion</strong>, where GCD spawns more and more threads to try make progress, exhausting system resources.</blockquote><p><strong>2. </strong><strong>DispatchBarrier: The “Readers-Writer” Lock</strong></p><p>This is the key to building high-performance, thread-safe objects. It solves the classic “readers-writer problem” where you have many reads (which can be concurrent) but infrequent writes (which must be exclusive).</p><p><strong>Solution:</strong> Use a private .concurrent queue and dispatch your writes with the .barrier flag.</p><ol><li><strong>Reads</strong> are dispatched async (or sync) without a barrier. They can all run in parallel.</li><li><strong>Writes</strong> are dispatched async(flags: .barrier). This task:</li></ol><ul><li>Waits for all currently running read task to finish</li><li>Runs exclusively (no other task on that queue runs).</li><li>Once it’s done, the queue resumes concurrent operations.</li></ul><pre>class ThreadSafeCache&lt;Key: Hashable, Value&gt; {<br>    private var cache: [Key: Value] = [:]<br>    <br>    // 1. A private, concurrent queue acts as the lock<br>    private let queue = DispatchQueue(label: &quot;com.myapp.cacheQueue&quot;, <br>                                    attributes: .concurrent)<br><br>    // 2. Reads are concurrent (using sync for a simple return)<br>    func value(forKey key: Key) -&gt; Value? {<br>        queue.sync {<br>            self.cache[key]<br>        }<br>    }<br><br>    // 3. Writes use a barrier for exclusive access<br>    func setValue(_ value: Value, forKey key: Key) {<br>        queue.async(flags: .barrier) {<br>            self.cache[key] = value<br>        }<br>    }<br>}</pre><p><strong>3. </strong><strong>DispatchSemaphore : The “Velvet Rope”</strong></p><p>A semaphore is a concurrency primitive that limits access to a resource. It maintains a counter.</p><ul><li>wait(): Decrements the counter. If the counter is 0, it <em>blocks</em> the thread.</li><li>signal(): Increments the counter.</li></ul><p><strong>Use Case: </strong>You want to limit the number of concurrent network request to, say, 4, to avoid overwhelming the server or the device’s radio.</p><pre>// 1. Create a semaphore with a &quot;count&quot; of 4<br>let networkSemaphore = DispatchSemaphore(value: 4)<br><br>// 2. In your network layer, before *every* request:<br>func startRequest(_ request: URLRequest) {<br>    // This will block the *current queue* if 4 requests are already &quot;out&quot;<br>    networkSemaphore.wait() // Decrement count, or block<br>    <br>    // We&#39;re &quot;in.&quot; Dispatch the work.<br>    DispatchQueue.global(qos: .utility).async {<br>        let task = URLSession.shared.dataTask(with: request) { data, _, _ in<br>            // ... process data ...<br>            <br>            // 3. CRITICAL: Signal on completion (success or failure)<br>            // This increments the count and unblocks another waiting request.<br>            networkSemaphore.signal()<br>        }<br>        task.resume()<br>    }<br>}</pre><p><strong>⚠️ Warning: </strong>Semaphores are powerful but dangerous. A forgotten signal() leads to a permanent block. And, like group.wait() , semaphore.wait() blocks a thread. Use them with extreme caution.</p><p><strong>4. </strong><strong>DispatchWorkItem: The “Cancellable Task”</strong></p><p>A DispatchWorkItem wraps your closure in an object, giving you two key powers:</p><ol><li><strong>Cancellation:</strong> You can call workItem.cancel(). This is <em>cooperative,</em> in preemptive. You must check the workItem.isCancelled flag inside your task.</li><li><strong>Notification:</strong> You can chain items: workItem.notify(queue: .main) { . . . }.</li></ol><p>This was our best-effort “cancellation” before Task came along, which provides far superior, automatic cancellation.</p><h3>GCD in the Modern async/await World</h3><p>So, when do you reach these tools today?</p><p><strong>My Key takeaways:</strong></p><ol><li><strong>Default to Swift Concurrency. </strong>Write all new asynchronous code with async/await . Use Task to create units of work and Actor to protect shared state. The compiler-level safety and structured concurrency are a massive leap forward in robustness.</li><li>@MainActor <strong>is the new</strong> DispatchQueue.main. Annotate your UI-touching properties functions, and classes with @MainActor. the compiler will enforce main-thread-only access for you, which is far safer than manually dispatching.</li><li><strong>Keep GCD for what it’s best at:</strong></li></ol><ul><li>DispatchQueue.main.async: Still the simples, most direct way to hop to the main thread from a <em>non-async </em>context (like a legacy completion block or a C-API callback).</li><li>DispatchBarrier : Still a valid, high-performance pattern for the “Readers-Writer” problem. While an Actor is safer (it serializes all access), the barrier pattern can be more performant if your reads truly and safely can run in parallel.</li><li>DispatchSemaphore: When you <em>truly</em> need to limit concurrency to a specific number (e.g., N=4). An Actor serializes access, which isn’t the same as allowing N tasks at once.</li></ul><p>GCD isn’t dead. It’s the foundation. A true engineer understands the foundation to build better abstraction and to know exactly what’s happening when a Task is suspended or Actor is isolating a call.</p><blockquote>Understand the whole stack. Choose the right tool for the job.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32d7c12d5edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>