<?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 Abdallah Edres on Medium]]></title>
        <description><![CDATA[Stories by Abdallah Edres on Medium]]></description>
        <link>https://medium.com/@abdallahedres005?source=rss-44123d5ef02f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7aEahoRDV3ocSKr6</url>
            <title>Stories by Abdallah Edres on Medium</title>
            <link>https://medium.com/@abdallahedres005?source=rss-44123d5ef02f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:46:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdallahedres005/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[The Facade Pattern: Insulating App Code from AVFoundation]]></title>
            <link>https://medium.com/@abdallahedres005/the-facade-pattern-insulating-app-code-from-avfoundation-9a443168cd75?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a443168cd75</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 09:19:10 GMT</pubDate>
            <atom:updated>2026-10-28T09:19:10.148Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>What a word card actually needs</h3><p>Anywhere in WordsWarrior that wants a word pronounced out loud needs exactly one capability: “say this text.” AVSpeechSynthesizer can do that, but its actual API is a small orchestration exercise — construct an AVSpeechUtterance, configure its voice, hand it to a synthesizer instance that has to outlive the call. None of that belongs at a card view&#39;s call site, and none of it should have to be re-learned by whatever replaces AVSpeechSynthesizer if this app ever needs a different speech engine, a remote TTS service, or a test double that asserts what was spoken.</p><h3>A two-method facade over the whole framework</h3><p>SpeechServicing reduces all of that down to the one capability call sites actually need:</p><pre>// SpeechService.swift<br>protocol SpeechServicing {<br>    func speak(_ text: String)<br>}</pre><pre>final class AVSpeechService: SpeechServicing {<br>    static let shared = AVSpeechService()</pre><pre>    private let synthesizer = AVSpeechSynthesizer()</pre><pre>    func speak(_ text: String) {<br>        let utterance = AVSpeechUtterance(string: text)<br>        utterance.voice = AVSpeechSynthesisVoice(language: &quot;en-US&quot;)<br>        synthesizer.speak(utterance)<br>    }<br>}</pre><p>Every piece of AVFoundation-specific knowledge — that pronunciation requires an utterance object, that the utterance needs an explicit voice, that the synthesizer instance has to be kept alive across the async speech callback — lives inside AVSpeechService and nowhere else. A call site asks for a SpeechServicing and calls speak(_:); it has no way to reach past the facade to AVSpeechUtterance even if it wanted to, because it was never handed a reference to anything but the protocol.</p><h3>The singleton this codebase otherwise avoids</h3><p>AVSpeechService.shared is worth noticing precisely because it stands out: elsewhere in WordsWarrior, every collaborator is passed in through a constructor with a protocol type, never reached into as a .shared static. Speech synthesis breaks that convention for a concrete reason — AVSpeechSynthesizer needs to persist for the lifetime of an utterance being spoken, and constructing a fresh one per call risks the instance (and the speech with it) getting deallocated mid-utterance. A single, long-lived instance sidesteps that entirely, and the facade is precisely what makes the singleton safe to have: nothing outside SpeechService.swift ever names AVSpeechService directly, so nothing outside it depends on <em>how</em> that lifetime problem got solved. If a future version constructs it differently — injected instead of shared, one synthesizer instance shared across a pool of utterances — every call site stays exactly as it is, because they only ever depended on SpeechServicing.</p><h3>Why this earns its place</h3><ul><li><strong>The protocol names the capability, not the framework.</strong> SpeechServicing says &quot;can speak text,&quot; never &quot;wraps AVSpeechSynthesizer&quot; — a call site reading the protocol has no reason to know AVFoundation is involved at all.</li><li><strong>The singleton’s justification lives right next to the singleton.</strong> Breaking an otherwise-consistent convention is fine when the reason is written down where the exception is made, not left for the next reader to reverse-engineer.</li><li><strong>Replacing the speech engine is a one-file change.</strong> A different SpeechServicing conformance is the entire migration path — no call site, no view model, no test double needs to change shape.</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/05-notification-signature-sync.md"><strong>← Cross-Feature State Sync</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a443168cd75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Feature State Sync Without a Shared Store: NotificationCenter + Signature Diffing]]></title>
            <link>https://medium.com/@abdallahedres005/cross-feature-state-sync-without-a-shared-store-notificationcenter-signature-diffing-d1e89ccf1c4b?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e89ccf1c4b</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 08:39:41 GMT</pubDate>
            <atom:updated>2026-10-25T08:39:41.421Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 5 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>Two tabs, one shared setting, no shared object</h3><p>Home and Profile are separate tabs backed by separate coordinators and separate view models. Profile is where the user changes their studied categories or daily word count; Home is what needs to react when they do. The obvious SwiftUI answer — a shared @Observable settings object injected into both — would work, but it means introducing a cross-feature dependency neither tab otherwise has, just to carry two values. WordsWarrior reaches for something already sitting underneath both of them: UserDefaults is the actual source of truth for those settings, and UserDefaults already broadcasts a notification every time it changes.</p><h3>Listening, and refusing to over-react</h3><p>HomeDecksView listens for that notification directly, but a raw &quot;reload on every notification&quot; would be wrong for a different reason: UserDefaults posts didChangeNotification for <em>any</em> write to the suite — including writes Home&#39;s own load() makes to its own bookkeeping keys. Reloading on every notification would mean load() re-triggering itself in a loop of diminishing relevance.</p><pre>// HomeDecksView.swift<br>.onAppear {<br>    lastSettingsSignature = viewModel.settingsSignature()<br>    viewModel.load(context: modelContext)<br>}<br>.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in<br>    let signature = viewModel.settingsSignature()<br>    guard signature != lastSettingsSignature else { return }<br>    lastSettingsSignature = signature<br>    viewModel.load(context: modelContext)<br>}</pre><p>The guard is what makes this safe: every notification computes a fresh signature and compares it against the last one <em>actually acted on</em>, and only reloads when they differ.</p><h3>A fingerprint of only what matters</h3><p>The signature itself is deliberately narrow — it reads exactly the two settings load() cares about, nothing else:</p><pre>// HomeViewModel.swift<br>func settingsSignature() -&gt; String {<br>    let categories: [String] = defaults.value(forKey: OnboardingDefaultsKey.categories.rawValue) ?? []<br>    let wordsPerDay: Int = defaults.value(forKey: OnboardingDefaultsKey.wordsPerDay.rawValue) ?? 0<br>    return Set(categories).sorted().joined(separator: &quot;,&quot;) + &quot;|&quot; + String(wordsPerDay)<br>}</pre><p>Categories get sorted before joining, so a Profile screen that persists the same set of categories in a different order doesn’t register as a change. Anything Home itself writes during load() — learned-word IDs, the batch, level state — never enters the signature at all, so load()&#39;s own side effects can never trigger another load(). The comparison is cheap enough to run on every single notification without a second thought: two small reads and a string diff, not a deep equality check across view model state.</p><h3>Why not a shared observable store?</h3><p>A shared SettingsStore injected into both tabs would remove the notification entirely and arguably be more &quot;SwiftUI-idiomatic.&quot; It would also mean Home takes on a dependency for two values it currently gets for free from a mechanism — UserDefaults — it already depends on for those exact keys. The notification-plus-signature approach keeps the two tabs&#39; view models fully independent of each other; the only thing they share is the same underlying UserDefaults suite they&#39;d need to agree on either way.</p><h3>Why this earns its place</h3><ul><li><strong>No new cross-feature dependency.</strong> Home reacts to Profile’s changes without either one holding a reference to a shared object.</li><li><strong>The signature is the debouncer.</strong> Comparing a cheap fingerprint, not raw notification counts, is what stops Home’s own writes from re-triggering itself.</li><li><strong>Scoped to exactly two keys, on purpose.</strong> A signature over “everything in defaults” would reload on changes Home doesn’t care about; a signature over these two specific keys reloads only when the answer to “what should today’s batch contain” could actually have changed.</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/04-deterministic-batch-reconciliation.md"><strong>← Deterministic Batch-Selection Algorithm</strong></a> · Next: <a href="https://medium.com/06-speech-service-facade.md"><strong>The Facade Pattern →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e89ccf1c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Deterministic Batch-Selection Algorithm (No Randomness Required)]]></title>
            <link>https://medium.com/@abdallahedres005/designing-a-deterministic-batch-selection-algorithm-no-randomness-required-bfd2605ae123?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfd2605ae123</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 08:38:02 GMT</pubDate>
            <atom:updated>2026-10-25T08:38:02.023Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>Why a shuffle is the wrong tool here</h3><p>“Pick N words for today” sounds like a one-liner: shuffle the pool, take the first N. That’s exactly what breaks the moment a user reopens the app mid-session. A fresh shuffle every load() call would silently swap out words they&#39;ve already looked at but not yet dispositioned, replace a word they just saved for later with a completely different one, or hand back a different batch after a level-up even though nothing about &quot;today&quot; changed. Randomness makes &quot;today&#39;s batch&quot; mean something different every time it&#39;s computed, which is exactly the property it can&#39;t have.</p><h3>Retain, top up, trim — in that order</h3><p>nextBatch treats yesterday&#39;s batch as the starting point, not a coin flip:</p><pre>// WordRepository.swift<br>extension WordRepository {<br>    func nextBatch(from pool: [Word], catalog: [Word], previousIDs: [String], learnedIDs: Set&lt;String&gt;, pageSize: Int) -&gt; [Word] {<br>        let ordered = wordsOrderedByLevel(pool)<br>        let catalogByID = Dictionary(uniqueKeysWithValues: catalog.map { ($0.id, $0) })</pre><pre>        let retainedIDs = previousIDs.filter { catalogByID[$0] != nil }<br>        let learnedRetained = retainedIDs.filter { learnedIDs.contains($0) }<br>        var pendingRetained = retainedIDs.filter { !learnedIDs.contains($0) }</pre><pre>        if retainedIDs.count &lt; pageSize {<br>            let excluded = Set(retainedIDs).union(learnedIDs)<br>            let candidates = words(ordered, excludingIDs: excluded)<br>            let needed = pageSize - retainedIDs.count<br>            pendingRetained.append(contentsOf: candidates.prefix(needed).map(\.id))<br>        } else if retainedIDs.count &gt; pageSize {<br>            let allowedPending = max(0, pageSize - learnedRetained.count)<br>            pendingRetained = Array(pendingRetained.prefix(allowedPending))<br>        }</pre><pre>        let finalIDs = learnedRetained + pendingRetained<br>        return finalIDs.compactMap { catalogByID[$0] }<br>    }<br>}</pre><p>Three phases, always in this order:</p><ol><li><strong>Retain.</strong> Every ID from previousIDs that still exists in catalog survives — checked against the <em>catalog</em>, not the <em>pool</em>, so a word saved for later or a level-up that moves the pool&#39;s floor never evicts something already sitting in today&#39;s snapshot.</li><li><strong>Top up.</strong> If retention alone comes up short of pageSize, the level-ordered pool fills the gap, skipping anything already retained or already learned.</li><li><strong>Trim.</strong> If retention overshoots pageSize — the daily word count got turned down mid-batch — already-learned words are kept in full (they&#39;re done, no reason to re-litigate them) and only the still-pending ones get cut down to fit.</li></ol><h3>What this buys that a shuffle can’t</h3><p>A word the user already swiped “learned” on stays learned and stays in the batch, permanently, until startNewDay() explicitly clears it — learnedRetained is never trimmed, only pendingRetained is. Reopening the app, backgrounding it, rotating the device, none of it changes the answer to &quot;what are today&#39;s words,&quot; because none of those events touch previousIDs. The only two things that ever change the batch are startNewDay() (an explicit user action) and the pool actually running out of untouched words to top up with. That&#39;s the entire contract, and it&#39;s checkable by reading the function once — no hidden dependency on Int.random or a seeded generator to reason about.</p><h3>Why this earns its place</h3><ul><li><strong>Idempotent by construction.</strong> Calling nextBatch twice with the same arguments returns the same words, in the same order — a property a shuffle-based version could never have offered, seeded or not.</li><li><strong>The catalog check, not the pool check, is what protects saved-for-later words.</strong> Filtering previousIDs against catalog rather than pool is the one line standing between &quot;saved words survive a level-up&quot; and a subtle, hard-to-reproduce bug report.</li><li><strong>Trimming favors what’s already done.</strong> Keeping learnedRetained untouched and only trimming pendingRetained means shrinking the daily word count can never un-complete a word the user already finished.</li><li><strong>No randomness to seed, log, or debug.</strong> A support conversation about “why did my words change” has a one-sentence, reproducible answer instead of “let me check what the random seed was.”</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/03-singleton-row-swiftdata.md"><strong>← The Singleton-Row Pattern</strong></a> · Next: <a href="https://medium.com/05-notification-signature-sync.md"><strong>Cross-Feature State Sync →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfd2605ae123" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Singleton-Row Pattern: Modeling Global State in SwiftData]]></title>
            <link>https://medium.com/@abdallahedres005/part-3-of-6-in-the-wordswarrior-architecture-design-patterns-series-951e096b7a5b?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/951e096b7a5b</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 08:09:49 GMT</pubDate>
            <atom:updated>2026-10-25T08:33:45.418Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>A persistence framework built for collections, asked for exactly one thing</h3><p>SwiftData’s whole design centers on collections — @Model types you insert many of, query with predicates, and fetch back as arrays. WordsWarrior has one piece of state that doesn&#39;t fit that shape at all: &quot;today&#39;s daily word batch.&quot; There is never more than one. There&#39;s no natural identity to key it by — no date, no user, nothing except &quot;the current one.&quot; Reaching for UserDefaults would have been the simpler move. WordsWarrior keeps it in SwiftData anyway, modeled as a singleton row.</p><h3>Forcing exactly one row to exist</h3><p>WordBatch is a normal @Model class with one unusual detail: its unique attribute isn&#39;t an identity derived from the data, it&#39;s a hardcoded constant.</p><pre>// WordBatch.swift<br>@Model<br>final class WordBatch {<br>    @Attribute(.unique) var singletonKey: String<br>    var wordIDs: [String]</pre><pre>    init(wordIDs: [String]) {<br>        self.singletonKey = WordBatch.key<br>        self.wordIDs = wordIDs<br>    }</pre><pre>    static let key = &quot;current&quot;<br>}</pre><p>@Attribute(.unique) is normally how you&#39;d stop two rows from representing the same <em>entity</em>. Here it&#39;s repurposed to stop a second row from existing at all — every WordBatch that gets inserted has the identical singletonKey, so SwiftData&#39;s own uniqueness constraint becomes the enforcement mechanism for &quot;there can be only one.&quot; No manual &quot;check if one exists before inserting&quot; logic could be forgotten in some new call site, because the constraint lives in the schema, not in the calling code&#39;s discipline.</p><h3>Reading and writing through the same predicate</h3><p>The repository never needs to track <em>which</em> row is the singleton — it just asks for the one row whose key matches the constant:</p><pre>// WordBatchRepository.swift<br>struct SwiftDataWordBatchRepository: WordBatchRepository {<br>    func saveBatch(wordIDs: [String], context: ModelContext) {<br>        if let existing = batch(context: context) {<br>            existing.wordIDs = wordIDs<br>        } else {<br>            context.insert(WordBatch(wordIDs: wordIDs))<br>        }<br>        try? context.save()<br>    }</pre><pre>    func clearBatch(context: ModelContext) {<br>        guard let existing = batch(context: context) else { return }<br>        context.delete(existing)<br>        try? context.save()<br>    }<br>}</pre><pre>private extension SwiftDataWordBatchRepository {<br>    func batch(context: ModelContext) -&gt; WordBatch? {<br>        let key = WordBatch.key<br>        let descriptor = FetchDescriptor&lt;WordBatch&gt;(predicate: #Predicate { $0.singletonKey == key })<br>        return try? context.fetch(descriptor).first<br>    }<br>}</pre><p>saveBatch reads as an upsert — update in place if the row exists, insert if it doesn&#39;t — which is exactly the semantic &quot;today&#39;s batch&quot; needs. clearBatch deletes the row entirely rather than emptying its array, so &quot;no batch yet&quot; and &quot;batch of zero words&quot; stay genuinely distinguishable states, which matters the moment HomeViewModel.load() needs to tell &quot;nothing computed yet&quot; apart from &quot;computed, and it&#39;s empty.&quot;</p><h3>Why not just UserDefaults?</h3><p>UserDefaults would have worked mechanically — an array of word IDs under one key. WordsWarrior draws its persistence line elsewhere: scalar preferences live in UserDefaults, anything that&#39;s queried, versioned, or reasoned about with the same idioms as the rest of the app&#39;s structured data lives behind a SwiftData repository. The daily batch is read and written through exactly the same FetchDescriptor/ModelContext machinery as learned-word progress, so keeping it there means one persistence stack to reason about instead of two, even for a piece of state that happens to only ever have one row.</p><h3>Why this earns its place</h3><ul><li><strong>The constraint lives in the schema, not in caller discipline.</strong> @Attribute(.unique) on a constant guarantees singularity at the model layer — no code path can accidentally create a second row.</li><li><strong>Existence and emptiness are different states, on purpose.</strong> Deleting the row (not emptying its array) is what lets currentBatchWordIDs distinguish &quot;never computed&quot; from &quot;computed to be empty.&quot;</li><li><strong>One persistence idiom, not two.</strong> The alternative — UserDefaults for this one array — would have been simpler locally and inconsistent everywhere else this data gets touched.</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/02-constructor-dependency-injection.md"><strong>← Constructor-Based Dependency Injection</strong></a> · Next: <a href="https://medium.com/04-deterministic-batch-reconciliation.md"><strong>Deterministic Batch-Selection Algorithm →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=951e096b7a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Constructor-Based Dependency Injection: Testable Code Without a DI Framework]]></title>
            <link>https://medium.com/@abdallahedres005/constructor-based-dependency-injection-testable-code-without-a-di-framework-ca246bb39ed2?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca246bb39ed2</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 07:15:27 GMT</pubDate>
            <atom:updated>2026-10-20T07:15:27.729Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>The decision that isn’t in the code</h3><p>Dependency injection has a reputation for needing a framework — a container, a registration phase, sometimes a macro that generates a graph at compile time. WordsWarrior has none of that, and every collaborator in the app is still swappable. The trick isn’t a technique so much as a refusal: no singleton is ever reached into from inside a method body. Every object that needs a collaborator receives it through init, as a protocol type, with a concrete default for production use.</p><h3>Two examples, same shape</h3><p>ThemeManager needs exactly one collaborator — somewhere to read and persist the selected theme:</p><pre>// ThemeManager.swift<br>@Observable<br>final class ThemeManager {<br>    private let defaults: UserDefaultsManager</pre><pre>    private(set) var kind: ThemeKind<br>    var current: any Theme { kind.theme }</pre><pre>    init(defaults: UserDefaultsManager = UserDefaultsManager()) {<br>        self.defaults = defaults<br>        let stored: String? = defaults.value(forKey: ThemeDefaultsKey.selectedTheme.rawValue)<br>        self.kind = stored.flatMap(ThemeKind.init(rawValue:)) ?? .midnight<br>    }<br>}</pre><p>OnboardingViewModel needs two — a repository for the screen definitions, and the same UserDefaultsManager seam:</p><pre>// OnboardingViewModel.swift<br>@Observable<br>final class OnboardingViewModel {<br>    private let repository: OnboardingRepository<br>    private let defaults: UserDefaultsManager</pre><pre>    init(repository: OnboardingRepository = JSONOnboardingRepository(), defaults: UserDefaultsManager = UserDefaultsManager()) {<br>        self.repository = repository<br>        self.defaults = defaults<br>    }<br>}</pre><p>Neither type knows or cares that its default arguments happen to be the same production implementations used everywhere else in the app. A test constructs either one with a fake UserDefaultsManager backed by an in-memory dictionary, or a fake OnboardingRepository that returns a fixed set of screens, and nothing about ThemeManager or OnboardingViewModel needs to change to allow it. HomeViewModel follows the identical shape with four collaborators instead of two — the pattern doesn&#39;t get more complicated as the dependency count grows, it just gets one more constructor parameter.</p><h3>What a container would have bought — and cost</h3><p>A DI framework’s pitch is real: register types once, resolve a whole graph automatically, catch a missing registration at startup instead of at the call site. WordsWarrior’s dependency graph is shallow enough — a handful of view models, each with two to four collaborators, nothing depending on something three layers removed — that the registration bookkeeping would outweigh the convenience. The graph is fully visible by reading constructor signatures; cmd+click on any dependency&#39;s type resolves it immediately. A container would trade that direct traceability for a central registry that has to be kept in sync with the types it describes, to solve a scaling problem this codebase doesn&#39;t have yet.</p><p>That’s a real trade-off, not a free win — a container earns its keep once a graph gets deep enough that manually threading dependencies through every initializer becomes its own maintenance burden. WordsWarrior just isn’t there.</p><h3>Why this earns its place</h3><ul><li><strong>The composition root is just </strong><strong>init.</strong> There&#39;s no separate registration step to forget to update when a new dependency shows up — the constructor signature <em>is</em> the documentation.</li><li><strong>Every collaborator is a protocol, never a concrete type, at the point of use.</strong> ThemeManager depends on UserDefaultsManager&#39;s public interface, not on UserDefaults directly, which is what makes swapping it in a test free.</li><li><strong>Defaults keep call sites clean without hiding the seam.</strong> ThemeManager() reads exactly like a no-argument initializer everywhere it&#39;s actually constructed in production, while still being fully overridable the one place — a test — that needs to.</li><li><strong>Deliberately minimal.</strong> No property wrappers for injection, no @Injected macro, no service locator reached into from inside a method. If WordsWarrior&#39;s dependency graph ever gets deep enough to need one, that will be a visible, deliberate addition — not a default reached for early.</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/01-protocol-oriented-repository.md"><strong>← Protocol-Oriented Repository Pattern</strong></a> · Next: <a href="https://medium.com/03-singleton-row-swiftdata.md"><strong>The Singleton-Row Pattern →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca246bb39ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protocol-Oriented Repository Pattern: Composition Over Inheritance in Swift]]></title>
            <link>https://medium.com/@abdallahedres005/protocol-oriented-repository-pattern-composition-over-inheritance-in-swift-e59969b246b4?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e59969b246b4</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 08:00:34 GMT</pubDate>
            <atom:updated>2026-10-18T08:00:34.240Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of 6 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior Architecture &amp; Design Patterns series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>The problem with sharing logic across repositories</h3><p>WordsWarrior has three repositories behind its Home feature: one for the word catalog, one for progress (learned/saved/liked), one for the daily batch. All three filter, sort, or select from arrays of domain objects. In an object-oriented language the reflex is a shared base class — BaseRepository with the common logic, subclasses filling in the storage-specific bits. Swift has a better tool for exactly this shape: a protocol with a default implementation.</p><h3>Shared logic as a protocol extension, not a base class</h3><p>WordRepository declares the contract once, then supplies every filtering/ordering/selection method as a default implementation in an extension:</p><pre>// WordRepository.swift<br>protocol WordRepository {<br>    func loadWords() throws -&gt; [Word]</pre><pre>    func words(_ words: [Word], inCategories categories: [String]) -&gt; [Word]<br>    func words(_ words: [Word], atOrAbove level: WordLevel) -&gt; [Word]<br>    func words(_ words: [Word], excludingIDs ids: Set&lt;String&gt;) -&gt; [Word]<br>    func wordsOrderedByLevel(_ words: [Word]) -&gt; [Word]<br>    func nextBatch(from pool: [Word], catalog: [Word], previousIDs: [String], learnedIDs: Set&lt;String&gt;, pageSize: Int) -&gt; [Word]<br>}</pre><pre>extension WordRepository {<br>    func words(_ words: [Word], inCategories categories: [String]) -&gt; [Word] {<br>        categories.isEmpty ? words : words.filter { categories.contains($0.topic) }<br>    }</pre><pre>    func wordsOrderedByLevel(_ words: [Word]) -&gt; [Word] {<br>        words.enumerated()<br>            .sorted { lhs, rhs in<br>                lhs.element.wordLevel != rhs.element.wordLevel<br>                    ? lhs.element.wordLevel &lt; rhs.element.wordLevel<br>                    : lhs.offset &lt; rhs.offset<br>            }<br>            .map(\.element)<br>    }<br>}</pre><p>The concrete type that ships to production implements exactly one method:</p><pre>struct JSONWordRepository: WordRepository {<br>    func loadWords() throws -&gt; [Word] {<br>        try JSONLoader.load(&quot;words&quot;, as: [Word].self)<br>    }<br>}</pre><p>Every filtering rule, every ordering rule, the entire daily-batch-selection algorithm — none of it is duplicated if a second implementation ever loads words from a remote API instead of a bundled JSON file. A base class could achieve the same sharing, but it would also force every repository into one inheritance hierarchy and give up the ability to conform to more than one such “base” at once. The protocol extension shares the logic without constraining the type’s shape at all.</p><h3>Why two sibling repositories deliberately skip this trick</h3><p>WordProgressRepository and WordBatchRepository sit right next to WordRepository in the same folder, and neither one hoists any logic into a protocol extension:</p><pre>// WordBatchRepository.swift<br>protocol WordBatchRepository {<br>    func currentBatchWordIDs(context: ModelContext) -&gt; [String]<br>    func saveBatch(wordIDs: [String], context: ModelContext)<br>    func clearBatch(context: ModelContext)<br>}</pre><pre>struct SwiftDataWordBatchRepository: WordBatchRepository {<br>    func saveBatch(wordIDs: [String], context: ModelContext) {<br>        if let existing = batch(context: context) {<br>            existing.wordIDs = wordIDs<br>        } else {<br>            context.insert(WordBatch(wordIDs: wordIDs))<br>        }<br>        try? context.save()<br>    }<br>    // ...<br>}</pre><p>This isn’t an oversight — it’s the same judgment call applied consistently. WordRepository&#39;s shared methods are pure functions over arrays already sitting in memory: nothing in words(_:inCategories:) cares whether those words came from JSON, a network call, or a database. WordBatchRepository and WordProgressRepository don&#39;t have that luxury — every one of their methods needs a live ModelContext to fetch, insert, or save, which means the &quot;shared&quot; part of their logic is inseparable from the storage call itself. A protocol extension over ModelContext-dependent methods wouldn&#39;t remove duplication; it would just relocate persistence code to a place that&#39;s harder to see next to the type that owns it.</p><h3>Why this earns its place</h3><ul><li><strong>Composition, not a hierarchy.</strong> Any type can conform to WordRepository and inherit its default behavior without giving up its ability to conform to anything else — a base class can&#39;t offer that.</li><li><strong>The default implementation is the single source of truth.</strong> wordsOrderedByLevel&#39;s tie-breaking rule (by original position, not by sort&#39;s incidental stability) is written once and every repository gets it, exactly, forever.</li><li><strong>The line is drawn by what’s actually shared, not by folder proximity.</strong> WordRepository gets the extension because its logic is storage-agnostic; its neighbors don&#39;t, because theirs isn&#39;t. Applying the pattern everywhere &quot;for consistency&quot; would have been the wrong call.</li></ul><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Next: <a href="https://medium.com/02-constructor-dependency-injection.md"><strong>Constructor-Based Dependency Injection →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e59969b246b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside WordsWarrior: Architecture & Design Patterns (Series Intro)]]></title>
            <link>https://medium.com/@abdallahedres005/inside-wordswarrior-architecture-design-patterns-series-intro-92f3f48e9a08?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f3f48e9a08</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 11:16:50 GMT</pubDate>
            <atom:updated>2026-10-15T11:16:50.595Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 0 of 6 — the series overview. This article is the parent: it links out to every other part.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>Why this series exists</h3><p>A previous series walked through WordsWarrior’s top-level architecture — Coordinators, data-driven onboarding, the persistence split, theming, MVVM, gamification. This one goes a level deeper. It’s not about <em>what</em> WordsWarrior’s layers are, it’s about the smaller design-pattern decisions living <strong>inside</strong> those layers — the kind of call you make a dozen times a week as an iOS engineer, usually without a name for it: should this shared logic live in a protocol extension or a base class? Does this dependency need a DI framework, or does a constructor argument do the job? Is this global piece of state actually a database row?</p><p>Six patterns, six real files, one running theme: <strong>why this pattern, and not the fancier alternative that would also have worked.</strong></p><h3>What “pattern,” concretely, means here</h3><p>None of these are textbook Gang-of-Four boxes copied onto a Swift file. They’re the actual shape WordsWarrior’s code took when a real constraint showed up — a repository that needed shared filtering logic, a view model that needed to be testable without a DI container, a persistence framework being asked to model something that isn’t really a collection. The pattern names (Repository, Facade, Singleton) are useful shorthand, not the point. The point is the trade-off each one resolves.</p><h3>The series</h3><ol><li><a href="https://medium.com/01-protocol-oriented-repository.md"><strong>Protocol-Oriented Repository Pattern: Composition Over Inheritance in Swift</strong></a> — why shared filtering/ordering logic lives in a protocol extension, and why two sibling repositories deliberately <em>don’t</em> use that same trick.</li><li><a href="https://medium.com/02-constructor-dependency-injection.md"><strong>Constructor-Based Dependency Injection: Testable Code Without a DI Framework</strong></a> — the composition root you get for free when every dependency is a protocol-typed constructor argument with a production default.</li><li><a href="https://medium.com/03-singleton-row-swiftdata.md"><strong>The Singleton-Row Pattern: Modeling Global State in SwiftData</strong></a> — how to represent “there is exactly one of these” inside a persistence framework built around collections.</li><li><a href="https://medium.com/04-deterministic-batch-reconciliation.md"><strong>Designing a Deterministic Batch-Selection Algorithm</strong></a> — replacing a shuffle-and-pick with an ID-retention algorithm that never surprises the user.</li><li><a href="https://medium.com/05-notification-signature-sync.md"><strong>Cross-Feature State Sync Without a Shared Store</strong></a> — how two independent tabs stay in sync without a shared observable object or a full reload on every notification.</li><li><a href="https://medium.com/06-speech-service-facade.md"><strong>The Facade Pattern: Insulating App Code from AVFoundation</strong></a> — a two-line protocol that keeps AVSpeechSynthesizer out of every call site that needs to talk.</li></ol><p>Each article is built directly from the WordsWarrior source — real code, not pseudocode — with a link back to the repo so you can see it in context.</p><h3>A quick look at the shape these patterns share</h3><p>Almost every pattern in this series starts from the same two-piece seam: a protocol describing <em>what</em> a collaborator does, and exactly one concrete type describing <em>how</em>:</p><pre>// WordBatchRepository.swift<br>protocol WordBatchRepository {<br>    func currentBatchWordIDs(context: ModelContext) -&gt; [String]<br>    func saveBatch(wordIDs: [String], context: ModelContext)<br>    func clearBatch(context: ModelContext)<br>}</pre><pre>struct SwiftDataWordBatchRepository: WordBatchRepository { /* ... */ }</pre><p>Nothing exotic — no reflection, no macros, no third-party dependency-injection library. Just a seam placed deliberately, every time, at the boundary that’s actually likely to change or need a test double. That restraint is the throughline of this whole series.</p><p>Follow along, or jump straight to the pattern you need. Source for everything: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f3f48e9a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gamification Engineering: Levels, Batches & XP]]></title>
            <link>https://medium.com/@abdallahedres005/gamification-engineering-levels-batches-xp-761c22f93f1f?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/761c22f93f1f</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 12:56:53 GMT</pubDate>
            <atom:updated>2026-10-13T12:56:53.336Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of 7 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior MVP engineering series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>Gamification is a state machine, not a visual effect</h3><p>It’s tempting to think of “gamification” as confetti and a progress bar. The actual engineering problem is a state machine: what counts as progress, when does a level change, and how do you communicate a <em>transition</em> — not just a new value — to the UI. WordsWarrior’s leveling system is a compact example of doing this without it turning into a tangle of booleans.</p><h3>Levels are a Comparable enum, not magic numbers</h3><pre>// WordLevel.swift<br>enum WordLevel: String, CaseIterable, Comparable {<br>    case beginner, intermediate, advanced</pre><pre>    var rank: Int { Self.allCases.firstIndex(of: self)! }</pre><pre>    var title: String {<br>        switch self {<br>        case .beginner: &quot;Squire&quot;<br>        case .intermediate: &quot;Warrior&quot;<br>        case .advanced: &quot;Legend&quot;<br>        }<br>    }</pre><pre>    static func &lt; (lhs: WordLevel, rhs: WordLevel) -&gt; Bool {<br>        lhs.rank &lt; rhs.rank<br>    }<br>}</pre><p>Making WordLevel Comparable means the rest of the codebase can write $0.wordLevel &lt; starting directly — no separate integer-mapping table to keep in sync, and no risk of a word&#39;s difficulty and a user&#39;s rank being compared inconsistently.</p><h3>The daily quest is a persisted, cached selection — not a live query</h3><pre>// WordBatch.swift<br>// Singleton row: the app only ever tracks one current batch, keyed by the constant<br>// `WordBatch.key` rather than a calendar date.<br>@Model<br>final class WordBatch {<br>    @Attribute(.unique) var singletonKey: String<br>    var wordIDs: [String]<br>    static let key = &quot;current&quot;<br>}</pre><p>Today’s word batch is computed once and cached, so the quest survives a relaunch instead of silently reshuffling. Picking the batch itself pads the current level with higher-level words when needed:</p><pre>// HomeViewModel.swift<br>// Scoped to `currentLevel` and everything above it, so today&#39;s total always matches<br>// `wordsPerDay` even if the current level alone can&#39;t fill it — the shortfall is padded<br>// with higher-level words, ordered so they sit behind the current level&#39;s words in the deck.<br>func refreshCurrentBatch(context: ModelContext) {<br>    let wordsPerDay: Int = defaults.value(forKey: OnboardingDefaultsKey.wordsPerDay.rawValue) ?? 5<br>    let pool = repository.wordsOrderedByLevel(repository.words(categoryWords, atOrAbove: currentWordLevel))<br>    let previousIDs = batchRepository.currentBatchWordIDs(context: context)<br>    let batch = repository.nextBatch(from: pool, catalog: categoryWords, previousIDs: previousIDs, learnedIDs: learnedWordIDs, pageSize: wordsPerDay)<br>    todayWords = batch<br>    batchRepository.saveBatch(wordIDs: batch.map(\.id), context: context)<br>}</pre><h3>XP as a pure derivation</h3><pre>var learnedToday: Int {<br>    todayWords.filter { learnedWordIDs.contains($0.id) }.count<br>}<br>var revisitedTodayCount: Int {<br>    todayWords.filter { revisitedToday.contains($0.id) }.count<br>}<br>var dailyXP: Int {<br>    learnedToday * 10 + revisitedTodayCount * 5<br>}</pre><p>No stored XP counter to drift out of sync — dailyXP is always correct because it&#39;s computed from the same sets everything else reads.</p><h3>A level-up is a snapshot, not a boolean</h3><p>This is the detail worth internalizing: checkForLevelUp() doesn&#39;t just flip didLevelUp = true. It captures a full <strong>before/after snapshot</strong>:</p><pre>// LevelUpSnapshot.swift<br>struct LevelUpSnapshot {<br>    let fromNumber: Int<br>    let fromTitle: String<br>    let fromProgress: (current: Int, total: Int)<br>    let toNumber: Int<br>    let toTitle: String<br>    let toNextTitle: String?<br>    let toProgress: (current: Int, total: Int)<br>}</pre><pre>// HomeViewModel.swift<br>func checkForLevelUp() {<br>    let fromProgress = levelProgress<br>    guard fromProgress.total &gt; 0, fromProgress.current &gt;= fromProgress.total, let next = nextWordLevel else { return }</pre><pre>    let fromNumber = levelNumber<br>    let fromTitle = currentLevelTitle<br>    defaults.set(next.rawValue, forKey: OnboardingDefaultsKey.userLevel.rawValue)</pre><pre>    pendingLevelUp = LevelUpSnapshot(<br>        fromNumber: fromNumber, fromTitle: fromTitle, fromProgress: fromProgress,<br>        toNumber: levelNumber, toTitle: currentLevelTitle,<br>        toNextTitle: nextLevelTitle, toProgress: levelProgress<br>    )<br>    didLevelUp = true<br>}</pre><p>Why does this matter? By the time the level-up sheet reads pendingLevelUp, currentLevel has <em>already</em> moved on to the new value — a bare didLevelUp = true boolean would leave the celebration screen with no way to say &quot;you went from Squire to Warrior,&quot; only &quot;you are now Warrior.&quot; Capturing the snapshot <em>before</em> mutating state is what makes an honest before/after animation possible at all.</p><h3>Why this matters for an MVP</h3><p>Retention mechanics are exactly the kind of feature that gets bolted on carelessly under launch pressure — a flag here, a counter there, until level state and UI state quietly disagree. Modeling the <em>transition</em> as data (a snapshot), not just the destination, is a small extra step that prevents an entire class of “the animation shows the wrong number” bugs later.</p><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/05-mvvm-observable.md"><strong>← MVVM with @Observable</strong></a> · Back to <a href="https://medium.com/00-series-overview.md"><strong>series overview</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761c22f93f1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM with @Observable: Clean State Management in SwiftUI]]></title>
            <link>https://medium.com/@abdallahedres005/mvvm-with-observable-clean-state-management-in-swiftui-b44fe14d60d3?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b44fe14d60d3</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 08:43:41 GMT</pubDate>
            <atom:updated>2026-09-28T08:43:41.739Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 5 of 7 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior MVP engineering series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>View models that own logic, not just state</h3><p>The difference between a view model that’s “MVVM” in name only and one that actually earns its place is whether business logic lives there or leaked into the view body. In WordsWarrior, every view model is @Observable, holds zero UI code, and is constructed with its dependencies as <strong>protocols</strong>, not concrete types:</p><pre>// HomeViewModel.swift<br>@Observable<br>final class HomeViewModel {<br>    private let repository: WordRepository<br>    private let progressRepository: WordProgressRepository<br>    private let batchRepository: WordBatchRepository<br>    private let defaults: UserDefaultsManager</pre><pre>    weak var coordinator: (any HomeCoordinatorProtocol)?</pre><pre>    init(<br>        repository: WordRepository = JSONWordRepository(),<br>        progressRepository: WordProgressRepository = SwiftDataWordProgressRepository(),<br>        batchRepository: WordBatchRepository = SwiftDataWordBatchRepository(),<br>        defaults: UserDefaultsManager = UserDefaultsManager()<br>    ) {<br>        self.repository = repository<br>        self.progressRepository = progressRepository<br>        self.batchRepository = batchRepository<br>        self.defaults = defaults<br>    }<br>}</pre><p>Every dependency has a sensible default for production use, but every one is swappable in a test — no singleton reached into mid-method, no static state to reset between test runs.</p><h3>Computed properties instead of imperative recalculation</h3><p>Rather than manually keeping counters in sync, HomeViewModel derives everything from a small set of source-of-truth sets:</p><pre>var pendingTodayWords: [Word] {<br>    todayWords.filter { !learnedWordIDs.contains($0.id) }<br>}</pre><pre>var dailyProgress: (current: Int, total: Int) {<br>    let current = todayWords.filter { learnedWordIDs.contains($0.id) }.count<br>    return (current, todayWords.count)<br>}</pre><pre>var isQuestComplete: Bool {<br>    dailyProgress.total &gt; 0 &amp;&amp; dailyProgress.current &gt;= dailyProgress.total<br>}</pre><p>There’s no code path where isQuestComplete and dailyProgress can disagree — one is defined in terms of the other. That&#39;s the kind of bug class computed properties eliminate for free.</p><h3>The one deliberate exception, and why it’s deliberate</h3><p>Coordinators in this codebase use ObservableObject/@Published, not @Observable — the single break from an otherwise consistent convention:</p><pre>// AppCoordinator.swift<br>final class AppCoordinator: AppCoordinatorProtocol {<br>    @Published var root: AppRoute = .splash<br>    @Published var path = NavigationPath()<br>    @Published var sheet: AppRoute?<br>    ...<br>}</pre><p>This isn’t inconsistency — it’s a documented choice to match a reference Coordinator implementation exactly, since Coordinator is a protocol with a default extension (see <a href="https://medium.com/01-coordinator-pattern-navigation.md">Part 1</a>), and ObservableObject conformance is easy to express generically across AnyObject types in a way @Observable isn&#39;t (yet). View models stay @Observable; both coexist without friction. Knowing <em>why</em> an exception exists — and writing that reasoning down — is what keeps a codebase&#39;s conventions legible instead of feeling arbitrary six months later.</p><h3>ModelContext as a parameter — the pattern that makes this all testable</h3><p>Covered in <a href="https://medium.com/03-persistence-strategy.md">Part 3</a> from the persistence side, but it’s really a view-model design decision: HomeViewModel never stores a ModelContext. Every method that needs one takes it as an argument:</p><pre>func recordDisposition(_ word: Word, disposition: WordDisposition, context: ModelContext) {<br>    progressRepository.setDisposition(wordID: word.id, disposition: disposition, context: context)<br>    switch disposition {<br>    case .learned:<br>        learnedWordIDs.insert(word.id)<br>        savedForLaterWordIDs.remove(word.id)<br>        checkForLevelUp()<br>    case .savedForLater:<br>        savedForLaterWordIDs.insert(word.id)<br>        learnedWordIDs.remove(word.id)<br>        revisitedToday.insert(word.id)<br>    }<br>}</pre><p>The view supplies whichever ModelContext its own @Environment holds. The view model has no lifecycle dependency on <em>when</em> that context was created — which also means a unit test can pass an in-memory context created fresh per test, with no shared state bleeding between tests.</p><h3>Why this matters for an MVP</h3><p>MVP code gets thrown away less often than people expect — the parts that survive are usually the business logic, not the pixels. A view model with protocol-injected dependencies and no stored ModelContext is a view model you can actually unit test today, and refactor the persistence layer under tomorrow without breaking a single test.</p><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/04-themeable-design-system.md"><strong>← Themeable Design System</strong></a> · Next: <a href="https://medium.com/06-gamification-engineering.md"><strong>Gamification Engineering →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b44fe14d60d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Runtime-Themeable Design System in SwiftUI]]></title>
            <link>https://medium.com/@abdallahedres005/building-a-runtime-themeable-design-system-in-swiftui-b323243cbff7?source=rss-44123d5ef02f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b323243cbff7</guid>
            <dc:creator><![CDATA[Abdallah Edres]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 08:42:17 GMT</pubDate>
            <atom:updated>2026-09-28T08:42:17.821Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 of 7 in the </em><a href="https://medium.com/00-series-overview.md"><em>WordsWarrior MVP engineering series</em></a><em>.</em></p><p><strong>Repo:</strong> <a href="https://github.com/AbdallahEdres/WordsWarrior">github.com/AbdallahEdres/WordsWarrior</a></p><h3>The tell-tale sign of a design system that doesn’t exist yet</h3><p>Grep any SwiftUI codebase for Color( or a raw asset-catalog name used directly in a view body. If that search returns fifty hits, a rebrand or a dark-mode-style theme switch means touching fifty files. WordsWarrior ships four selectable themes (Midnight, Forest, Ocean, Rose) precisely because that search returns close to zero.</p><h3>One protocol, semantic roles only</h3><pre>// Theme.swift<br>protocol Theme {<br>    var background: Color { get }<br>    var surface: Color { get }<br>    var textPrimary: Color { get }<br>    var textSecondary: Color { get }<br>    var accent: Color { get }<br>    var deckLearned: Color { get }<br>    var foreGround: Color { get }<br>}</pre><p>No view ever asks for .periwinkle or .charcoalBlue. It asks for textPrimary or accent — a <em>role</em>, not a literal color. Four structs implement that role mapping:</p><pre>// AppThemes.swift<br>struct ForestTheme: Theme {<br>    let background: Color = .forestBackground<br>    let surface: Color = .charcoalBlue<br>    let textPrimary: Color = .periwinkle<br>    let textSecondary: Color = .lavenderGrey<br>    let accent: Color = .forestAccent<br>    let deckLearned: Color = .drySage<br>    let foreGround: Color = .periwinkle<br>}</pre><p>Adding a fifth theme is a new struct implementing seven properties — nothing else in the app changes.</p><h3>A selector enum, not a scattered set of flags</h3><pre>// ThemeKind.swift<br>enum ThemeKind: String, CaseIterable, Identifiable {<br>    case midnight, forest, ocean, rose</pre><pre>    var id: String { rawValue }</pre><pre>    var theme: any Theme {<br>        switch self {<br>        case .midnight: MainTheme()<br>        case .forest: ForestTheme()<br>        case .ocean: OceanTheme()<br>        case .rose: RoseTheme()<br>        }<br>    }<br>}</pre><p>CaseIterable means the Profile screen&#39;s theme picker is built by iterating ThemeKind.allCases — no hardcoded list of four buttons to keep in sync.</p><h3>State lives in one @Observable manager</h3><pre>// ThemeManager.swift<br>@Observable<br>final class ThemeManager {<br>    private let defaults: UserDefaultsManager<br>    private(set) var kind: ThemeKind<br>    var current: any Theme { kind.theme }</pre><pre>    init(defaults: UserDefaultsManager = UserDefaultsManager()) {<br>        self.defaults = defaults<br>        let stored: String? = defaults.value(forKey: ThemeDefaultsKey.selectedTheme.rawValue)<br>        self.kind = stored.flatMap(ThemeKind.init(rawValue:)) ?? .midnight<br>    }</pre><pre>    func select(_ kind: ThemeKind) {<br>        self.kind = kind<br>        defaults.set(kind.rawValue, forKey: ThemeDefaultsKey.selectedTheme.rawValue)<br>    }<br>}</pre><p>ThemeManager is injected exactly once, at the app root — .environment(themeManager) in WordsWarriorApp — and every screen reads it back with @Environment(ThemeManager.self). Selecting a new theme from Profile updates current for the entire app tree instantly, because it&#39;s the same observable instance everywhere.</p><h3>Two small primitives every screen builds on</h3><pre>// ScreenBackground.swift<br>struct ScreenBackground: ViewModifier {<br>    @Environment(ThemeManager.self) private var themeManager<br>    func body(content: Content) -&gt; some View {<br>        ZStack {<br>            themeManager.current.background.ignoresSafeArea()<br>            content<br>        }<br>    }<br>}<br>extension View {<br>    func screenBackground() -&gt; some View { modifier(ScreenBackground()) }<br>}</pre><pre>// PrimaryButton.swift<br>struct PrimaryButton: View {<br>    @Environment(ThemeManager.self) private var themeManager<br>    let title: String<br>    var icon: String?<br>    let action: () -&gt; Void</pre><pre>    var body: some View {<br>        let theme = themeManager.current<br>        Button(action: action) {<br>            HStack(spacing: 8) {<br>                Text(title).font(.headline)<br>                if let icon { Image(systemName: icon).font(.headline) }<br>            }<br>            .foregroundStyle(theme.foreGround)<br>            .frame(maxWidth: .infinity)<br>            .padding(.vertical, 16)<br>            .background(theme.accent, in: Capsule())<br>        }<br>        .buttonStyle(.plain)<br>    }<br>}</pre><p>Every screen calls .screenBackground() once instead of re-deriving a ZStack + color; every primary call-to-action is one PrimaryButton(title:action:). The established convention — enforced by code review, not the compiler — is that <strong>any themed view reads colors via </strong><strong>themeManager.current.&lt;role&gt;, never a hardcoded </strong><strong>Color or asset name.</strong></p><h3>Why this matters for an MVP</h3><p>Visual identity is one of the first things that changes after user testing — a color that “felt off,” a request for a dark mode, a rebrand before launch. A protocol-based theme system turns that from a multi-file find-and-replace into adding one struct and letting the type system verify you covered every role.</p><p>Full source: <a href="https://github.com/AbdallahEdres/WordsWarrior"><strong>github.com/AbdallahEdres/WordsWarrior</strong></a></p><p>Previous: <a href="https://medium.com/03-persistence-strategy.md"><strong>← Persistence Strategy</strong></a> · Next: <a href="https://medium.com/05-mvvm-observable.md"><strong>MVVM with @Observable →</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b323243cbff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>