<?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 Steve on Medium]]></title>
        <description><![CDATA[Stories by Steve on Medium]]></description>
        <link>https://medium.com/@mobileledge?source=rss-d7def8c13c85------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*45IegqUB6nk1OFksXDy2iw.png</url>
            <title>Stories by Steve on Medium</title>
            <link>https://medium.com/@mobileledge?source=rss-d7def8c13c85------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 13:16:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mobileledge/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[Frontend SWE — Part 15 Why Your FE Architecture Needs a Mediator (Before It Turns Into Spaghetti)]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-15-why-your-fe-architecture-needs-a-mediator-before-it-turns-into-spaghetti-b5e7fd9f5df3?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e7fd9f5df3</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 10:07:11 GMT</pubDate>
            <atom:updated>2026-11-09T10:07:11.578Z</atom:updated>
            <content:encoded><![CDATA[<p>Every mid-to-senior engineer has inherited — or accidentally written — this specific brand of frontend mess:</p><p>You have a screen where a user selects an item. Let’s say an <strong>Inspection Site</strong>. That single user tap sounds innocent enough, but the cascade begins immediately:</p><ol><li>The <strong>Inspection Templates</strong> must reload for that specific site.</li><li>The technician’s <strong>Certifications</strong> must be validated against the site’s safety tier.</li><li>The <strong>Map View</strong> needs to pan to the new GPS coordinates and drop a pin.</li><li>The local <strong>Draft Session</strong> needs to wipe stale fields and rehydrate.</li></ol><p>Before long, you inspect the SiteSelector component or custom hook, and you find this:</p><pre>// ❌ The &quot;God Component&quot; that knows way too much<br>function handleSiteSelect(siteId: string) {<br>  // Direct import 1: Service<br>  templateStore.fetchTemplates(siteId);<br><br>  // Direct import 2: Auth/Permissions<br>  certChecker.validateTechnician(user.id, siteId);<br>  // Direct import 3: Imperative UI ref<br>  mapRef.current?.animateToRegion(site.coordinates);<br>  // Direct import 4: Local draft state<br>  draftStore.setSiteId(siteId);<br>}</pre><p>Look at that code from an architectural standpoint. Your UI component now holds hard references to four distinct subsystems. It knows the lifecycles, timing dependencies, and error semantics of peers it shouldn’t care about.</p><p>If CertChecker changes its contract, your button breaks. If someone else triggers a site change from a recent-items drawer, they have to copy-paste this coordination dance all over again. Testing this component requires mocking the entire universe.</p><p>In computer science, this is an O(N²) direct-connection nightmare. In real-world software, we solve this with a pattern introduced thirty years ago by the Gang of Four that modern frontend developers routinely overlook: <strong>The Mediator Pattern</strong>.</p><h3>Why Is It Called a “Mediator”?</h3><p>In law and international diplomacy, a <strong>mediator</strong> is a neutral third party brought in when opposing sides shouldn’t or can’t deal directly with one another.</p><p>Instead of Party A and Party B shouting across a table and creating chaos, Party A speaks only to the mediator. Party B speaks only to the mediator. The mediator hears the intents, weighs the ground rules, and coordinates the outcome.</p><p>In aviation, it’s the <strong>Air Traffic Control tower</strong>. Aircraft don’t radio one another to negotiate runway slots, they speak exclusively to the tower. The tower enforces separation policy, timing, and sequence.</p><p>In frontend architecture, the <strong>Mediator</strong> stands right in the middle between independent domain components, stores, and services. <strong>They are forbidden from talking to each other directly.</strong> They report events inward to the mediator; the mediator directs side effects outward.</p><h3>The Architecture: Hub-and-Spoke</h3><p>Instead of a spiderweb of mutual imports, we shift to a clean hub-and-spoke topology:</p><pre>[Site Selector]      [Template Store]<br>       │                    ▲<br>       │ 1. Event:          │ 2. fetchForSite()<br>       │   &#39;siteSelected&#39;   │<br>       ▼                    │<br>    ┌───────────────────────────┐<br>    │  InspectionSetupMediator  │<br>    └───────────────────────────┘<br>       │                    ▲<br>       │ 3. check()         │ 4. applySiteSelection()<br>       ▼                    ▼<br>[Cert Checker]        [Draft Store]</pre><p>Notice the inversion of responsibility:</p><ul><li>SiteSelector doesn&#39;t know templates exist. It just fires an event: <em>&quot;Hey, the user picked Site 42.&quot;</em></li><li>TemplateStore doesn&#39;t know who picked the site. It simply exposes a domain contract:fetchForSite(siteId).</li><li>InspectionSetupMediator owns the <strong>interaction policy</strong>: the order of execution, error fallbacks, and concurrency.</li></ul><h3>Writing a Production-Ready Mediator</h3><p>Client-side workflows are asynchronous and messy. Users tap buttons twice. Users switch tabs. Network requests resolve out of order.</p><p>A naive mediator that just calls await sequentially will fall flat in production. If a user taps <strong>Site A</strong> and immediately taps <strong>Site B</strong>, a slow network response for Site A can resolve <em>after</em> Site B, leaving the screen showing Site B&#39;s name with Site A&#39;s templates.</p><p>Here is how you structure a production-grade mediator with explicit colleague contracts and <strong>latest-wins cancellation</strong>:</p><pre>// 1. Strictly typed domain inputs<br>export type SetupWorkflowEvent =<br>  | { type: &#39;siteSelected&#39;; siteId: string }<br>  | { type: &#39;templateSelected&#39;; templateId: string };<br><br>// 2. Colleague contracts (Semantic domain interfaces, NOT raw React setState)<br>export interface TemplateStore {<br>  fetchForSite(siteId: string): Promise&lt;Template[]&gt;;<br>}<br><br>export interface EligibilityService {<br>  checkTechnician(siteId: string): Promise&lt;boolean&gt;;<br>}<br><br>export interface DraftStore {<br>  applySiteSelection(payload: {<br>    siteId: string;<br>    templates: Template[];<br>    isEligible: boolean;<br>  }): void;<br>}<br><br>// 3. The Coordinator<br>export class InspectionSetupMediator {<br>  private activeRequestId = 0;<br>  constructor(<br>    private readonly templates: TemplateStore,<br>    private readonly eligibility: EligibilityService,<br>    private readonly draft: DraftStore,<br>  ) {}<br><br>  async handle(event: SetupWorkflowEvent): Promise&lt;void&gt; {<br>    switch (event.type) {<br>      case &#39;siteSelected&#39;: {<br>        // Increment request token to track latest user intent<br>        const currentRequestId = ++this.activeRequestId;<br>        // Fan out independent queries concurrently<br>        const [templates, isEligible] = await Promise.all([<br>          this.templates.fetchForSite(event.siteId),<br>          this.eligibility.checkTechnician(event.siteId),<br>        ]);<br>        // Stale execution check: A newer action occurred while awaiting I/O<br>        if (currentRequestId !== this.activeRequestId) {<br>          return;<br>        }<br>        // Atomic update to consumer state<br>        this.draft.applySiteSelection({<br>          siteId: event.siteId,<br>          templates,<br>          isEligible,<br>        });<br>        return;<br>      }<br>      case &#39;templateSelected&#39;: {<br>        // Centralized template logic goes here<br>        return;<br>      }<br>    }<br>  }<br>}</pre><h3>Wiring to the UI: Keeping Components Dumb</h3><p>How does this land in React or React Native? We don’t pollute our mediator with hooks or render cycles. We inject the mediator instance via a clean Context or dependency container:</p><pre>export const SiteOptionItem = ({ siteId, label }: { siteId: string; label: string }) =&gt; {<br>  const mediator = useInspectionMediator();<br><br>  return (<br>    &lt;Pressable<br>      onPress={() =&gt; mediator.handle({ type: &#39;siteSelected&#39;, siteId })}<br>      style={styles.item}<br>    &gt;<br>      &lt;Text&gt;{label}&lt;/Text&gt;<br>    &lt;/Pressable&gt;<br>  );<br>};</pre><p>Look at that component. It has zero knowledge of certification checks, map animations, or template stores. It’s completely testable, renders fast, and its only job is to translate user gestures into typed domain events.</p><h3>Engineering Guardrails: Avoiding the “God Mediator”</h3><p>Like any design pattern, sloppy implementation creates architectural debt:</p><ul><li><strong>Beware the “God Mediator”:</strong> A mediator should be scoped to a single, coherent workflow boundary (InspectionSetupMediator, CheckoutMediator, OnboardingMediator). If your mediator is handling auth tokens, push notifications, navigation routing, and analytics all at once, you’ve built a monolith disguised as a class.</li><li><strong>Never expose raw state setters as colleague APIs:</strong> Avoid putting setTemplates() or setIsLoading() in your participant interfaces. Keep contracts semantic (applySiteSelection, markVerificationFailed).</li><li><strong>Keep the Mediator UI-agnostic:</strong> Your mediator should be a plain TypeScript class. It should have zero dependencies on react, react-native, or DOM APIs. If you can&#39;t run your mediator tests inside Node in under 5 milliseconds without mocking a virtual DOM, your abstractions are leaking.</li></ul><h3>The Bottom Line</h3><p>When you find your frontend code tangling multiple stores, APIs, and hooks directly inside UI screens just to make them play nice together, pause before writing another useEffect.</p><p>Decouple the participants. Define an explicit interface contract. Step back, and let a Mediator run traffic control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e7fd9f5df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 14 Flyweight Design Pattern in React Native: Share Data, Save Memory]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-14-flyweight-design-pattern-in-react-native-share-data-save-memory-b40e23438c32?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/b40e23438c32</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 08:00:10 GMT</pubDate>
            <atom:updated>2026-11-07T08:00:10.750Z</atom:updated>
            <content:encoded><![CDATA[<p>When building mobile applications, performance is not only about rendering components faster. Memory usage also matters — especially when an application handles hundreds or thousands of objects on constrained mobile hardware.</p><p>Imagine building a field inspection application where users answer hundreds of questions during a single audit. Many questions share the exact same metadata, such as labels, input types, measurement units, and validation rules.</p><p>Should we create a completely new copy of that metadata for every single answer?</p><p>Not necessarily. This is where the <strong>Flyweight Design Pattern</strong> becomes useful.</p><h3>1. The Problem: Repeating the Same Data</h3><p>Imagine an inspection application called <strong>FieldFlow</strong>. An inspection contains hundreds of checkpoints, and each checkpoint records its own answer.</p><p>A native implementation often merges the question metadata directly into every answer object:</p><pre>const answers = [<br>  {<br>    id: &#39;answer-1&#39;,<br>    label: &#39;Temperature&#39;,<br>    kind: &#39;number&#39;,<br>    unit: &#39;°C&#39;,<br>    rules: { min: 0, max: 100 },<br>    value: 25,<br>  },<br>  {<br>    id: &#39;answer-2&#39;,<br>    label: &#39;Temperature&#39;,<br>    kind: &#39;number&#39;,<br>    unit: &#39;°C&#39;,<br>    rules: { min: 0, max: 100 },<br>    value: 30,<br>  },<br>];</pre><p>Notice the duplication? Both answers contain the exact same question metadata:</p><ul><li><strong>Label:</strong> Temperature</li><li><strong>Type:</strong> Number</li><li><strong>Unit:</strong> °C</li><li><strong>Validation rules:</strong> 0–100</li></ul><p>The only thing that actually changes between them is the id and the value.</p><p>Now imagine an offline-capable inspection with <strong>2,000 answers</strong> built from only <strong>20 distinct question definitions</strong>. If we repeatedly allocate the same metadata for every answer, we bloat the JavaScript heap in Hermes and increase garbage collection overhead.</p><p>This is the exact problem the Flyweight pattern aims to solve.</p><h3>2. What Is the Flyweight Pattern?</h3><p>The <strong>Flyweight Pattern</strong> is a structural design pattern that reduces memory duplication by sharing common data across multiple objects.</p><blockquote><strong><em>Core Idea:</em></strong><em> Store shared information once, and let multiple objects reference that single source of truth.</em></blockquote><p>Flyweight divides object data into two distinct categories:</p><h3>Intrinsic State — Shared Data</h3><p>Intrinsic state contains immutable information that remains identical across multiple objects. In our inspection example, this includes:</p><ul><li>Question label</li><li>Input type (text | number)</li><li>Measurement unit</li><li>Validation rules (min, max)</li></ul><h3>Extrinsic State — Context-Specific Data</h3><p>Extrinsic state contains unique information that belongs to a specific instance and changes over time:</p><ul><li>Answer ID</li><li>User-entered value</li><li>Timestamp or attached photo evidence</li></ul><p>Instead of duplicating both types of data inside every object, we separate them.</p><h3>3. Applying Flyweight to React Native Data</h3><p>Let’s redesign our inspection data model by splitting the <strong>intrinsic</strong> definition from the <strong>extrinsic</strong> answer.</p><p>First, define the immutable shared question metadata (the Flyweight):</p><pre>export type QuestionDefinition = Readonly&lt;{<br>  id: string;<br>  label: string;<br>  kind: &#39;text&#39; | &#39;number&#39;;<br>  unit?: string;<br>  min?: number;<br>  max?: number;<br>}&gt;;</pre><p>Next, define the individual answer so it only holds a lightweight reference (definitionId) to its Flyweight:</p><p>TypeScript</p><pre>export type QuestionAnswer = Readonly&lt;{<br>  id: string;<br>  definitionId: string;<br>  value: string | number;<br>}&gt;;</pre><p>Now our data structure looks like this:</p><p>TypeScript</p><pre>const definitions: Record&lt;string, QuestionDefinition&gt; = {<br>  temperature: {<br>    id: &#39;temperature&#39;,<br>    label: &#39;Temperature&#39;,<br>    kind: &#39;number&#39;,<br>    unit: &#39;°C&#39;,<br>    min: 0,<br>    max: 100,<br>  },<br>};<br><br>const answers: QuestionAnswer[] = [<br>  {<br>    id: &#39;answer-1&#39;,<br>    definitionId: &#39;temperature&#39;,<br>    value: 25,<br>  },<br>  {<br>    id: &#39;answer-2&#39;,<br>    definitionId: &#39;temperature&#39;,<br>    value: 30,<br>  },<br>];</pre><p>Instead of storing the full question definition inside every answer, each answer stores only a string key. Both answers point to the exact same QuestionDefinition in memory:</p><p>Plaintext</p><pre>Answer 1 (value: 25) ─────┐<br>                          │<br>Answer 2 (value: 30) ─────┼──► Shared QuestionDefinition (&#39;temperature&#39;)<br>                          │<br>Answer 3 (value: 28) ─────┘</pre><h3>4. Building a Flyweight Factory / Registry</h3><p>What happens when inspection payloads arrive from different paginated API responses or local SQLite queries? If we aren’t careful, parsing those payloads will still allocate new JavaScript objects in memory for the same question definition.</p><p>In classical OOP, we solve this with a <strong>Flyweight Registry (or Factory)</strong> that guarantees canonical object references:</p><p>TypeScript</p><pre>export class QuestionDefinitionRegistry {<br>  private definitions = new Map&lt;string, QuestionDefinition&gt;();<br><br>  getOrCreate(definition: QuestionDefinition): QuestionDefinition {<br>    const existing = this.definitions.get(definition.id);<br>    if (existing) {<br>      return existing;<br>    }<br>    // Freeze the flyweight so no consumer can accidentally mutate shared state<br>    const shared = Object.freeze({ ...definition });<br>    this.definitions.set(definition.id, shared);<br>    return shared;<br>  }<br><br>  get(id: string): QuestionDefinition | undefined {<br>    return this.definitions.get(id);<br>  }<br><br>  clear(): void {<br>    this.definitions.clear();<br>  }<br>}</pre><p>When we process incoming data through the registry, multiple calls with the same ID return the <strong>exact same memory reference</strong>:</p><pre>const registry = new QuestionDefinitionRegistry();<br><br>const first = registry.getOrCreate({<br>  id: &#39;temperature&#39;,<br>  label: &#39;Temperature&#39;,<br>  kind: &#39;number&#39;,<br>  unit: &#39;°C&#39;,<br>});<br><br>const second = registry.getOrCreate({<br>  id: &#39;temperature&#39;,<br>  label: &#39;Temperature&#39;,<br>  kind: &#39;number&#39;,<br>  unit: &#39;°C&#39;,<br>});<br><br>console.log(first === second); // true</pre><h3>Bridging the Registry to React State</h3><p>While a class-based registry works well for imperative resources (like caching @shopify/react-native-skia Pathobjects, map marker icons, or Three.js geometries), passing a mutable class instance directly via React props can bypass React&#39;s reactivity if a definition ever updates.</p><p>In idiomatic React Native, we can turn our <strong>reactive store</strong> (such as Zustand or Redux Toolkit) into a Flyweight Registry. This gives us both <strong>referential sharing in memory</strong> and <strong>automatic UI reactivity</strong>:</p><p>TypeScript</p><pre>import { create } from &#39;zustand&#39;;<br><br>interface InspectionStore {<br>  // Intrinsic Flyweight Pool<br>  definitions: Record&lt;string, QuestionDefinition&gt;;<br>  // Extrinsic Instances<br>  answers: Record&lt;string, QuestionAnswer&gt;;<br>  answerIds: string[];<br>  // Flyweight Factory Action: Only stores a definition if it doesn&#39;t exist yet<br>  registerDefinitions: (incoming: QuestionDefinition[]) =&gt; void;<br>  updateAnswer: (answerId: string, value: string | number) =&gt; void;<br>}<br><br>export const useInspectionStore = create&lt;InspectionStore&gt;((set) =&gt; ({<br>  definitions: {},<br>  answers: {},<br>  answerIds: [],<br>  registerDefinitions: (incoming) =&gt;<br>    set((state) =&gt; {<br>      const nextDefinitions = { ...state.definitions };<br>      let hasNew = false;<br>      for (const def of incoming) {<br>        if (!nextDefinitions[def.id]) {<br>          nextDefinitions[def.id] = Object.freeze({ ...def });<br>          hasNew = true;<br>        }<br>      }<br>      return hasNew ? { definitions: nextDefinitions } : state;<br>    }),<br>  updateAnswer: (answerId, value) =&gt;<br>    set((state) =&gt; ({<br>      answers: {<br>        ...state.answers,<br>        [answerId]: { ...state.answers[answerId], value },<br>      },<br>    })),<br>}));</pre><p>Notice how registerDefinitions acts just like getOrCreate(): if a QuestionDefinition already exists in the pool, it keeps the existing reference untouched.</p><h3>5. Consuming Flyweights in React Native Components</h3><p>Now let’s connect our shared Flyweight definitions and individual answers inside a React Native component:</p><pre>import React from &#39;react&#39;;<br>import { View, Text, StyleSheet } from &#39;react-native&#39;;<br>import { useInspectionStore } from &#39;./store&#39;;<br><br>type QuestionProps = {<br>  answerId: string;<br>};<br><br>export const QuestionItem = React.memo(function QuestionItem({<br>  answerId,<br>}: QuestionProps) {<br>  // 1. Select extrinsic state for this specific row<br>  const answer = useInspectionStore((state) =&gt; state.answers[answerId]);<br>  // 2. Select shared intrinsic state (the Flyweight)<br>  const definition = useInspectionStore((state) =&gt;<br>    answer ? state.definitions[answer.definitionId] : undefined<br>  );<br>  if (!answer || !definition) {<br>    return null;<br>  }<br>  return (<br>    &lt;View style={styles.row}&gt;<br>      &lt;Text style={styles.label}&gt;<br>        {definition.label} {definition.unit ? `(${definition.unit})` : &#39;&#39;}<br>      &lt;/Text&gt;<br>      &lt;Text style={styles.value}&gt;{String(answer.value)}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>});<br>const styles = StyleSheet.create({<br>  row: { padding: 16, borderBottomWidth: 1, borderColor: &#39;#eee&#39; },<br>  label: { fontWeight: &#39;600&#39;, fontSize: 16 },<br>  value: { marginTop: 4, fontSize: 14, color: &#39;#555&#39; },<br>});</pre><p>Every QuestionItem accesses the same shared QuestionDefinition reference in memory while managing its own independent answer value.</p><p><strong>The benefits are clear:</strong></p><ul><li><strong>Shared metadata is stored once</strong> in the JavaScript heap.</li><li><strong>Each answer manages its own extrinsic state</strong> without duplicating rules or labels.</li><li><strong>Updating one answer</strong> never recreates or clones its question definition.</li><li><strong>Prop drilling is eliminated</strong> — the parent list only needs to pass answerId.</li></ul><h3>6. Bonus: How React Native Uses Flyweight Under the Hood</h3><p>Interestingly, the Flyweight pattern doesn’t stop at your JavaScript data layer — it is also the secret behind high-performance list rendering in React Native.</p><p>When rendering 1,000 items in @shopify/flash-list, creating 1,000 native iOS UIView or Android Viewinstances would crash the app with an Out-Of-Memory error. Instead, FlashList applies the Flyweight pattern to native UI views via <strong>View Recycling</strong>:</p><ul><li><strong>Intrinsic State:</strong> The allocated native view hierarchy, layout structure, and styles (kept in a small reusable pool of ~15 views).</li><li><strong>Extrinsic State:</strong> The specific item’s text and value injected into the view as it scrolls into the viewport.</li></ul><p>By pairing <strong>Data Flyweights</strong> (shared QuestionDefinition objects) with <strong>UI Flyweights</strong> (FlashList&#39;s getItemTyperecycling), your app stays fast and memory-light on both the JS thread and the Native UI thread.</p><h3>7. Flyweight vs. useMemo vs. React.memo</h3><p>A common misconception in React Native is treating every form of reuse or caching as the Flyweight pattern.They solve fundamentally different problems:</p><ul><li><strong>Flyweight:</strong> Shares canonical object data in memory across <em>multiple</em> instances so duplicate objects are never allocated.</li><li><strong>Cache:</strong> Stores network responses or expensive calculations to avoid re-fetching or recomputing.</li><li><strong>useMemo:</strong> Reuses a computed value <em>between renders of a single component instance</em> when its dependencies haven&#39;t changed.</li><li><strong>React.memo:</strong> Skips re-rendering a component tree when its props remain referentially equal.</li></ul><p>Consider this example:</p><pre>const definition = useMemo(<br>  () =&gt; createDefinition(rawQuestion),<br>  [rawQuestion],<br>);</pre><p>useMemo preserves definition across re-renders of <em>that single component</em>. However, if 500 list items each call useMemo(() =&gt; createDefinition(...)), you still allocate <strong>500 separate objects</strong> in memory.</p><ul><li><strong>Flyweight</strong> optimizes <strong>shared memory representation</strong> across the app.</li><li><strong>React memoization</strong> optimizes <strong>computation and rendering cycles</strong>.</li></ul><p>They complement each other beautifully (in fact, Flyweight’s stable object references make React.memochecks cheap and predictable), but they are not interchangeable.</p><h3>8. Tradeoffs and Common Mistakes</h3><p>Before introducing a Flyweight registry or normalized pool, keep these production considerations in mind:</p><ul><li><strong>Shared Mutable State:</strong> If multiple consumers share a single object and one consumer mutates it, every component sharing that flyweight breaks. Always enforce immutability with Readonly&lt;T&gt; at compile time and Object.freeze() at runtime (including deep-freezing nested validation rules).</li><li><strong>Stale Schema Versions:</strong> If your backend updates a question definition (e.g., changing the unit from °C to °F) while keeping the same ID, a naive getOrCreate registry will ignore the update and return the old object. Incorporate a version or updatedAt hash into your lookup key or store update logic.</li><li><strong>Unbounded Memory Growth:</strong> A global singleton registry that never clears its Map becomes a memory leak of its own. Scope your registry&#39;s lifecycle to the screen, session, or active inspection, and clean it up on unmount.</li><li><strong>Premature Optimization:</strong> If your screen only renders 15 items, the memory saved by extracting flyweights is negligible. Measure memory allocation in Hermes before adding architectural layers.</li></ul><h3>9. Key Takeaways</h3><p>The Flyweight Design Pattern is a practical tool for eliminating duplicate memory allocations when hundreds or thousands of objects share common information.</p><p>When applying it in React Native, remember:</p><ul><li><strong>Separate intrinsic and extrinsic state:</strong> Share stable metadata (definitions, styles, geometries) and keep instance-specific values (answers, coordinates) separate.</li><li><strong>Reuse canonical references:</strong> Use a Flyweight registry or normalized state pool so identical definitions point to the exact same object in memory.</li><li><strong>Keep Flyweights strictly immutable:</strong> Never allow an individual consumer to mutate shared data.</li><li><strong>Manage the lifecycle:</strong> Clear registries when switching contexts or unmounting heavy workflows.</li><li><strong>Don’t confuse memory sharing with render optimization:</strong> Combine Flyweight data structures with React.memo and FlashList for complete end-to-end performance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b40e23438c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 12 — Facade for Platform and SDK Complexity]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-12-facade-for-platform-and-sdk-complexity-8c8c00dfd9dc?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c8c00dfd9dc</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 16:10:11 GMT</pubDate>
            <atom:updated>2026-10-15T16:10:11.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The Problem: One Simple Feature, Too Many Responsibilities</h3><p>Imagine you’re building an application where users can take photos during an inspection.</p><p>From the user’s perspective, it’s simple:</p><p><strong>Tap a button → Take a photo → Save it.</strong></p><p>But behind that button, the application needs to perform several operations:</p><ol><li>Check camera permission.</li><li>Request permission if necessary.</li><li>Open the camera.</li><li>Capture a photo.</li><li>Process or compress the image.</li><li>Remove sensitive metadata.</li><li>Save the photo to local storage.</li><li>Clean up temporary files.</li></ol><p>What looks like one feature actually depends on multiple native APIs, SDKs, and services.</p><p>Now imagine implementing these steps directly inside a React component.</p><pre>async function handleTakePhoto() {<br>  const permission = await permissions.request();<br><br>  if (!permission.granted) return;<br>  const photo = await camera.capture();<br>  if (!photo) return;<br>  const processed = await imageProcessor.prepare(photo);<br>  await attachmentStore.save(processed);<br>}</pre><p>At first, this looks perfectly reasonable.</p><p>But what happens when another screen also needs to capture photos?</p><p>You might copy the same logic.</p><p>And what happens when the camera SDK changes, image processing fails, or a temporary file needs to be deleted?</p><p>Every screen may need to be updated.</p><p><strong>The real problem isn’t the number of operations. It’s that the UI knows too much about how the feature works internally.</strong></p><p>This is where the Facade pattern becomes useful.</p><h3>2. What Is the Facade Pattern?</h3><p>The Facade pattern is a structural design pattern that provides a simple interface to a complex subsystem.</p><p>Instead of making the UI communicate with several services, we introduce one entry point that coordinates them.</p><p>Think about ordering coffee.</p><p>You don’t need to operate the coffee machine, manage ingredients, or understand how the kitchen works.</p><p>You simply order a coffee.</p><p>The staff handles everything behind the counter.</p><p>A Facade works similarly.</p><p>In our example, the UI should only need to say:</p><pre>const result = await evidenceCapture.capturePhoto({<br>  inspectionId: &#39;inspection-123&#39;,<br>});</pre><p>That’s it.</p><p>The UI doesn’t need to know:</p><ul><li>Which camera library is being used.</li><li>How permissions work on iOS or Android.</li><li>How the image is processed.</li><li>Where the attachment is stored.</li><li>How temporary files are cleaned up.</li></ul><p>All those details belong behind the Facade.</p><h3>3. How Does the Facade Work?</h3><p><strong>Inspection Screen</strong></p><p>Handles user interactions and displays results.</p><p><strong>EvidenceCapture Facade</strong></p><p>Coordinates the operations required to capture and save evidence.</p><p><strong>Supporting Services</strong></p><p>Handle specific technical responsibilities such as camera access, image processing, or file persistence.</p><p>The important distinction is that the Facade does not replace these services.</p><p><strong>It brings them together into one meaningful application capability.</strong></p><h3>4. Implementing a Simple Facade</h3><p>Let’s create an interface that describes what our application needs.</p><pre>type CaptureResult =<br>  | { kind: &#39;captured&#39;; attachment: Attachment }<br>  | { kind: &#39;cancelled&#39; }<br>  | { kind: &#39;permissionDenied&#39; }<br>  | { kind: &#39;failed&#39;; error: Error };<br><br>interface EvidenceCapture {<br>  capturePhoto(<br>    inspectionId: string<br>  ): Promise&lt;CaptureResult&gt;;<br>}</pre><p>Notice something important.</p><p>The interface doesn’t expose any native SDK details.</p><p>It describes an application capability: capturing inspection evidence.</p><p>Now let’s implement it.</p><pre>class DefaultEvidenceCapture implements EvidenceCapture {<br>  constructor(<br>    private permissions: CameraPermission,<br>    private camera: Camera,<br>    private processor: ImageProcessor,<br>    private storage: AttachmentStorage<br>  ) {}<br><br><br>  async capturePhoto(<br>    inspectionId: string<br>  ): Promise&lt;CaptureResult&gt; {<br>    const permission = await this.permissions.request();<br>    if (!permission.granted) {<br>      return { kind: &#39;permissionDenied&#39; };<br>    }<br>    const photo = await this.camera.capture();<br>    if (!photo) {<br>      return { kind: &#39;cancelled&#39; };<br>    }<br>    try {<br>      const processed = await this.processor.prepare(photo);<br>      const attachment = await this.storage.save(<br>        processed,<br>        inspectionId<br>      );<br>      return { kind: &#39;captured&#39;, attachment };<br>    } catch (error) {<br>      return {<br>        kind: &#39;failed&#39;,<br>        error: error instanceof Error<br>          ? error<br>          : new Error(&#39;Photo capture failed&#39;),<br>      };<br>    }<br>  }<br>}</pre><p><em>This is a simplified example. Production code should also handle unexpected permission/camera failures and release owned temporary resources.</em></p><p>Now the entire process is encapsulated inside one class.</p><p>The UI becomes much simpler.</p><pre>async function handleTakePhoto() {<br>  const result = await evidenceCapture.capturePhoto(<br>    inspectionId<br>  );<br><br>  switch (result.kind) {<br>    case &#39;captured&#39;:<br>      showAttachment(result.attachment);<br>      break;<br>    case &#39;permissionDenied&#39;:<br>      showPermissionMessage();<br>      break;<br>    case &#39;cancelled&#39;:<br>      break;<br>    case &#39;failed&#39;:<br>      showError(result.error);<br>      break;<br>  }<br>}</pre><p>Compare this with the original implementation.</p><p>Before, the UI had to coordinate multiple dependencies.</p><p>Now, it only handles the result of one application operation.</p><p>This is the main benefit of the Facade pattern.</p><h3>5. Why Not Just Create a Utility Function?</h3><p>You might be thinking:</p><p>“Couldn’t I just create a function called capturePhoto()?&quot;</p><p>Yes, absolutely.</p><p>A Facade doesn’t have to be a class.</p><p>The important idea is <strong>encapsulating subsystem complexity behind a simple interface</strong>, not using a particular syntax.</p><p>However, a Facade becomes especially useful when you want to inject dependencies, test them independently, or provide different implementations.</p><p>For example:</p><pre>const evidenceCapture = new DefaultEvidenceCapture(<br>  cameraPermission,<br>  nativeCamera,<br>  imageProcessor,<br>  attachmentStorage<br>);</pre><p>During testing, you can replace those dependencies with fakes.</p><p>You can also replace the camera implementation without changing the UI.</p><p>The application depends on what the capability does, not how a specific SDK implements it.</p><h3>7. What About Error Handling and Cleanup?</h3><p>Here’s something easy to overlook.</p><p>Capturing a photo doesn’t always succeed.</p><p>The user might cancel.</p><p>Permission might be denied.</p><p>Image processing might fail.</p><p>Storage might run out of space.</p><p>These aren’t just UI problems. Some failures require cleanup of resources created during the operation.</p><p>For example:</p><pre>let processed: ProcessedPhoto | undefined;<br><br>try {<br>  processed = await processor.prepare(photo);<br>  const attachment = await storage.save(<br>    processed,<br>    inspectionId<br>  );<br>  return { kind: &#39;captured&#39;, attachment };<br>} catch (error) {<br>  return {<br>    kind: &#39;failed&#39;,<br>    error: mapCaptureError(error),<br>  };<br>} finally {<br>  if (processed) {<br>    await processor.release(processed);<br>  }<br>}</pre><p>Here, release() is assumed to remove only a temporary processing resource. The storage service must preserve the saved attachment independently.</p><p>The Facade provides a suitable place to coordinate this cleanup because it understands the complete operation.</p><p>For larger workflows, you should also define which component owns temporary files, what happens after a partial save, and whether cancellation requires additional cleanup.</p><p>The UI shouldn’t have to understand these implementation details.</p><h3>8. Avoid Creating a God Facade</h3><p>A common mistake is building one enormous Facade for every native capability.</p><p>For example:</p><pre>class MobileServicesFacade {<br>  capturePhoto() {}<br>  authenticateBiometrics() {}<br>  getLocation() {}<br>  registerNotifications() {}<br>  trackAnalytics() {}<br>  shareFile() {}<br>}</pre><p>This creates a new problem.</p><p>The Facade becomes responsible for unrelated features and grows whenever the application adds another integration.</p><p>Instead, organize Facades around cohesive application capabilities.</p><pre>interface EvidenceCapture {<br>  capturePhoto(): Promise&lt;CaptureResult&gt;;<br>}<br><br>interface BiometricUnlock {<br>  authenticate(): Promise&lt;AuthResult&gt;;<br>}<br><br>interface ReportSharing {<br>  shareReport(id: string): Promise&lt;ShareResult&gt;;<br>}</pre><p>Each interface has one clear purpose.</p><p>This makes implementations easier to understand, replace, and test.</p><h3>9. When Should You Use a Facade?</h3><p>Consider introducing a Facade when:</p><ul><li>A feature requires several SDK or service calls.</li><li>Multiple screens repeat the same integration workflow.</li><li>Platform-specific implementation details are leaking into UI code.</li><li>Operations require coordinated error handling or cleanup.</li><li>You want to replace or test SDK integrations independently.</li></ul><p>But don’t create a Facade for every function.</p><p>If a service already exposes a simple, stable interface and requires no additional coordination, wrapping it in another layer may provide little value.</p><p><strong>The goal isn’t to introduce more abstractions. It’s to reduce the complexity that application features must manage.</strong></p><h3>Final Thoughts</h3><p>The Facade pattern helps by providing one cohesive entry point to a complicated subsystem.</p><p>The UI focuses on user interaction.</p><p>The Facade coordinates the operation.</p><p>Supporting services handle the technical details.</p><p>And when an SDK changes, you can often update the implementation behind the Facade without rewriting every feature that depends on it.</p><p><strong>A good Facade doesn’t make the underlying complexity disappear. It makes that complexity somebody else’s responsibility — behind a well-defined boundary.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8c00dfd9dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 11 — Multicast Delegate Pattern: One Component, Multiple Listeners, Without…]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-11-multicast-delegate-pattern-one-component-multiple-listeners-without-event-76af8d196a1c?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/76af8d196a1c</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 11:24:25 GMT</pubDate>
            <atom:updated>2026-10-11T11:26:43.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Frontend SWE — Part 11 — Multicast Delegate Pattern: One Component, Multiple Listeners, Without Event Chaos</h3><p><em>How to notify multiple consumers without turning your application into a network of hidden dependencies.</em></p><h3>The problem: One delegate is no longer enough</h3><p>Imagine we’re developing a React Native application with a synchronization engine.</p><p>The engine handles a single responsibility: synchronizing pending local data with a remote server.</p><p>When synchronization finishes, several components need to react:</p><ul><li><strong>UI:</strong> Update the synchronization status.</li><li><strong>Analytics:</strong> Record synchronization metrics.</li><li><strong>Diagnostics:</strong> Track failures and performance.</li></ul><p>A traditional Delegate Pattern might look like this:</p><pre>interface SyncDelegate {<br>  onSyncCompleted(duration: number): void;<br>}<br><br>class SyncEngine {<br>  delegate?: SyncDelegate;<br>  completeSync(duration: number) {<br>    this.delegate?.onSyncCompleted(duration);<br>  }<br>}</pre><p>This works when one object is responsible for handling the callback.</p><p>But what happens when three independent components need the same notification?</p><p>We could create a composite delegate that forwards callbacks:</p><pre>class CompositeSyncDelegate implements SyncDelegate {<br>  constructor(<br>    private delegates: SyncDelegate[],<br>  ) {}<br><br>  onSyncCompleted(duration: number) {<br>    for (const delegate of this.delegates) {<br>      delegate.onSyncCompleted(duration);<br>    }<br>  }<br>}</pre><p>This is a valid solution, particularly when the list of delegates is fixed.</p><p>However, it becomes inconvenient when consumers have different lifetimes and must register or unregister independently.</p><p><strong>This is where the Multicast Delegate Pattern becomes useful.</strong></p><p>Instead of maintaining one delegate, the synchronization engine maintains a collection of delegates.</p><p>One component produces a notification. Multiple registered consumers receive it.</p><h3>The solution: Multicast Delegate</h3><p>Multicast Delegate extends the traditional delegate relationship from one-to-one to one-to-many.</p><p>The key idea is simple:</p><p><strong>The synchronization engine owns the event, but it does not own the behavior of every consumer.</strong></p><p>Let’s define the delegate contract:</p><pre>interface SyncDelegate {<br>  onSyncCompleted(duration: number): void;<br>}</pre><p>Now implement multicast support:</p><pre>class SyncEngine {<br>  private delegates = new Set&lt;SyncDelegate&gt;();<br><br>  addDelegate(delegate: SyncDelegate) {<br>    this.delegates.add(delegate);<br>  }<br>  removeDelegate(delegate: SyncDelegate) {<br>    this.delegates.delete(delegate);<br>  }<br>  completeSync(duration: number) {<br>    for (const delegate of [...this.delegates]) {<br>      delegate.onSyncCompleted(duration);<br>    }<br>  }<br>}</pre><p>Our consumers can implement the same contract independently:</p><pre>const analyticsDelegate: SyncDelegate = {<br>  onSyncCompleted(duration) {<br>    analytics.track(&#39;sync_completed&#39;, { duration });<br>  },<br>};<br><br>const diagnosticsDelegate: SyncDelegate = {<br>  onSyncCompleted(duration) {<br>    logger.info(`Sync took ${duration}ms`);<br>  },<br>};<br><br>syncEngine.addDelegate(analyticsDelegate);<br>syncEngine.addDelegate(diagnosticsDelegate);</pre><p>When synchronization completes, both delegates receive the notification.</p><p>The synchronization engine does not need to know what analytics or diagnostics do internally.</p><p>It knows only the SyncDelegate contract.</p><p>This gives us three benefits:</p><ol><li><strong>Decoupling:</strong> The engine does not directly depend on analytics or diagnostics.</li><li><strong>Extensibility:</strong> New listeners can be added without modifying the engine.</li><li><strong>Lifecycle control:</strong> Consumers can register and unregister independently.</li></ol><p>The implementation deliberately keeps callbacks synchronous. A production version must also define how listener exceptions are handled, especially if one failure should not prevent other delegates from being notified.</p><h3>Wait, isn’t this just the Observer Pattern?</h3><p>Yes, structurally, they are extremely similar.</p><p>In fact, Multicast Delegate can be understood as a specialized form of the Observer Pattern.</p><p>Both maintain a collection of subscribers and notify them when something happens.</p><p>The difference is primarily in how we express the relationship and its responsibilities.</p><h3>Observer Pattern</h3><p>The Observer Pattern describes a relationship between a subject and its observers.</p><p>When the subject changes, observers receive notifications.</p><pre>interface Observer&lt;T&gt; {<br>  update(value: T): void;<br>}</pre><p>The contract is generic. The observer receives information and determines how to react.</p><h3>Multicast Delegate Pattern</h3><p>Multicast Delegate typically uses a domain-specific callback contract:</p><pre>interface SyncDelegate {<br>  onSyncStarted(): void;<br>  onSyncProgress(completed: number, total: number): void;<br>  onSyncCompleted(duration: number): void;<br>}</pre><p>The callback names describe events in the synchronization engine’s lifecycle.</p><p>Instead of a generic update(value), the engine invokes meaningful operations on registered delegates.</p><p>However, <strong>named callbacks are not an exclusive feature of Multicast Delegate</strong>. Observer interfaces can also have strongly typed, domain-specific methods.</p><p>The distinction is about architectural intent, not a completely different notification mechanism.</p><h3>The architectural boundary matters more than the implementation</h3><p>A common mistake is introducing a global notification mechanism:</p><pre>events.emit(&#39;sync-completed&#39;, result);<br>events.emit(&#39;user-updated&#39;, user);<br>events.emit(&#39;payment-failed&#39;, error);</pre><p>Eventually, unrelated features begin communicating through the same event system.</p><p>The application becomes harder to understand because important dependencies are no longer obvious.</p><p>Who handles payment-failed?</p><p>Does a listener trigger another event?</p><p>Does the order of registration affect the result?</p><p>These questions become difficult to answer when the event system has no clear ownership boundary.</p><p>Multicast Delegate should not become a global event bus with a different name.</p><p>Instead, the delegate collection belongs to the component responsible for producing the notifications.</p><p>For example:</p><pre>class SyncEngine {<br>  private delegates = new Set&lt;SyncDelegate&gt;();<br>}</pre><p>The engine owns its delegates.</p><p>Consumers receive notifications only if they have access to that engine and explicitly register.</p><p>This keeps communication <strong>local, bounded, and discoverable</strong>.</p><h3>Multicast is notification, not orchestration</h3><p>There’s another important distinction.</p><p>Suppose that after synchronization completes, the application must:</p><ol><li>Save the synchronization result.</li><li>Update the local database.</li><li>Navigate to another screen.</li></ol><p>These operations may have strict dependencies.</p><p>Using multicast callbacks to coordinate them would be dangerous:</p><pre>syncEngine.addDelegate(databaseDelegate);<br>syncEngine.addDelegate(navigationDelegate);</pre><p>What if navigation executes before the database update finishes?</p><p>What if the first operation fails?</p><p>What if a delegate performs asynchronous work?</p><p>Multicast notification does not automatically provide execution ordering, transactional guarantees, or error recovery.</p><p>For workflows where one step depends on another, use an explicit orchestrator, coordinator, or use case.</p><pre>async function completeSyncFlow() {<br>  const result = await syncEngine.sync();<br><br>  await database.save(result);<br>  navigation.navigate(&#39;SyncSuccess&#39;);<br>}</pre><p>Once the required workflow completes, independent consumers can still receive a notification for analytics or diagnostics.</p><p><strong>Use orchestration for operations that must happen. Use multicast notification for independent reactions to something that happened.</strong></p><p>That distinction prevents event-driven communication from becoming event-driven chaos.</p><h3>Events are not UI state</h3><p><strong>Case 1: Synchronization progress</strong></p><p>The UI needs to know the current progress whenever it renders.</p><p>If the screen mounts after synchronization has already started, simply subscribing to future events is insufficient. The screen also needs the current snapshot.</p><p>A state store with React-compatible subscriptions, such as one integrated through useSyncExternalStore, is a better primary abstraction.</p><p><strong>Case 2: Synchronization completed</strong></p><p>Analytics and diagnostics simply need to know that completion occurred.</p><p>They don’t necessarily need to retain a current value.</p><p>A multicast callback is a natural fit.</p><p>A practical architecture might look like this:</p><pre>SyncEngine<br>    |<br>    +-- Current State --&gt; SyncStore --&gt; React UI<br>    |<br>    +-- Delegates<br>           |<br>           +-- Analytics<br>           |<br>           +-- Diagnostics</pre><p>The store answers:</p><p>“What is the current synchronization status?”</p><p>The delegates answer:</p><p>“What happened in the synchronization lifecycle?”</p><p>Separating these responsibilities makes both easier to reason about.</p><h3>Lifecycle management is not optional</h3><p>Each registered delegate should have a clearly defined owner.</p><p>If a delegate belongs to a React component, unregister it when that component unmounts.</p><pre>useEffect(() =&gt; {<br>  syncEngine.addDelegate(syncDelegate);<br><br>  return () =&gt; {<br>    syncEngine.removeDelegate(syncDelegate);<br>  };<br>}, [syncEngine, syncDelegate]);</pre><p>The delegate identity should be stable when appropriate, so the effect does not repeatedly register and unregister because a new object was created on each render.</p><p>Long-lived services can register their delegates when the service starts and remove them when it is disposed.</p><p>Without cleanup, the engine may retain stale listeners, cause duplicate notifications, or keep objects alive unnecessarily.</p><h3>When should you avoid Multicast Delegate?</h3><p>Not every one-to-many relationship requires multicast delegates.</p><p>Avoid introducing them when:</p><ul><li><strong>There is only one responsible consumer.</strong> A normal delegate is simpler.</li><li><strong>Consumers need current state.</strong> Use an observable state container or store.</li><li><strong>Consumers need complex stream operations.</strong> Consider RxJS.</li><li><strong>Operations have strict ordering or dependencies.</strong> Use explicit orchestration.</li><li><strong>Notifications cross unrelated feature boundaries.</strong> Reconsider whether a local delegate contract is the correct abstraction.</li></ul><p>The goal is not to maximize the number of patterns in the codebase.</p><p>It’s to select the smallest abstraction that expresses the responsibility clearly.</p><h3>Final thoughts</h3><p>Multicast Delegate is not a replacement for the Observer Pattern, or state management.</p><p>It is a way to extend a delegate relationship so that one component can notify multiple independent consumers.</p><p>Its real architectural value appears when we preserve three boundaries:</p><p><strong>Ownership:</strong> The component that produces notifications owns the delegate collection.</p><p><strong>Responsibility:</strong> Delegates react independently; they should not secretly orchestrate critical workflows.</p><p><strong>Lifecycle:</strong> Registration and cleanup are explicit and predictable.</p><p>When these boundaries are clear, multicast delegates provide a useful communication mechanism without requiring a global event bus or unnecessarily complex reactive infrastructure.</p><p><strong>The important question isn’t “How do I notify multiple listeners?”</strong></p><p><strong>It’s “Who owns this notification, and what responsibilities should its listeners be allowed to have?”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76af8d196a1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 10 — State Pattern]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-10-state-pattern-545ef4f83c33?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/545ef4f83c33</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 16:08:41 GMT</pubDate>
            <atom:updated>2026-10-05T16:08:41.764Z</atom:updated>
            <content:encoded><![CDATA[<p>When an object behaves differently depending on its current state, that behavior may belong to the state itself.</p><p>Frontend applications have state everywhere.</p><p>Consider a simple inspection workflow:</p><pre>type InspectionStatus =<br>  | &#39;draft&#39;<br>  | &#39;submitted&#39;<br>  | &#39;approved&#39;<br>  | &#39;rejected&#39;;</pre><p>At first, this is easy to manage.</p><p>The rules might be:</p><ul><li>A draft inspection can be edited and submitted.</li><li>A submitted inspection can be approved or rejected.</li><li>A rejected inspection can be edited and resubmitted.</li><li>An approved inspection can no longer be edited.</li></ul><p>For a small application, simple conditions are perfectly reasonable:</p><pre>if (inspection.status === &#39;draft&#39;) {<br>  // ...<br>}<br>if (inspection.status === &#39;submitted&#39;) {<br>  // ...<br>}<br>if (inspection.status === &#39;approved&#39;) {<br>  // ...<br>}</pre><p>The problem is not the if statement.</p><p>The problem begins when many parts of the application need to understand the same state rules.</p><p>That is where the State Pattern can become useful.</p><h3>Start with the simple solution</h3><p>Imagine an Inspection object:</p><pre>type InspectionStatus =<br>  | &#39;draft&#39;<br>  | &#39;submitted&#39;<br>  | &#39;approved&#39;<br>  | &#39;rejected&#39;;<br><br>class Inspection {<br>  constructor(public status: InspectionStatus) {}<br>  submit() {<br>    if (<br>      this.status === &#39;draft&#39; ||<br>      this.status === &#39;rejected&#39;<br>    ) {<br>      this.status = &#39;submitted&#39;;<br>      return;<br>    }<br>    throw new Error(&#39;Cannot submit inspection&#39;);<br>  }<br>  approve() {<br>    if (this.status === &#39;submitted&#39;) {<br>      this.status = &#39;approved&#39;;<br>      return;<br>    }<br>    throw new Error(&#39;Cannot approve inspection&#39;);<br>  }<br>}</pre><p>There is nothing wrong with this code.</p><p>For a small workflow, I would probably keep it exactly like this.</p><p>But now imagine that the workflow grows:</p><pre>submit()<br>approve()<br>reject()<br>edit()<br>cancel()<br>retry()<br>archive()<br>attachPhoto()<br>resubmit()</pre><p>Each method may now need another status check:</p><pre>if (this.status === &#39;draft&#39;) {<br>  // ...<br>} else if (this.status === &#39;submitted&#39;) {<br>  // ...<br>} else if (this.status === &#39;rejected&#39;) {<br>  // ...<br>}</pre><p>Over time, the Inspection object becomes responsible for understanding:</p><ul><li>Every possible state, every valid operation, every invalid operation, every allowed transition.</li></ul><p>Instead of focusing on the operation itself, the object repeatedly asks:</p><blockquote><em>What state am I in, and what am I allowed to do in this state?</em></blockquote><p>That is a strong signal that the State Pattern may help.</p><h3>State can be more than a value</h3><p>This distinction is important.</p><p>Sometimes state is simply data:</p><pre>status === &#39;loading&#39;</pre><p>But sometimes state represents a set of capabilities.</p><p>For example:</p><pre>Draft<br>  can edit<br>  can attach<br>  can submit<br><br>Submitted<br>  can view<br>  can cancel<br>  cannot edit<br><br>Approved<br>  can view<br>  can archive<br>  cannot edit<br><br>Rejected<br>  can edit<br>  can resubmit</pre><p>In this case, the state does more than tell us where the object currently is.</p><p>It determines what the object is allowed to do.</p><p>That is where the State Pattern becomes interesting.</p><h3>What is the State Pattern?</h3><p>The core idea is simple:</p><blockquote><em>Move state-specific behavior into the object representing that state.</em></blockquote><p>Instead of writing:</p><pre>if (status === &#39;draft&#39;) {<br>  // draft behavior<br>}</pre><p>we introduce an object representing the draft state:</p><pre>new DraftState()</pre><p>The state object itself knows what behavior is allowed.</p><p>A useful mental model is:</p><pre>Inspection<br>    │<br>    │ delegates<br>    ▼<br>Current State<br>    │<br>    │ decides<br>    ▼<br>Behavior + Transition</pre><p>The main object no longer needs to understand every state-specific rule.</p><p>It delegates those decisions to its current state.</p><h3>Building the pattern step by step</h3><p>First, define the operations supported by an inspection state:</p><pre>interface InspectionState {<br>  submit(context: Inspection): void;<br>  approve(context: Inspection): void;<br>}</pre><p>Now implement the draft state:</p><pre>class DraftState implements InspectionState {<br>  submit(context: Inspection) {<br>    context.transitionTo(new SubmittedState());<br>  }<br><br>  approve() {<br>    throw new Error(<br>      &#39;Draft inspection cannot be approved&#39;,<br>    );<br>  }<br>}</pre><p>The draft state now owns its rules:</p><pre>submit   -&gt; allowed<br>approve  -&gt; not allowed</pre><p>Next, implement the submitted state:</p><pre>class SubmittedState implements InspectionState {<br>  submit() {<br>    throw new Error(<br>      &#39;Inspection has already been submitted&#39;,<br>    );<br>  }<br><br>  approve(context: Inspection) {<br>    context.transitionTo(new ApprovedState());<br>  }<br>}</pre><p>Its rules are different:</p><pre>submit   -&gt; not allowed<br>approve  -&gt; allowed</pre><p>Finally, the Inspection object delegates operations to the current state:</p><pre>class Inspection {<br>  constructor(<br>    private state: InspectionState,<br>  ) {}<br>  transitionTo(state: InspectionState) {<br>    this.state = state;<br>  }<br>  submit() {<br>    this.state.submit(this);<br>  }<br>  approve() {<br>    this.state.approve(this);<br>  }<br>}</pre><p>Now we can use it like this:</p><pre>const inspection = new Inspection(<br>  new DraftState(),<br>);<br>inspection.submit();<br>inspection.approve();</pre><p>The lifecycle becomes:</p><pre>Draft<br>  │<br>  │ submit()<br>  ▼<br>Submitted<br>  │<br>  │ approve()<br>  ▼<br>Approved</pre><p>Notice what is missing from Inspection:</p><pre>if (status === &#39;draft&#39;) {}<br><br>if (status === &#39;submitted&#39;) {}<br><br>if (status === &#39;approved&#39;) {}</pre><p>The context no longer decides what each state allows.</p><p>It delegates.</p><h3>Where did the complexity go?</h3><p>This is an important point.</p><p>The State Pattern does not remove complexity.</p><p>It reorganizes it.</p><p>Before:</p><pre>Inspection<br> ├── understands Draft<br> ├── understands Submitted<br> ├── understands Approved<br> ├── understands Rejected<br> ├── understands every transition<br> └── understands every valid operation</pre><p>After:</p><pre>Inspection<br> └── delegates behavior<br>DraftState<br> └── understands draft behavior<br>SubmittedState<br> └── understands submitted behavior<br>ApprovedState<br> └── understands approved behavior<br>RejectedState<br> └── understands rejected behavior</pre><p>Each state owns the behavior related to that state.</p><p>That is the real purpose of the pattern.</p><h3>Why this matters in frontend applications</h3><p>Consider the UI for the same inspection workflow.</p><p>When the inspection is in draft, the user may be allowed to:</p><pre>Edit<br>Attach photo<br>Submit</pre><p>When it is submitted:</p><pre>View<br>Cancel</pre><p>When it is approved:</p><pre>View<br>Archive</pre><p>When it is rejected:</p><pre>Edit<br>Resubmit</pre><p>Without a clear state model, these rules often spread throughout the application.</p><p>One component may contain:</p><pre>if (inspection.status !== &#39;approved&#39;) {<br>  showEditButton();<br>}</pre><p>Another may contain:</p><pre>if (<br>  inspection.status === &#39;draft&#39; ||<br>  inspection.status === &#39;rejected&#39;<br>) {<br>  enableSubmitButton();<br>}</pre><p>And somewhere else:</p><pre>if (inspection.status === &#39;submitted&#39;) {<br>  allowCancellation();<br>}</pre><p>Now several unrelated parts of the application understand pieces of the same workflow.</p><p>That becomes dangerous when the backend introduces another state:</p><pre>&#39;underReview&#39;</pre><p>You may now need to search the codebase for every condition involving:</p><pre>status === ...</pre><p>and decide whether underReview should also be handled there.</p><p>With the State Pattern, state-specific behavior has a more natural place to live:</p><pre>UnderReviewState</pre><p>The workflow becomes easier to extend because the new behavior is concentrated around the new state instead of being scattered across unrelated components.</p><h3>Do you always need classes?</h3><p>No.</p><p>This is especially important in frontend development.</p><p>Do not turn this:</p><pre>type RequestStatus =<br>  | &#39;idle&#39;<br>  | &#39;loading&#39;<br>  | &#39;success&#39;<br>  | &#39;error&#39;;</pre><p>into:</p><pre>IdleState<br>LoadingState<br>SuccessState<br>ErrorState</pre><p>just because you learned the State Pattern.</p><p>For simple UI state, a discriminated union, reducer, signal, store, or state machine may already express the model clearly.</p><p>For example:</p><pre>type RequestState =<br>  | { type: &#39;idle&#39; }<br>  | { type: &#39;loading&#39; }<br>  | { type: &#39;success&#39;; data: User[] }<br>  | { type: &#39;error&#39;; error: Error };</pre><p>This is already clear.</p><p>There is probably no reason to introduce separate state objects.</p><p>The State Pattern becomes more valuable when individual states own meaningful behavior.</p><p>For example:</p><pre>class SubmittedInspectionState {<br>  approve() {}<br>  reject() {}<br>  cancel() {}<br>}</pre><pre>class ApprovedInspectionState {<br>  archive() {}<br>}</pre><pre>class RejectedInspectionState {<br>  edit() {}<br>  resubmit() {}<br>}</pre><p>Now each state represents a different set of responsibilities.</p><p>At that point, the abstraction may be worth the additional structure.</p><h3>When should you use the State Pattern?</h3><p>Consider it when:</p><ul><li>Different states allow significantly different operations</li><li>The same state checks appear throughout the codebase</li><li>Individual operations contain increasingly complicated if/else logic</li><li>Adding a new state requires changing many unrelated files</li><li>Invalid operations should be rejected by the domain object</li><li>The object has a meaningful lifecycle.</li></ul><p>Typical examples include:</p><pre>Order<br>Draft -&gt; Paid -&gt; Shipped -&gt; Delivered<br><br>Payment<br>Idle -&gt; Processing -&gt; Success -&gt; Failed<br><br>Document<br>Draft -&gt; Review -&gt; Approved -&gt; Rejected<br><br>Upload<br>Idle -&gt; Uploading -&gt; Paused -&gt; Completed<br><br>Media<br>Stopped -&gt; Playing -&gt; Paused<br><br>Connection<br>Disconnected -&gt; Connecting -&gt; Connected</pre><p>These are good candidates because the object’s state changes which operations make sense.</p><h3>When should you not use it?</h3><p>Do not use the State Pattern simply because something has state.</p><p>Every frontend application has state.</p><p>This usually does not need it:</p><pre>const [isOpen, setIsOpen] = useState(false);</pre><p>Neither does this:</p><pre>const [selectedTab, setSelectedTab] =<br>  useState(&#39;home&#39;);</pre><p>And a simple request lifecycle often does not need it either:</p><pre>type Status =<br>  | &#39;idle&#39;<br>  | &#39;loading&#39;<br>  | &#39;success&#39;<br>  | &#39;error&#39;;</pre><p>The State Pattern introduces additional concepts:</p><pre>State interface<br>State implementations<br>Context<br>Delegation<br>Transitions</pre><p>Those abstractions have a cost.</p><p>Use the pattern only when it removes more complexity than it introduces.</p><h3>Final mental model</h3><p>Do not remember the State Pattern as:</p><blockquote><em>Replace </em><em>if statements with classes.</em></blockquote><p>That is not the goal.</p><p>Remember it as:</p><blockquote><em>When behavior changes significantly based on state, let the state own that behavior.</em></blockquote><p>Without the pattern:</p><pre>if (state === &#39;draft&#39;) {<br>  doDraftBehavior();<br>}</pre><pre>if (state === &#39;submitted&#39;) {<br>  doSubmittedBehavior();<br>}</pre><p>With the pattern:</p><pre>context.doSomething();</pre><p>Internally:</p><pre>Context<br>   │<br>   ▼<br>Current State<br>   │<br>   ▼<br>State-specific behavior<br>   │<br>   ▼<br>Optional transition<br>   │<br>   ▼<br>Next State</pre><p>So whenever you repeatedly see:</p><pre>if (status === ...)</pre><p>across several operations, ask:</p><blockquote><em>Is this condition really part of the operation, or does this behavior belong to the state itself?</em></blockquote><p>That question captures the heart of the State Pattern.</p><p>The goal is not to eliminate every if.</p><p>The goal is to prevent one object — or your entire frontend — from needing to understand the behavior of every possible state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=545ef4f83c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 8 — Iterator, Async Iterator, and Streaming Data]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-8-iterator-async-iterator-and-streaming-data-0074fbd923ba?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/0074fbd923ba</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 11:23:57 GMT</pubDate>
            <atom:updated>2026-10-03T11:23:57.581Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Iterator separates how consumers traverse values from how those values are stored or produced.</em></p><h3>A real-life scenario</h3><p>Imagine a technician opens the <strong>Assigned Inspections</strong> screen.</p><p>There may be thousands of inspections, but the backend only returns 50 at a time.</p><p>Without an abstraction, the application needs to manage:</p><pre>fetch page<br>↓<br>read next cursor<br>↓<br>fetch next page<br>↓<br>map DTOs<br>↓<br>repeat</pre><p>But the consumer usually does not care about pages or cursors.</p><p>It simply wants inspections:</p><pre>for await (const inspection of assignedInspections(api)) {<br>  store.add(inspection);<br>}</pre><p>The Async Iterator hides the pagination details and exposes one continuous sequence.</p><p>That is the core idea of Iterator:</p><blockquote><strong><em>The consumer works with values without knowing how those values are reached.</em></strong></blockquote><h3>Iterator</h3><p>For synchronous data, JavaScript supports Iterator through:</p><pre>Symbol.iterator</pre><p>For example, inspection questions may be nested inside sections:</p><pre>class InspectionQuestions implements Iterable&lt;Question&gt; {<br>  constructor(<br>    private readonly sections: readonly InspectionSection[],<br>  ) {}<br><br>  *[Symbol.iterator](): Iterator&lt;Question&gt; {<br>    for (const section of this.sections) {<br>      yield* questionsIn(section);<br>    }<br>  }<br>}</pre><p>Consumers simply write:</p><pre>for (const question of inspectionQuestions) {<br>  validateQuestion(question);<br>}</pre><p>The iterator owns traversal.</p><p>The consumer owns business behavior.</p><h3>Async Iterator</h3><p>When getting the next value requires asynchronous work, use Async Iterator.</p><p>Common examples include:</p><ul><li>Pagination</li><li>Database cursors</li><li>Large files</li><li>Pull-based streams</li></ul><p>A practical React Native use case is the <strong>Assigned Inspections</strong> screen from earlier.</p><p>Instead of putting pagination logic inside the ViewModel or UI, keep it inside the data layer:</p><pre>async function* assignedInspections(<br>  api: AssignmentApi,<br>  signal?: AbortSignal,<br>): AsyncGenerator&lt;InspectionSummary&gt; {<br>  // Keep track of the backend pagination cursor.<br>  // `undefined` means &quot;load the first page&quot;.<br>  let cursor: string | undefined;<br><br>  do {<br>    // Pause the async generator while the next page is being fetched.<br>    // During this await, JavaScript can continue processing other work.<br>    const page = await api.fetchAssignments({<br>      cursor,<br>      signal,<br>    });<br><br>    // Yield items one by one instead of returning the whole page.<br>    // Each `yield` pauses the generator and gives one value back<br>    // to the consumer.<br>    for (const dto of page.items) {<br>      yield toInspectionSummary(dto);<br>    }<br><br>    // Store the cursor for the next page.<br>    // If there is no next cursor, iteration will finish.<br>    cursor = page.nextCursor;<br><br>    // Continue only when another page exists<br>    // and the consumer has not cancelled the operation.<br>  } while (cursor &amp;&amp; !signal?.aborted);<br>}</pre><p>Now the consumer only works with inspections:</p><pre>for await (<br>  const inspection of assignedInspections(api, signal)<br>) {<br>  store.add(inspection);<br>}</pre><p>The architecture becomes:</p><pre>Assignment API<br>      ↓<br>Async Iterator<br>      ↓<br>ViewModel / Store<br>      ↓<br>UI</pre><p>The important part is that the ViewModel does not need to know:</p><ul><li>How many items exist per page</li><li>Whether the backend uses cursors</li><li>How the next page is requested</li><li>How DTOs are converted into domain models</li></ul><p>That knowledge stays inside the iterator.</p><p>If the backend later changes its pagination strategy, the consumer can remain unchanged.</p><p>This is where Iterator becomes useful in a real project:</p><blockquote><strong><em>Traversal and pagination logic stay behind one boundary, while the rest of the application works with a simple sequence of domain values.</em></strong></blockquote><h3>Streaming Data</h3><p>Async Iterator also works well for pull-based streams:</p><pre>for await (const chunk of readChunks(source)) {<br>  await processChunk(chunk);<br>}</pre><p>The consumer processes values one by one instead of loading everything first.</p><p>This works well when the consumer naturally asks for the next value when it is ready.</p><h3>Async Iterator vs Observer</h3><p>A useful rule is:</p><pre>Consumer asks for next value<br>        ↓<br>Iterator / Async Iterator</pre><pre>Producer announces new value<br>        ↓<br>Observer</pre><p>Pagination fits Async Iterator well.</p><p>Live UI events, sensors, or WebSocket notifications often fit Observer better.</p><p>The key question is:</p><blockquote><strong><em>Who controls the flow?</em></strong></blockquote><h3>Cancellation and Cleanup</h3><p>Async iteration should stop when the consumer no longer needs data.</p><p>Use AbortSignal for cancellation.</p><p>If the iterator owns a resource, clean it up with try/finally.</p><pre>async function* records(database: Database) {<br>  const cursor = await database.openCursor();<br><br>  try {<br>    while (await cursor.hasNext()) {<br>      yield await cursor.next();<br>    }<br>  } finally {<br>    await cursor.close();<br>  }<br>}</pre><p>This prevents resources from continuing to run after the consumer has stopped.</p><h3>Key Decisions</h3><p>Use Iterator when traversal logic should be hidden.</p><p>Use Async Iterator when producing the next value requires asynchronous work.</p><p>Good use cases include:</p><ul><li>Nested structures</li><li>Pagination</li><li>Database cursors</li><li>Large files</li><li>Pull-based streams</li></ul><p>A simple rule to remember:</p><blockquote><strong><em>Iterator hides how values are reached.</em></strong></blockquote><p>The consumer should only need to care about the next value.</p><p>In a real project, that means infrastructure details such as pagination, traversal, or data production stay behind the iterator, while the application works with a clean sequence of domain values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0074fbd923ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 7 — Adapter at Every External Boundary]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-7-adapter-at-every-external-boundary-2f85b9b9cba2?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f85b9b9cba2</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 12:29:37 GMT</pubDate>
            <atom:updated>2026-09-26T12:29:37.739Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Adapters prevent a vendor, transport, or native API from defining the language of the application.</em></p><p>External systems rarely expose exactly the interface your application wants.</p><p>A native SDK may return vendor-specific constants. An API may use transport-specific field names. A third-party library may expose errors, callbacks, and types that make sense to the library but not to your application.</p><p>The Adapter pattern creates a boundary between those two worlds.</p><p>The idea is simple:</p><blockquote><strong><em>Your application defines the interface it needs. The adapter translates the external system into that interface.</em></strong></blockquote><h3>The boundary problem</h3><p>Imagine a React Native application needs the user’s current location.</p><p>A native location SDK might expose:</p><ul><li>Numeric permission constants</li><li>Nullable coordinates</li><li>Vendor-specific error codes</li><li>Platform-specific permission states</li><li>SDK-specific response objects</li></ul><p>If those details spread into your ViewModels, use cases, and components, your application becomes coupled to that SDK.</p><p>Instead of asking:</p><pre>nativeLocationSdk.currentPosition();</pre><p>the application should ask a question in its own language:</p><blockquote><em>Can I obtain the current location?</em></blockquote><p>Define that contract first.</p><pre>type LocationResult =<br>  | {<br>      kind: &#39;available&#39;;<br>      point: GeoPoint;<br>      accuracyMeters: number;<br>    }<br>  | {<br>      kind: &#39;permissionDenied&#39;;<br>      canOpenSettings: boolean;<br>    }<br>  | {<br>      kind: &#39;unavailable&#39;;<br>      reason: LocationUnavailableReason;<br>    };<br><br>interface CurrentLocation {<br>  request(): Promise&lt;LocationResult&gt;;<br>}</pre><p>Notice what the contract does <strong>not</strong> contain:</p><ul><li>SDK permission constants</li><li>Native response types</li><li>Vendor error codes</li><li>Platform-specific enum</li></ul><p>The application owns the abstraction.</p><p>That is the first important rule:</p><blockquote><strong><em>Define what the application needs before adapting what the dependency provides.</em></strong></blockquote><h3>The adapter</h3><p>Now we can implement the application contract using the native SDK.</p><pre>class NativeLocationAdapter implements CurrentLocation {<br>  constructor(<br>    private readonly sdk: NativeLocationSdk,<br>  ) {}<br><br>  async request(): Promise&lt;LocationResult&gt; {<br>    try {<br>      const permission =<br>        await this.sdk.requestPermission();<br>      if (permission !== this.sdk.GRANTED) {<br>        return mapPermission(permission);<br>      }<br>      const raw =<br>        await this.sdk.currentPosition();<br>      return {<br>        kind: &#39;available&#39;,<br>        point: geoPoint(<br>          raw.coords.latitude,<br>          raw.coords.longitude,<br>        ),<br>        accuracyMeters:<br>          raw.coords.accuracy,<br>      };<br>    } catch (error: unknown) {<br>      return mapLocationFailure(error);<br>    }<br>  }<br>}</pre><p>The adapter sits between the application and the dependency.</p><pre>Application<br>    ↓<br>CurrentLocation<br>    △<br>    │ implements<br>NativeLocationAdapter<br>    ↓<br>Native Location SDK</pre><p>The application knows only about:</p><pre>CurrentLocation</pre><p>The adapter knows about:</p><pre>NativeLocationSdk</pre><p>That separation is the pattern.</p><h3>Adapter is more than renaming methods</h3><p>A weak adapter might look like this:</p><pre>class LocationAdapter {<br>  constructor(<br>    private readonly sdk: NativeLocationSdk,<br>  ) {}<br><br>  getLocation() {<br>    return this.sdk.currentPosition();<br>  }<br>}</pre><p>That changes the method name, but the SDK response still leaks into the application.</p><p>The application may still need to understand:</p><pre>response.coords.latitude;<br>response.coords.longitude;<br>sdk.PERMISSION_BLOCKED;<br>error.code;</pre><p>That is not a useful boundary.</p><p>A good adapter translates <strong>meaning</strong>, not just method names.</p><p>For example, the SDK might expose:</p><pre>GRANTED<br>DENIED<br>BLOCKED<br>RESTRICTED<br>UNAVAILABLE</pre><p>while the application only needs:</p><pre>available<br>permissionDenied<br>unavailable</pre><p>The adapter translates those external concepts into application concepts.</p><pre>SDK enum<br>   ↓<br>Adapter<br>   ↓<br>Application result</pre><p>The feature does not need to understand how the SDK represents permission states.</p><h3>Why this matters</h3><p>Suppose the application directly depends on the SDK.</p><pre>Component<br>   ↓<br>ViewModel<br>   ↓<br>Native SDK</pre><p>Now the ViewModel may contain logic such as:</p><pre>if (<br>  permission ===<br>  NativeLocationSdk.PERMISSION_BLOCKED<br>) {<br>  // ...<br>}</pre><p>Later, you replace the location library.</p><p>The new SDK uses different constants and different response objects.</p><p>You may now need to update multiple parts of the application.</p><p>With an adapter:</p><pre>Component<br>   ↓<br>ViewModel<br>   ↓<br>CurrentLocation<br>   ↓<br>NativeLocationAdapter<br>   ↓<br>Native SDK</pre><p>the replacement happens mostly at the boundary.</p><p>You can create:</p><pre>class NewLocationAdapter<br>  implements CurrentLocation {<br>  // ...<br>}</pre><p>and the rest of the application can continue using:</p><pre>CurrentLocation</pre><p>unchanged.</p><p>That is the real benefit of Adapter:</p><blockquote><strong><em>External change is absorbed at the boundary instead of spreading through the application.</em></strong></blockquote><h3>The same idea applies to APIs</h3><p>Adapter is not limited to native SDKs.</p><p>The same principle applies to HTTP APIs.</p><p>Imagine the backend returns:</p><pre>type InspectionDto = {<br>  inspection_id: string;<br>  state: &#39;NEW&#39; | &#39;SUBMITTED&#39;;<br>};</pre><p>Your application might want:</p><pre>type Inspection = {<br>  id: InspectionId;<br>  status: InspectionStatus;<br>};</pre><p>Keep the transport representation at the boundary.</p><pre>function toInspection(<br>  dto: InspectionDto,<br>): Inspection {<br>  return {<br>    id: inspectionId(<br>      dto.inspection_id,<br>    ),<br>    status:<br>      toInspectionStatus(dto.state),<br>  };<br>}</pre><p>Now if the backend changes:</p><pre>inspection_id</pre><p>to:</p><pre>inspectionId</pre><p>the mapping changes.</p><p>Your component, ViewModel, use case, and domain model should not need to know.</p><pre>Backend DTO<br>    ↓<br>Boundary<br>    ↓<br>Application model</pre><p>The principle is the same:</p><blockquote><strong><em>Do not let the external representation become the application’s representation.</em></strong></blockquote><h3>Normalize external errors</h3><p>Errors are also part of an external system’s language.</p><p>A native SDK might expose:</p><pre>LOCATION_101<br>LOCATION_105<br>PERMISSION_BLOCKED</pre><p>An HTTP client might expose:</p><pre>ERR_NETWORK<br>401<br>404<br>409<br>500</pre><p>Feature code should normally not make decisions using those values directly.</p><p>Instead, translate them into something meaningful to the application.</p><pre>type LocationFailure =<br>  | {<br>      kind: &#39;permissionDenied&#39;;<br>    }<br>  | {<br>      kind: &#39;unavailable&#39;;<br>    }<br>  | {<br>      kind: &#39;unexpected&#39;;<br>      cause: unknown;<br>    };</pre><p>Then the application can reason about:</p><pre>if (<br>  failure.kind ===<br>  &#39;permissionDenied&#39;<br>) {<br>  // ...<br>}</pre><p>instead of:</p><pre>if (<br>  error.code === &#39;LOCATION_105&#39;<br>) {<br>  // ...<br>}</pre><p>The vendor’s error model stays behind the boundary.</p><h3>Adapter should not own business workflow</h3><p>An adapter translates external behavior.</p><p>It should not decide what the application should do next.</p><p>This is appropriate:</p><pre>Adapter:<br>&quot;Permission is denied.&quot;</pre><p>This is not:</p><pre>Adapter:<br>&quot;Navigate to Settings,<br>cancel the inspection,<br>and show an alert.&quot;</pre><p>Navigation and workflow decisions belong to higher layers such as:</p><ul><li>Use Cases</li><li>ViewModels</li><li>Coordinators</li></ul><p>The adapter reports application-friendly information.</p><p>The application decides how to react.</p><h3>Adapter vs Mapper</h3><p>These concepts are related, but they are not exactly the same.</p><p>A mapper usually transforms data:</p><pre>function toInspection(<br>  dto: InspectionDto,<br>): Inspection {<br>  // ...<br>}</pre><p>An adapter makes an external interface behave like the interface your application expects:</p><pre>class NativeLocationAdapter<br>  implements CurrentLocation {<br>  // ...<br>}</pre><p>A mapper can live inside an adapter.</p><pre>External SDK / API<br>       ↓<br>     Adapter<br>       ↓<br>     Mapper<br>       ↓<br>Application model</pre><p>You do not need a class for every transformation.</p><p>Use a function when the job is only data transformation.</p><p>Use an adapter object when you are adapting the behavior of an external client or SDK.</p><h3>Vendor types leak into feature code</h3><pre>if (<br>  status ===<br>  sdk.PERMISSION_BLOCKED<br>) {<br>  // ...<br>}</pre><p>The feature now understands the vendor.</p><h3>The adapter only renames methods</h3><pre>sdk.getPosition()<br>      ↓<br>adapter.getLocation()</pre><p>If vendor response types still leak through, the boundary is too thin.</p><h3>Domain models mirror backend DTOs</h3><p>If a backend rename causes changes across ViewModels and components, the transport model has escaped its boundary.</p><h3>The adapter contains business decisions</h3><p>Adapters translate.</p><p>Use cases, ViewModels, and coordinators decide what the application should do.</p><h3>When should you use Adapter?</h3><p>Adapter is useful when your application depends on something whose interface you do not want spreading through your codebase.</p><p>Common React Native examples include:</p><pre>Location SDK<br>Camera SDK<br>Biometric SDK<br>Push notifications<br>Analytics<br>Secure storage<br>Payment SDK<br>HTTP API<br>Native module<br>Third-party authentication</pre><p>You probably do not need an adapter for every small library.</p><p>The pattern becomes valuable when:</p><ul><li>The dependency exposes concepts different from your application’s concepts</li><li>Vendor types would otherwise leak into multiple layers</li><li>You expect the dependency to change</li><li>iOS and Android expose different behavior</li><li>You want production and test implementations behind the same contract</li></ul><h3>Key decisions</h3><ul><li>Define the application contract first.</li><li>Let the adapter depend on the external system, not the rest of the application.</li><li>Keep vendor and transport types at the boundary.</li><li>Translate semantics, not only names.</li><li>Normalize external failures into application-friendly outcomes.</li><li>Keep business workflow outside the adapter.</li></ul><h3>Final principle</h3><p>External systems will change.</p><p>SDKs will be replaced.</p><p>Backend payloads will evolve.</p><p>Native APIs will behave differently across platforms.</p><p>The goal is not to prevent those changes.</p><p>The goal is to prevent those changes from becoming application-wide changes.</p><pre>Vendor API<br>    ↓<br>Adapter<br>    ↓<br>Application Contract</pre><p>That is the Adapter pattern.</p><blockquote><strong><em>External systems speak their own language. Adapters are where that language stops.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f85b9b9cba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 6— Factory and the Composition Root]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-6-factory-and-the-composition-root-f2ceee2cf142?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ceee2cf142</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 10:24:47 GMT</pubDate>
            <atom:updated>2026-09-13T10:24:47.239Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Factory centralizes a meaningful construction decision, it should not conceal every ordinary call to </em><em>new.</em></p><h3>Creation is a dependency</h3><p>FieldFlow uses different inspection repository implementations across production, previews, tests, and offline-capable sessions.</p><p>If screens or feature code decide which implementation to create, they inherit configuration knowledge, lifecycle policy, and vendor details that should remain outside the feature.</p><pre>interface InspectionRepository {<br>  load(id: InspectionId, signal?: AbortSignal): Promise&lt;Inspection&gt;;<br><br>  saveDraft(draft: InspectionDraft): Promise&lt;void&gt;;<br>}</pre><p>A factory centralizes the construction decision:</p><pre>type RepositoryConfig =<br>  | {<br>      kind: &#39;offlineFirst&#39;;<br>      api: InspectionApi;<br>      database: InspectionDatabase;<br>    }<br>  | {<br>      kind: &#39;remoteOnly&#39;;<br>      api: InspectionApi;<br>    }<br>  | {<br>      kind: &#39;memory&#39;;<br>      seed?: readonly Inspection[];<br>    };<br><br>function createInspectionRepository(<br>  config: RepositoryConfig<br>): InspectionRepository {<br>  switch (config.kind) {<br>    case &#39;offlineFirst&#39;:<br>      return new OfflineFirstInspectionRepository(<br>        config.api,<br>        config.database<br>      );<br>    case &#39;remoteOnly&#39;:<br>      return new RemoteInspectionRepository(<br>        config.api<br>      );<br>    case &#39;memory&#39;:<br>      return new InMemoryInspectionRepository(<br>        config.seed<br>      );<br>  }<br>}</pre><p>The factory owns implementation selection.</p><p>Consumers depend only on the repository contract.</p><p>They do not need to know whether the implementation uses HTTP, SQLite, an in-memory store, or a synchronization layer.</p><h3>The Composition Root</h3><p>A factory should normally be invoked from a <strong>Composition Root</strong>.</p><p>The Composition Root is the place where the application assembles concrete implementations and wires them into the object graph.</p><p>It answers questions such as:</p><ul><li>Which repository implementation should be used?</li><li>Which API client should be injected?</li><li>Which database belongs to the current session?</li><li>Which use cases depend on those services?</li><li>Who owns long-lived resources?</li><li>Who is responsible for disposing them?</li></ul><p>For example:</p><pre>type ApplicationServices = {<br>  inspectionRepository: InspectionRepository;<br>  loadInspection: LoadInspection;<br>  saveInspectionDraft: SaveInspectionDraft;<br>};<br><br>function createApplicationServices(<br>  config: AppConfig<br>): ApplicationServices {<br>  const api = createInspectionApi(config.api);<br><br>  const repository =<br>    createInspectionRepository({<br>      kind: config.repositoryKind,<br>      api,<br>      database: config.database,<br>    });<br><br>  const loadInspection = new LoadInspection(repository);<br><br>  const saveInspectionDraft = new SaveInspectionDraft(repository);<br><br>  return {<br>    inspectionRepository: repository,<br>    loadInspection,<br>    saveInspectionDraft,<br>  };<br>}</pre><p>The application can then inject those dependencies into the feature:</p><pre>const services =<br>  createApplicationServices(config);<br><br>const viewModel = new InspectionViewModel({<br>    loadInspection: services.loadInspection,<br>    saveInspectionDraft:<br>      services.saveInspectionDraft,<br>  });<br></pre><p>Construction happens at the boundary.</p><p>Feature code receives ready dependencies.</p><h3>Architecture</h3><p>The important direction is:</p><pre>Configuration<br>      ↓<br>Composition Root<br>      ↓<br>Factory<br>      ↓<br>Concrete dependency<br>      ↓<br>Use Case<br>      ↓<br>ViewModel<br>      ↓<br>View</pre><p>The UI consumes abstractions.</p><p>It does not construct infrastructure.</p><h3>Factory function first</h3><p>In TypeScript, prefer a factory function before introducing a factory class.</p><p>Factory functions can:</p><ul><li>Validate configuration</li><li>Close over dependencies</li><li>Choose concrete implementations</li><li>Enforce construction rules</li><li>Return interfaces instead of classes</li></ul><p>For example:</p><pre>function createInspectionRepository(<br>  config: RepositoryConfig<br>): InspectionRepository {<br>  // meaningful construction policy<br>}</pre><p>A factory class is more appropriate when the factory itself has meaningful state, related behavior, or substitutable construction logic.</p><pre>class InspectionRepositoryFactory {<br>  constructor(<br>    private readonly api: InspectionApi,<br>    private readonly databaseProvider:<br>      DatabaseProvider<br>  ) {}<br><br>  create(session: Session): InspectionRepository {<br>    const database = this.databaseProvider.forAccount(session.accountId);<br><br>    return new OfflineFirstInspectionRepository(<br>      this.api,<br>      database<br>    );<br>  }<br>}</pre><p>Even then, consider whether a closure is simpler:</p><pre>function createInspectionRepositoryFactory(<br>  api: InspectionApi,<br>  databaseProvider: DatabaseProvider<br>) {<br>  return (session: Session): InspectionRepository =&gt; {<br>    const database = databaseProvider.forAccount( session.accountId);<br><br>    return new OfflineFirstInspectionRepository(<br>      api,<br>      database<br>    );<br>  };<br><br>}</pre><p>Use a class only when the class itself provides value.</p><h3>Factory is not a service locator</h3><p>Factories belong near composition boundaries.</p><p>Calling a global factory throughout feature code does not remove coupling.</p><p>It merely replaces constructor coupling with factory coupling.</p><p>Avoid:</p><pre>class InspectionViewModel {<br>  async load(<br>    id: InspectionId<br>  ): Promise&lt;Inspection&gt; {<br>    const repository = RepositoryFactory.create();<br>    return repository.load(id);<br>  }<br>}</pre><p>The dependency is hidden.</p><p>The ViewModel appears self-contained even though it requires a repository.</p><p>Prefer:</p><pre>class InspectionViewModel {<br>  constructor(<br>    private readonly repository:<br>      InspectionRepository<br>  ) {}<br><br>  load(<br>    id: InspectionId<br>  ): Promise&lt;Inspection&gt; {<br>    return this.repository.load(id);<br>  }<br>}</pre><p>Now the requirement is explicit:</p><pre>InspectionViewModel<br>        requires<br>InspectionRepository</pre><p>This improves:</p><ul><li>Testability</li><li>Readability</li><li>Dependency visibility</li><li>Replacement of implementations</li><li>Architectural reasoning</li></ul><p>A Factory creates dependencies.</p><p>A consumer should not repeatedly ask a Factory to locate them.</p><h3>Factory and dependency injection</h3><p>Factory and dependency injection solve related but different problems.</p><p>A Factory answers:</p><blockquote><em>Which concrete implementation should be created, and how?</em></blockquote><p>Dependency injection answers:</p><blockquote><em>How does a consumer receive the dependency it needs?</em></blockquote><p>Example:</p><pre>const repository = createInspectionRepository(config);</pre><p>That is construction.</p><p>Then:</p><pre>const useCase = new LoadInspection(repository);</pre><p>That is dependency injection.</p><p>Both usually meet at the Composition Root.</p><pre>Configuration<br>      │<br>      ▼<br>   Factory<br>      │<br>      ▼<br>Concrete Dependency<br>      │<br>      │ inject<br>      ▼<br>   Use Case<br>      │<br>      ▼<br>  ViewModel<br>      │<br>      ▼<br>     View</pre><h3>Construction and lifecycle</h3><p>Factories often create more than ordinary objects.</p><p>In React Native they may create resources such as:</p><ul><li>SQLite databases</li><li>Sync queues</li><li>Native event subscriptions</li><li>WebSockets</li><li>Timers</li><li>Background workers</li><li>Network observers</li><li>AppState listeners</li><li>Native module sessions</li></ul><p>When a Factory creates a resource, ownership must be clear.</p><p>If a Factory opens a database, who closes it?</p><p>If it starts a synchronization queue, who stops it?</p><p>If it creates a native subscription, who removes it?</p><p>A scoped aggregate can make that ownership explicit.</p><pre>type SessionServices = {<br>  repository: InspectionRepository;<br>  queue: SyncQueue;<br>  dispose(): Promise&lt;void&gt;;<br>};</pre><p>Then:</p><pre>type SessionServiceDependencies = {<br>  api: InspectionApi;<br>  openDatabase(accountId: AccountId): InspectionDatabase;<br>};<br>  <br>function createSessionServices(<br>  session: Session,<br>  dependencies: SessionServiceDependencies<br>): SessionServices {<br>  const database = dependencies.openDatabase(session.accountId);<br><br>  const repository = createInspectionRepository({<br>    kind: &#39;offlineFirst&#39;,<br>    api: dependencies.api,<br>    database,<br>  });<br><br>  const queue = createSyncQueue(database, repository);<br><br>  return {<br>    repository,<br>    queue,<br>    async dispose() {<br>      queue.stop();<br>      await database.close();<br>    },<br>  };<br>}</pre><p>The aggregate communicates scope:</p><pre>Session starts<br>      ↓<br>createSessionServices()<br>      ↓<br>Database opened<br>Repository created<br>Sync queue started<br>      ↓<br>Session executes<br>      ↓<br>dispose()<br>      ↓<br>Queue stopped<br>Database closed</pre><p>The creator establishes ownership.</p><p>Ownership does not mean consumers must know every cleanup detail.</p><p>They only need the lifecycle contract.</p><h3>Disposal should be explicit</h3><p>A resource-owning Factory should not rely on hidden cleanup.</p><p>Avoid creating infrastructure with no corresponding disposal policy.</p><p>For example:</p><pre>const services = createSessionServices(session, dependencies);<br><br>try {<br>  await runSession(services);<br>} finally {<br>  await services.dispose();<br>}</pre><p>This makes lifecycle boundaries observable and testable.</p><p>For more complex infrastructure, cleanup may need to tolerate partial failures.</p><h4>The architectural rule remains the same:</h4><blockquote><em>Every resource with a meaningful lifecycle should have an explicit owner.</em></blockquote><h3>Async initialization</h3><p>A Factory should not return an object that appears ready when initialization is still happening.</p><p>Avoid:</p><pre>function createRepository(): InspectionRepository {<br>  const repository = new OfflineFirstInspectionRepository();<br>  repository.initialize();<br>  return repository;<br>}</pre><p>The consumer can now call:</p><pre>await repository.load(id);</pre><p>without knowing whether initialization completed.</p><p>That creates temporal coupling.</p><p>Prefer making readiness explicit:</p><pre>async function createInspectionRepository(<br>  config: OfflineRepositoryConfig<br>): Promise&lt;InspectionRepository&gt; {<br><br>  const repository =<br>    new OfflineFirstInspectionRepository(<br>      config.api,<br>      config.database<br>    );<br><br>  await repository.initialize();<br>  return repository;<br>}</pre><p>Construction now means the returned object is actually usable.</p><p>If readiness must remain separate, model it explicitly rather than hiding it.</p><pre>type RepositoryHandle = {<br>  repository: InspectionRepository;<br>  ready: Promise&lt;void&gt;;<br>};</pre><p>The key rule is:</p><blockquote><em>A Factory should not return a partially initialized object while pretending construction is complete.</em></blockquote><h3>Compile-time configuration first</h3><p>When configuration is known inside the application, model valid states with TypeScript.</p><p>Prefer:</p><pre>type RepositoryConfig =<br>  | OfflineFirstConfig<br>  | RemoteOnlyConfig<br>  | MemoryConfig;</pre><p>over:</p><pre>type RepositoryConfig = {<br>  kind: string;<br>  api?: InspectionApi;<br>  database?: InspectionDatabase;<br>  seed?: Inspection[];<br>};</pre><p>The first model makes invalid combinations harder to represent.</p><p>For example:</p><pre>createInspectionRepository({<br>  kind: &#39;remoteOnly&#39;,<br>  database,<br>});</pre><p>should fail during development instead of failing later at runtime.</p><p>Factories are a good place to centralize construction policy, but TypeScript should enforce as much of that policy as possible before the application runs.</p><p>Not every configuration originates from TypeScript.</p><p>Some values may come from:</p><ul><li>Environment variables</li><li>Remote configuration</li><li>Native configuration</li><li>Persisted JSON</li><li>Server responses</li><li>Feature flags</li></ul><p>Those values should be validated before construction.</p><p>For example:</p><pre>type FactoryResult&lt;T&gt; =<br>  | {<br>      ok: true;<br>      value: T;<br>    }<br>  | {<br>      ok: false;<br>      error: ConfigurationError;<br>    };</pre><p>Then:</p><pre>function createInspectionRepositoryFromInput(<br>  input: unknown<br>): FactoryResult&lt;InspectionRepository&gt; {<br>  const parsed = parseRepositoryConfig(input);<br><br>  if (!parsed.ok) {<br>    return parsed;<br>  }<br><br>  return {<br>    ok: true,<br>    value:<br>      createInspectionRepository(<br>        parsed.value<br>      ),<br>  };<br>}</pre><p>Use the type system for application-owned configuration.</p><p>Use runtime validation for external configuration.</p><h3>Factory versus Builder</h3><p>Factory and Builder both participate in object creation, but they solve different construction problems.</p><p>A Factory typically performs one meaningful creation operation:</p><pre>const repository = createInspectionRepository(config);</pre><p>Conceptually:</p><pre>configuration<br>      ↓<br>   factory<br>      ↓<br>   product</pre><p>A Builder accumulates construction inputs before producing the final object.</p><pre>const request =<br>  new InspectionRequestBuilder()<br>    .forInspection(inspectionId)<br>    .withAttachments(files)<br>    .withLocation(location)<br>    .withMetadata(metadata)<br>    .build();</pre><p>Conceptually:</p><pre>builder<br>  ↓<br>configure<br>  ↓<br>configure<br>  ↓<br>configure<br>  ↓<br>build<br>  ↓<br>product</pre><p>The distinction is not that Builders create complex objects and Factories create simple ones.</p><p>The distinction is the construction interaction.</p><p><strong>Factory</strong></p><ul><li>Chooses or creates a usable product</li><li>Usually in one operation</li><li>Often centralizes selection or lifecycle policy</li></ul><p><strong>Builder</strong></p><ul><li>Collects construction inputs</li><li>Supports staged configuration</li><li>Finalizes only when enough information has been provided</li></ul><p>A Factory may create a Builder.</p><p>Their responsibilities should still remain separate.</p><h3>Keep business decisions out of factories</h3><p>Factories make construction decisions.</p><p>They should not gradually become application workflow engines.</p><p>Construction policy:</p><pre>offlineFirst<br>remoteOnly<br>memory<br>production<br>preview<br>test</pre><p>Business policy:</p><pre>inspection approved<br>amount exceeds threshold<br>user requires OTP<br>draft is recoverable<br>submission requires identity verification</pre><p>Avoid:</p><pre>function createInspectionRepository(<br>  inspection: Inspection<br>): InspectionRepository {<br>  if (<br>    inspection.status === &#39;submitted&#39;<br>  ) {<br>    return remoteRepository;<br>  }<br><br>  if (<br>    inspection.hasPendingChanges<br>  ) {<br>    return offlineRepository;<br>  }<br>  return memoryRepository;<br>}</pre><p>That decision is driven by domain state rather than construction configuration.</p><p>It belongs in application or domain logic.</p><p>Factories construct dependencies.</p><p>They should not execute workflows.</p><h3>Application scope and session scope</h3><p>Different dependencies often belong to different lifetimes.</p><p>For example:</p><pre>Application Scope<br>      │<br>      ├── API Client<br>      ├── Authentication<br>      ├── Analytics<br>      └── Logging<br>              │<br>              ▼<br>        Session Scope<br>              │<br>              ├── Account Database<br>              ├── Inspection Repository<br>              ├── Sync Queue<br>              └── dispose()</pre><p>This distinction becomes especially useful in React Native applications where users may:</p><ul><li>Sign in</li><li>Switch accounts</li><li>Enter an offline session</li><li>Leave a workflow</li><li>Reconnect</li><li>Sign out</li></ul><p>A Factory can help encode those scopes explicitly.</p><h3>Key decisions</h3><ul><li>Use Factories for meaningful selection, configuration, or lifecycle policy.</li><li>Prefer a factory function before introducing a factory class.</li><li>Invoke Factories at Composition Roots rather than throughout feature code.</li><li>Keep dependencies explicit through constructor or parameter injection.</li><li>Use TypeScript to prevent invalid construction states when possible.</li><li>Validate external configuration before constructing dependencies.</li><li>Do not hide asynchronous initialization behind apparently ready objects.</li><li>Make resource ownership and disposal explicit.</li><li>Keep business workflows outside Factories.</li><li>Do not use a Factory as a Service Locator.</li><li>Treat construction itself as an architectural dependency.</li><li>Let the Composition Root know concrete implementations so the rest of the application does not.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ceee2cf142" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 5 — Builder for Valid Complex Inputs]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-5-builder-for-valid-complex-inputs-4ccbae96ac52?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ccbae96ac52</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 12:22:52 GMT</pubDate>
            <atom:updated>2026-09-06T12:22:52.099Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Builder earns its place when construction is progressive, validity matters, and the finished value should not expose partially constructed state.</em></p><h4>A multi-step inspection</h4><p>FieldFlow creates an inspection submission across several screens. The technician answers questions, adds photos, records a location, signs, and reviews the result. A constructor requiring every input upfront does not match that interaction.</p><p>Builder separates incremental construction from creation of the final product:</p><ol><li><strong>Director:</strong> the workflow or UI that supplies inputs.</li><li><strong>Builder:</strong> accumulates construction state and controls how a product is finalized.</li><li><strong>Product:</strong> the valid submission, command, or immutable snapshot.</li></ol><p>A draft may be incomplete by design. The important boundary is that incomplete draft state must not accidentally become a valid domain command.</p><h4>Prefer immutable draft data first</h4><p>React works naturally with immutable form state:</p><pre>type SubmissionDraft = {<br>  inspectionId: InspectionId;<br>  answers: Readonly&lt;Partial&lt;Record&lt;QuestionId, AnswerValue&gt;&gt;&gt;;<br>  photoIds: readonly PhotoId[];<br>  signatureId?: SignatureId;<br>  location?: GeoPoint;<br>};<br><br>function answerQuestion(<br>  draft: SubmissionDraft,<br>  questionId: QuestionId,<br>  value: AnswerValue,<br>): SubmissionDraft {<br>  return {<br>    ...draft,<br>    answers: {<br>      ...draft.answers,<br>      [questionId]: value,<br>    },<br>  };<br>}</pre><p>A pure buildSubmission(draft) function can validate the current draft and return either a valid product or construction issues:</p><pre>type BuildResult =<br>  | { ok: true; command: SubmitInspectionCommand }<br>  | { ok: false; issues: readonly BuildIssue[] };</pre><p>For many applications, this is enough.</p><p>The draft acts as the evolving construction input while the finalizer performs the Builder pattern’s essential responsibility: it prevents incomplete or invalid construction state from becoming the finished product.</p><p>No mutable builder class is required.</p><h4>A class-based builder</h4><p>Use a builder object when construction happens outside React, chained calls improve the consuming API, or construction state and invariants benefit from encapsulation.</p><pre>class InspectionSubmissionBuilder {<br>  #answers = new Map&lt;QuestionId, AnswerValue&gt;();<br>  #photos: PhotoId[] = [];<br>  #signature?: SignatureId;<br>  #location?: GeoPoint;<br><br>  constructor(<br>    private readonly inspectionId: InspectionId,<br>  ) {}<br><br>  answer(id: QuestionId, value: AnswerValue): this {<br>    this.#answers.set(id, value);<br>    return this;<br>  }<br><br>  addPhoto(id: PhotoId): this {<br>    this.#photos.push(id);<br>    return this;<br>  }<br><br>  sign(id: SignatureId): this {<br>    this.#signature = id;<br>    return this;<br>  }<br><br>  locate(point: GeoPoint): this {<br>    this.#location = point;<br>    return this;<br>  }<br><br>  build(<br>    policy: SubmissionPolicy,<br>    clock: Clock,<br>  ): BuildResult {<br>    const draft = this.snapshot();<br>    const issues = policy(draft);<br>    return issues.length &gt; 0<br>      ? { ok: false, issues }<br>      : {<br>          ok: true,<br>          command: createSubmissionCommand(<br>            draft,<br>            clock.now(),<br>          ),<br>        };<br>  }<br><br>  private snapshot(): SubmissionDraft {<br>    return {<br>      inspectionId: this.inspectionId,<br>      answers: Object.fromEntries(this.#answers),<br>      photoIds: [...this.#photos],<br>      signatureId: this.#signature,<br>      location: this.#location,<br>    };<br>  }<br><br>}</pre><p>The product receives copied construction data so later mutation of the builder cannot change a command that has already been built.</p><p>This distinction matters: the builder may remain mutable while it is being used, but the completed product should not retain references to mutable builder internals.</p><h4>Builder and React forms</h4><p>Do not store a mutable builder in component state and mutate it in place. React observes state primarily through reference changes, so mutating the same builder instance can leave rendering and derived state out of sync.</p><p>Use immutable draft state or a reducer for interactive editing:</p><pre>function submissionReducer(<br>  state: SubmissionDraft,<br>  action: DraftAction,<br>): SubmissionDraft {<br>  switch (action.type) {<br>    case &#39;answered&#39;:<br>      return answerQuestion(<br>        state,<br>        action.questionId,<br>        action.value,<br>      );<br>    case &#39;photoAdded&#39;:<br>      return {<br>        ...state,<br>        photoIds: [<br>          ...state.photoIds,<br>          action.photoId,<br>        ],<br>      };<br>    case &#39;signed&#39;:<br>      return {<br>        ...state,<br>        signatureId: action.signatureId,<br>      };<br>    case &#39;locationRecorded&#39;:<br>      return {<br>        ...state,<br>        location: action.location,<br>      };<br>    default:<br>      return assertNever(action);<br>  }<br>}</pre><p>If a class-based builder still provides value, create or hydrate it at an application boundary when the user finalizes the workflow rather than using it as the interactive React state container.</p><p>Builder and Memento also cooperate naturally.</p><p>The draft may be persisted while construction is in progress, then migrated and restored later. The durable memento should remain an explicit versioned schema rather than serialized builder internals.</p><h4>Step builders and type-state</h4><p>For developer-facing APIs, generics can prevent build() from being available before required construction steps have occurred.</p><p>For example, a static API might require:</p><pre>builder<br>  .withAccount(account)<br>  .withAmount(amount)<br>  .confirm()<br>  .build();</pre><p>Type-state can encode those required transitions so invalid construction sequences fail at compile time.</p><p>That technique can be powerful, but it also introduces substantial generic complexity.</p><p>It is less useful when requirements come from a server-provided form. If today’s inspection requires a signature but tomorrow’s configuration does not, TypeScript cannot know that requirement statically.</p><p>Use runtime validation for dynamic mobile workflows.</p><p>Choose type-state when:</p><ul><li>Required construction steps are statically known</li><li>Consumers are other developers</li><li>Invalid call sequences are costly and the additional generic complexity produces meaningful safety.</li></ul><h4>Builder versus nearby patterns</h4><ul><li><strong>Factory</strong> selects or creates a product, usually in one operation.</li><li><strong>Builder</strong> accumulates inputs before producing a finished product.</li><li><strong>Memento</strong> captures state so work can be restored later.</li><li><strong>Prototype</strong> starts construction by copying an existing value.</li><li><strong>Reducer</strong> evolves interactive state through explicit events.</li></ul><p>These patterns can cooperate without taking ownership of the same responsibility.</p><p>For example:</p><pre>Reducer<br>   ↓<br>SubmissionDraft<br>   ↓<br>Memento ─────→ persistence / restoration<br>   ↓<br>Builder or finalizer<br>   ↓<br>SubmitInspectionCommand<br>   ↓<br>Factory / application service</pre><p>The reducer owns interactive state transitions.</p><p>The memento owns restoration.</p><p>The builder owns construction of a valid final value.</p><h4>Key decisions</h4><ul><li>Begin with immutable draft data and a pure finalizer.</li><li>Allow drafts to be incomplete, require finished products to be valid.</li><li>Use a builder class when encapsulated construction state or API ergonomics justify it.</li><li>Keep dynamic validation at runtime and centralize policy instead of duplicating rules across screens.</li><li>Copy mutable collections before exposing the finished product.</li><li>Persist explicit draft mementos rather than builder implementation details.</li><li>Do not introduce a Builder merely because construction has several fields, use it when progressive construction has meaningful rules or invariants.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ccbae96ac52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend SWE — Part 4 — Observer in a Rendering System]]></title>
            <link>https://mobileledge.medium.com/frontend-swe-part-4-observer-in-a-rendering-system-b90ab401affd?source=rss-d7def8c13c85------2</link>
            <guid isPermaLink="false">https://medium.com/p/b90ab401affd</guid>
            <dc:creator><![CDATA[Steve]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 09:38:14 GMT</pubDate>
            <atom:updated>2026-09-05T09:38:14.884Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In React Native, observable data used for rendering needs two things: a way to notify React about changes and a reliable way to read the latest value.</em></p><h3>Events are not always state</h3><p>FieldFlow listens to network connectivity, application visibility, synchronization progress, and notification interactions.</p><p>At first, these all look similar:</p><blockquote><em>Something publishes an update, and subscribers react.</em></blockquote><p>But they represent different kinds of information.</p><ol><li><strong>Connectivity is state.</strong><br>A new subscriber should immediately know the latest network status.</li><li><strong>“Notification opened” is an event.</strong><br>It happens once. Replaying it accidentally may trigger navigation twice.</li><li><strong>Sync progress is state.</strong><br>It changes frequently and usually has one clear owner.</li><li><strong>Analytics is an output destination.</strong><br>It receives information, but the UI does not observe it as application state.</li></ol><p>The Observer pattern describes one source notifying many subscribers.</p><p>The important design decision comes before implementing Observer:</p><p><strong>Are we publishing current state, or are we publishing an event that happened once?</strong></p><p>That decision affects how the data should be stored, replayed, and consumed.</p><h3>A React-compatible external store</h3><p>For state that React needs to render, the source should expose both the current value and a subscription mechanism.</p><pre>interface ExternalStore&lt;T&gt; {<br>  getSnapshot(): T;<br>  subscribe(onChange: () =&gt; void): () =&gt; void;<br>}<br><br>function useNetworkStatus(store: ExternalStore&lt;NetworkStatus&gt;) {<br>  return useSyncExternalStore(<br>    callback =&gt; store.subscribe(callback),<br>    () =&gt; store.getSnapshot(),<br>  );<br>}</pre><p>getSnapshot() allows React to read the latest state.</p><p>subscribe() tells React that the state may have changed.</p><p>The function returned by subscribe() handles cleanup when the subscriber is removed.</p><p>This creates a clear contract between the external system and React.</p><h3>Architecture diagram — Mermaid specification</h3><pre>flowchart LR<br>Native[&quot;&lt;&lt;native&gt;&gt; Connectivity source&quot;] --&gt; Adapter[&quot;Connectivity store&quot;]<br>Adapter --&gt;|getSnapshot| Hook[&quot;&lt;&lt;hook&gt;&gt; useNetworkStatus&quot;]<br>Adapter --&gt;|subscribe / unsubscribe| Hook<br>Hook --&gt; Screen[&quot;&lt;&lt;component&gt;&gt; SyncBadge&quot;]</pre><p>The responsibilities stay separated:</p><ul><li>The native adapter converts vendor-specific data into application data.</li><li>The store owns the latest network state.</li><li>The Hook connects the store to React.</li><li>React owns rendering.</li></ul><p>This keeps native APIs and vendor-specific details outside UI components.</p><h3>Snapshot stability</h3><p>getSnapshot() should return the same value while the underlying state has not changed.</p><p>A common mistake is returning a new object on every call:</p><pre>getSnapshot() {<br>  return {<br>    kind: this.currentStatus,<br>  };<br>}</pre><p>Even when currentStatus is unchanged, this creates a new object reference.</p><p>React may interpret that as a changed snapshot and perform unnecessary work.</p><p>Instead, cache the snapshot and replace it only when the real state changes.</p><pre>class ConnectivityStore implements ExternalStore&lt;NetworkStatus&gt; {<br>  #snapshot: NetworkStatus = { kind: &#39;unknown&#39; };<br><br>  #listeners = new Set&lt;() =&gt; void&gt;();<br><br>  getSnapshot = () =&gt; this.#snapshot;<br><br>  subscribe = (listener: () =&gt; void) =&gt; {<br>    this.#listeners.add(listener);<br>    return () =&gt; this.#listeners.delete(listener);<br>  };<br><br>  update(next: NetworkStatus) {<br>    if (sameNetworkStatus(this.#snapshot, next)) return;<br>    this.#snapshot = next;<br>    for (const listener of this.#listeners) {<br>      listener();<br>    }<br>  }<br><br>}</pre><p>The important rule is simple:</p><p><strong>If the state has not changed, the snapshot should not change either.</strong></p><h3>Model one-time events explicitly</h3><p>Not every observable value should behave like state.</p><p>For example, opening a push notification is usually a one-time event.</p><p>A simple typed event source may look like this:</p><pre>interface EventSource&lt;TEvent&gt; {<br>  subscribe(<br>    listener: (event: TEvent) =&gt; void,<br>  ): () =&gt; void;<br>}</pre><p>Unlike state, an event does not necessarily have a “current value.”</p><p>The subscriber or event system must define several behaviors:</p><ul><li>Should duplicate events be ignored?</li><li>Does event order matter?</li><li>How long should an event remain available?</li><li>What happens if the application is restarted before the event is handled?</li></ul><p>If losing an event would lose important business work, do not depend only on an in-memory event stream.</p><p>Persist the important action as a command, queue item, or inbox record.</p><p>For example:</p><pre>Push notification opened<br>        |<br>        v<br>Create durable application command<br>        |<br>        v<br>Process navigation or business action</pre><p>This makes the behavior recoverable even if the application restarts.</p><h3>Do not use render state to simulate events</h3><p>Another common mistake is placing navigation events inside shared UI state only to trigger an effect.</p><p>For example:</p><pre>{<br>  redirectTo: &#39;InspectionDetail&#39;<br>}</pre><p>A component may observe this value and navigate when it appears.</p><p>The problem is that state can survive longer than the behavior it was intended to trigger.</p><p>After a remount, state restoration, or another subscription, the same value may cause navigation again.</p><p>State should describe <strong>what is true now</strong>.</p><p>Events should describe <strong>what happened</strong>.</p><p>Keeping those concepts separate prevents many lifecycle bugs.</p><h3>Subscription scope</h3><p>Observe data at the smallest level that actually needs it.</p><p>For example:</p><ol><li>A sync badge may observe only the sync summary.</li><li>The sync engine, rather than every screen, should observe connectivity to resume background work.</li><li>An application-level coordinator may observe notification entry points.</li><li>A feature should observe only the record it needs instead of the entire database.</li></ol><p>Broad subscriptions often create:</p><ul><li>Unnecessary re-renders</li><li>Harder dependency tracking</li><li>Hidden coupling between features</li><li>More difficult performance debugging</li></ul><p>A useful rule is:</p><p><strong>Subscribe as close as possible to the owner of the behavior.</strong></p><h3>Listener failures and updates during notification</h3><p>A reusable event source also needs to define what happens when listeners behave unexpectedly.</p><p>For example:</p><pre>for (const listener of listeners) {<br>  listener(event);<br>}</pre><p>What happens if one listener throws an error?</p><p>Should the remaining listeners still receive the event?</p><p>Another case is when a listener adds or removes another listener while notification is already running.</p><p>To make behavior more predictable, the source can iterate over a copy of the listener collection:</p><pre>for (const listener of [...listeners]) {<br>  listener(event);<br>}</pre><p>This prevents changes to the listener set from unexpectedly affecting the current notification cycle.</p><p>Error handling can also be isolated:</p><pre>for (const listener of [...listeners]) {<br>  try {<br>    listener(event);<br>  } catch (error) {<br>    reportListenerError(error);<br>  }<br>}</pre><p>These rules should live inside the reusable event system instead of being reimplemented by every publisher.</p><p>Observer is useful when one source needs to notify multiple independent consumers.</p><p>But it should not automatically become the solution for every communication problem.</p><p>Depending on the situation, another approach may be clearer:</p><ul><li>Direct function calls for simple one-to-one communication,</li><li>React props for parent-to-child data,</li><li>Context for shared React-owned state,</li><li>An external store for renderable application state,</li><li>An event source for one-time events,</li><li>A command or queue for important work that must survive application restarts.</li></ul><p>The pattern should follow the behavior of the data, not the other way around.</p><h3>Key decisions</h3><ol><li>Decide whether the information represents <strong>current state</strong> or <strong>an event that happened once</strong>.</li><li>Give renderable state a <strong>stable snapshot</strong> and a clear subscription API.</li><li>Make unsubscribe and cleanup part of the public contract.</li><li>Subscribe only at the smallest scope that needs the information.</li><li>Keep one-time events out of shared render state.</li><li>Persist important actions when losing an in-memory event would be unacceptable.</li><li>Define how the event source handles listener errors and listener changes during notification.</li></ol><p>Observer is easy to implement mechanically.</p><p>The harder engineering problem is deciding <strong>what should be observed, who should own it, and whether the information represents state or an event.</strong></p><p>Getting those decisions right keeps rendering predictable and prevents the Observer pattern from turning into hidden application-wide coupling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b90ab401affd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>