<?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 Brian Arnold on Medium]]></title>
        <description><![CDATA[Stories by Brian Arnold on Medium]]></description>
        <link>https://medium.com/@mrlegowatch?source=rss-c9ad72f0a207------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4N3A8WpGXMUY0GlD.jpg</url>
            <title>Stories by Brian Arnold on Medium</title>
            <link>https://medium.com/@mrlegowatch?source=rss-c9ad72f0a207------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:06:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrlegowatch/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[Side-quests ate my summer, part 1: Third time’s the charm (almost)]]></title>
            <link>https://medium.com/@mrlegowatch/side-quests-ate-my-summer-part-1-third-times-the-charm-almost-924d3598a94d?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/924d3598a94d</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ai-assisted-coding]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dungeons-and-dragons]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Fri, 16 Oct 2026 19:46:37 GMT</pubDate>
            <atom:updated>2026-10-16T19:46:37.217Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>The first in a short series on what derailed my summer quest to finish writing the first draft of my debugging book.</em></strong></p><h3><strong>The loop</strong></h3><p>This article is about <a href="https://github.com/mrlegowatch/DungeonCore">DungeonCore</a>, my latest Swift Package on GitHub. Which needs some explaining.</p><p>Right after I retired in May, I took some time to polish several GitHub repositories and remembered an unpublished repo: DungeonCore, my third attempt in over ten years at a dungeon map builder app for iPads and Macs. It had basic map rendering; I&#39;d hit a breakthrough last year (which we’ll get to), and I wanted to take it to the next level with editing support. But I had other things to do, so I set it aside, again.</p><p>By midsummer, I needed a break before making further edits to my book—a diversion of some sort—and I had an upcoming trip to visit childhood friends. I figured we might reminisce about playing D&amp;D in the early 1980s, so I dug up several old adventures I had written and run. One of them stood out as fairly complete with a typescript, maps, and tons of handwritten notes.</p><p>On a re-read, I got way too excited. I embarked on an all-encompassing side quest to remake the adventure with current rules. Along the way, the maps themselves became another obsession. When I finally stopped for air two months later, I realized I should be writing about why I haven’t been working on my debugging book; then I realized I should be writing about why I’m struggling with my 1983 adventure maps; and then I realized I needed to be coding again to fix them. With DungeonCore. Which I did. And now I need to write about that.</p><p>We’re going to unpack these in reverse order:</p><ul><li>This article is about my return to coding, and the new repo.</li><li>In the next article, I’ll do a deeper dive on that RPG adventure.</li><li>In the article after that, we’ll take stock of where I am with the debugging book.</li></ul><p>It’s all connected. Trust me on this.</p><h3>Kryptonite, and a very old map</h3><p>My kryptonite is data structures and algorithms. I was never formally trained in Computer Science (I finished MechE with a side salad of numerical computation); my strengths have always been in realizing great user experiences and understanding how people interact with computers. Let’s see how these shaped the history and evolution of my GitHub repos.</p><p>Way back in 2015, I started a project on a lark, building nascent support for a role-playing game, starting from a map with rooms and hallways. With some time off around Thanksgiving 2016, I haphazardly added dice rolling and character logic. It quickly became a mishmash of ideas, quintessential <a href="https://medium.com/@mrlegowatch/so-i-made-a-dice-class-1-of-3-9b9bb5c1dc2?sharedUserId=mrlegowatch">Sandbox-Driven Development</a> (SDD)—I had no idea where it was going. The map component stalled first. Fast forward a year, and I separated out the core role-playing logic into <a href="https://github.com/mrlegowatch/RolePlayingCore">RolePlayingCore</a>, refined it, made it public, and wrote several Medium articles about that and SDD. In 2018, I tried to overhaul the map-building component I&#39;d left out, but I abandoned it again because I kept struggling with the data structure for rooms and hallways and the rendering logic.</p><p>So why return to it now? First, I’d dusted off the repo last year, worked through the algorithmic challenges with Claude, and hit a breakthrough before I stopped. And second—well, hold on. Let’s talk about…</p><h3>The breakthrough</h3><p>From the start, I wanted a way to specify a hallway as a path of segments (maybe starting from finger movement on an iPad) that snaps to the grid while automatically handling direction changes and diagonal turns. I obsessively drew hallways on graph paper, derived the points for the opposite edges, and often got the math wrong when I tried to compute them. Funnily enough, the first time I described what I was trying to do in a Claude prompt, it confidently came up with something completely wrong as well. That was when I decided to feed it test data, the “answers,” approximately, and the gotchas I found. With that in hand, and after a bit of iteration, Claude finally came up with an algorithm that mostly worked. Now, DungeonCore supports hallways specified as left-side segments, in addition to edges that specify the entire polygon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRhixRcC_vP_WLf-x_Zlkw.png" /></figure><p>That energized me to return to the library at some point. The “some point” came when, while updating my old adventure, I experimented with web-based map builders. I cringed at how 1990s the UIs were, and I also struggled to make things look as simple as my old 1983 maps. It left me confused and annoyed. One thing almost four decades of working on UI code taught me was “what isn’t good UI,” and these mapping tools were swimming in that end of the pool. And I realized I had an opportunity to just enhance my own tool to support my adventure maps.</p><h3>Dice and rules, made solid</h3><p>So, in my article about SDD, I talked a lot about the Dice component of the RolePlayingCore Swift Package. The dice parser, in particular, illustrates my journey overcoming my kryptonite, starting from something very ad hoc and eventually leveling it up and making <a href="https://github.com/mrlegowatch/SwiftDice">SwiftDice</a> a standalone Swift Package.</p><p>The first version of the parser literally peeked at one character at a time, and it hit my limit at simple expressions. The next step was either regular expressions or a real parser. RegEx concisely creates new problems for anyone who didn’t write it, future me included, so I went looking for what “looks right” and found a simple string tokenizer, albeit in another language. So I did what I do: converted it to Swift, bent it to dice notation, and had something working in a couple of days. Then I made it idiomatic, throwing errors instead of juggling optionals, and went back to the Internet for the notations I didn’t know.</p><p>But I didn’t really have the luxury of time to keep exploring things. I had a retirement to plan, a debugging book to write, and Guilder to frame for it. I was <em>swamped</em>. So. The last couple of things I threw at this new library, in the spring of this year, involved Claude. First, I wanted to leave a small gift for future me, when I return to it. I created prompts that capture my coding philosophy: smaller functions, classes, and files; better abstractions; and refactoring to maximize maintainability. The second thing I wanted to do was leave SwiftDice in a very good place feature-wise. So I created prompts to search the web for dice notations that weren’t yet supported, and developed strategies to prioritize and implement each. I stopped when I reached what I considered a reasonable first public iteration (a 0.1.0, if you will) of the package. The coolest thing I stumbled upon, with Claude&#39;s help, was Swift&#39;s expressiveness with inline math for building dice structures. Here are examples of that and the parser:</p><pre>let abilityRoll = (4 * .d6).keeping(3, .highest) // 4d6, keep the highest 3<br>let damage = try DiceParser().parse(&quot;2d8+4&quot;)</pre><p>RolePlayingCore itself also underwent major surgery and took on more capabilities. CodableWithConfiguration lets you wire references between data files to live objects at load time, such as classes, species, backgrounds, feats, equipment, etc., which I cover in the <a href="https://medium.com/@mrlegowatch/can-you-believe-i-still-think-codable-is-frickin-awesome-1e46fc2f0bb7">second half of this article</a>. I also audited the example data against the SRD because, early on, I was testing with example data (I’ll freely admit) from published rulebooks. I fed Claude SRD version 5.2.1 and created prompts that pruned anything in the package that might violate it, while also adding more example data based on its content.</p><h3>October 5: two days versus a couple of hours</h3><p>OK. At the end of August I reunited with childhood friends, and none of us could remember the specifics of any of my adventures, only the vibes: “I remember they were a lot of fun.” So much for that, but we had a great time catching up. When I got home, I went back to updating the Swamp King adventure in earnest and mapped out a Grand Plan for possibly publishing it. <em>(That’s Part 2.)</em> What matters here is that I lost two days trying to draw its Level One map in various web map builders, only to learn that was only half the puzzle. The other half is getting their output into a virtual tabletop (VTT), and that’s a completely separate thing. Jeebus.</p><p>Then I got an idea: I fed Claude my hand-drawn map and a transcription of my 1983 manuscript, and crafted a prompt. After a couple of hours of analysis and refinement, the example DungeonMapBuilder app displayed the entire Level One map from generated JSON. Boom. It wasn’t a well-drawn map or a full VTT, but it had the right shape and direction: selectable rooms, read-aloud text, door status, creatures with stat lines, and more. A basically functioning map.</p><p>The next day was about everything the 1983 key described that the format couldn’t express yet: doors that keys unlock, read-aloud text kept separate from the GM’s notes, sections of a level, room features like the chest in room 8 (and pools and pits that take up part of a room), stat lines for encounters, occupancy, and where to put each room’s label. Along the way, SwiftDice picked up a type-erased AnyRollable for anything that gets rolled, and RolePlayingCore a MoneyRoll for rolled coins. By the end of the second day the level had 42 rooms, 19 hallways and 73 doors, 16 of them locked and 14 secret, across ten commits.</p><p>Here is the abridged JSON for Room 8, to give you a taste:</p><pre>// Room 8, abridged; full file in the repo<br>{<br>  &quot;keyNumber&quot;: &quot;8&quot;,<br>  &quot;name&quot;: &quot;Chieftain&#39;s Room&quot;,<br>  &quot;readAloud&quot;: &quot;There are heaps of cloth and trash, and bits of battered furniture in this place.&quot;,<br>  &quot;encounters&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Bracken-folk chief&quot;,<br>      &quot;count&quot;: 1,<br>      &quot;stats&quot;: { &quot;text&quot;: &quot;AC5, HD2, hp8, #AT1, D2-8 battle axe&quot;, &quot;damage&quot;: [&quot;2d4&quot;], … },<br>      &quot;carried&quot;: { &quot;items&quot;: [<br>        { &quot;name&quot;: &quot;Bronze key&quot;, &quot;quantity&quot;: 2, &quot;value&quot;: &quot;5 gp&quot;,<br>          &quot;keyID&quot;: &quot;portcullis-bronze-key&quot; }, …<br>      ] }<br>    },<br>    {<br>      &quot;name&quot;: &quot;Bracken-folk tramp&quot;,<br>      &quot;count&quot;: 4,<br>      &quot;carriedEach&quot;: { &quot;coins&quot;: { &quot;gp&quot;: &quot;d6&quot; } }<br>    }<br>  ]<br>}<br><br>// …and one of the two doors that key opens<br>{ &quot;kind&quot;: &quot;portcullis&quot;, &quot;name&quot;: &quot;Feeding hatch, 9A&quot;,<br>  &quot;attributes&quot;: [&quot;isLocked&quot;], &quot;keyID&quot;: &quot;portcullis-bronze-key&quot; }</pre><p>This one room uses all three Swift packages. The &quot;d6&quot; gold is a SwiftDice expression, decoded straight from the file and rolled when you need it. The coins and their currencies come from RolePlayingCore. The keyID on the bronze keys is DungeonCore’s, and it’s what links them to the two feeding hatches in room 9. Nobody wrote “opens two doors” anywhere; the app just works it out.</p><p>Here are the hand-drawn and JSON-produced maps, side-by-side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0CY1YLBjWvfKZAVOZJ2nA.jpeg" /></figure><p>Here is the right-side panel when Room 8 is selected:</p><figure><img alt="Screen shot of room 8 indicating a read-aloud, DM notes, an encounters section with creatures, keys, and other items on their person, a treasure section, and tags." src="https://cdn-images-1.medium.com/max/630/1*TnDKL0AEkKMppTu43A1Wyg.png" /></figure><p>For someone whose kryptonite is algorithms, the coolest part isn’t the level of detail, which matches what passed for state of the art in 1983. It’s that the map can now tell me which keys open which doors, and which rooms the party can actually reach: from the entrance, behind a locked door, or unreachable.</p><p>That saved my bacon. Every key in the manuscript matched a door, but in several rooms the text never said which one. I must have figured out the pairing in my head the first time. Once the map knew about keys, it asked. Only one case was truly ambiguous: the small silver key in room 7 and two locked doors “to the south” it could plausibly open, one leading to room 8, the Chieftain’s Room, and the other below it into a random hallway. I picked the door to room 8 because it has a lot more going on. <em>(Wipes sweat off brow.)</em></p><p>I also used what it found to fix both the 1983 manuscript (through editorial notes) and several door descriptions in the 2027 edition, because I’m <em>writing prose, baby!</em></p><h3>When Claude had the right intentions: compatibility</h3><p>One thing I had to keep telling Claude in Xcode was that these are all libraries in development, with no external clients. It’s good to know that (at least in this case) it wants to be conservative about breaking backward compatibility, but it often chose options that didn’t let the library evolve fast enough. It took a lot of convincing to accept that changing the JSON format as part of a data or logic change was OK. So eventually, I made it an explicit caveat in each prompt. Once I did that, it was finally unleashed, and this enabled Claude to make certain changes across all three libraries in tandem. And once hashed out, Claude oh-so-carefully set about making changes, verifying that each propagated to the next downstream library, updating the underlying sample data and making commits along the way. Finally, we were cooking with gas.</p><h3>Where Claude fell short: interaction</h3><p>One thing I didn’t key into early enough was that when generating code from my prompts, Claude tended to “conservatively” pick UI elements that suit an iPhone best, when this app is most likely going to need the screen real estate of an iPad or Mac in order to truly shine. Also, unlike the random bits of lore my brain has stored away for such occasions, it wasn’t organically synthesizing the best existing interactive-drawing designs, and I have long-standing Opinions about that, deep in my subconscious. If only I could do a brain-dump or point it at best-in-class designs.</p><p>This was true when I worked on the character builder steps earlier in the summer—they weren’t quite up to my standards, and I’ll revisit them at some point. And it was especially true when I extended the map editing mode. Each new tool kept regressing the interaction from “almost working” to “completely non-functional.” In a word, clunky. It didn’t help that Claude was fairly clueless about how or why things kept breaking. The UI tests it generated took too long to run, didn’t test the right things, and so the prompts kept cycling through broken tests in a desperate attempt to make sense of them, and I kept having to stop it in its tracks and redirect it.</p><p>I wound up disabling editing behind a launch flag in the initial public release. Guiding Claude on UX remains an unsolved problem: I’m not there yet.</p><h3>Running with scissors</h3><p>I sometimes run fast with scissors. A prompt like “make hallway editing work” sent Claude confidently in a direction that wasn&#39;t necessarily mine. What reined it in was slowing down: getting specific about what I wanted, what “done” looked like, and how I’d check it, and then actually checking.</p><p>What worked best was separating planning from doing. I’d work through a problem in a chat with Claude (what’s broken, what the options are, what I’m not changing) and draft a detailed prompt there. Then I’d run that prompt in Xcode and confirm the results myself. What didn’t work was improvising in Xcode one tweak at a time, especially on UX. That’s where the whack-a-mole lived.</p><p>The planning half is where old failure-analysis habits paid off: stop the bleeding, then fix it right. Late in the release push, the example app crashed when it tried to view the first map. The culprit was infinite recursion: I’d made the settings both Codable and RawRepresentable so they could live in @AppStorage, and Swift’s default implementations of the two kept calling each other. Fixing it right meant writing the Codable conformance by hand and adding tests so it can’t come back. Sometimes the right outcome of weighing alternatives is to not decide yet, especially when time is a factor.</p><p>The stat lines shown earlier are a good example: I quickly realized I’d boxed myself in. “AC5, HD2, hp8” is just one kind of stat line; the 2027 edition points at SRD stat blocks instead, and other games have their own. The best move was to write down every kind of stat line I could think of as examples, and defer the choice of how to support them all to 0.2.0.</p><h3>Now, about that swamp</h3><p>With DungeonCore’s initial capabilities settled and public, my dungeon maps and descriptions are now in good shape. Which brings me to why I obsessed over them: I&#39;m expanding that 1983 manuscript into a 140+ page adventure module compatible with the SRD 5.2.1 ruleset. I’ll cover my journey so far with that in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924d3598a94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can you believe I still think Codable is frickin’ awesome?]]></title>
            <link>https://medium.com/@mrlegowatch/can-you-believe-i-still-think-codable-is-frickin-awesome-1e46fc2f0bb7?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e46fc2f0bb7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[codable]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 14:39:02 GMT</pubDate>
            <atom:updated>2026-09-15T14:39:02.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Pretty much. Mostly.</p><p>A long time ago (over nine years to be exact, from the time I am writing this), I wrote an article called <a href="https://medium.com/@mrlegowatch/omg-codable-is-so-frickin-awesome-bb9ff33139da">OMG, Codable is so frickin’ awesome</a>. As the title suggests, I was a little excited at the time. So, what’s changed, and how do I feel about it now, exactly?</p><p>Back then, Xcode 9 was in beta, and Swift 4’s Codable was a <em>Shiny New Thing</em>. I had wired up the USGS earthquake feed to a table view for a MathWorks Hackathon, made a couple of structs conform to Codable, called decode(), and watched JSON turn into typed Swift objects without writing a single line of parsing code. <em>Kaapow</em>. Then I went and started doing some genuinely fiddly things to <a href="https://github.com/mrlegowatch/RolePlayingCore">RolePlayingCore</a>, my D&amp;D-flavored Swift package, including measurement types, a dice protocol, nested sub-types, ability score dictionaries, and so on, and it mostly held up.</p><p>And then I went and used it for nine more years. On real things. But first, an explainer of how I got from there to here, and an answer to: why am I writing about it again now?</p><p>A couple of years after writing that article, I left MathWorks to build a mobile team at Wellframe, which Blackstone acquired and merged with HealthEdge, which Bain Capital then acquired and merged with UST HealthProof. And so it was… that I decided to retire. But I also set up <a href="https://www.muddypaddy.com/">Muddy Paddy Consulting LLC</a>. You know, <em>because reasons</em>. While I wait for consulting gigs to materialize, I’ve been writing a book about debugging and revisiting my open-source repos.</p><p>So. This is the follow-up: what happened when I moved on from using Codable for the thing it’s obviously for — RESTful JSON over the network — and started using it for a thing it is decidedly <em>less</em> obviously for: as the encoding layer of a persistent object store, with references between objects, in an open-source library used at Wellframe called <a href="https://github.com/mrlegowatch/GarageStorageSwift">GarageStorage</a>. And some time later, I got to fiddling with object references in RolePlayingCore as well.</p><p>Spoiler: it worked. Mostly. The hooks were there, and they got better over time. But you have to know where to look for them, and then use them appropriately, which is where things got interesting.</p><h4>Codable, circa 2017, in a few short paragraphs</h4><p>Here’s the whole pitch. You mark a type Codable — which is really two protocols in a trench coat, Encodable and Decodable — and the Swift compiler synthesizes three things for you: a CodingKeys enum, an init(from:), and an encode(to:). Nested structs, enums with raw values, optionals, arrays, dictionaries, etc. all work, as long as their elements are Codable. You hand the whole thing to a JSONDecoder, and it comes back typed.</p><p>Notice what’s not in that pitch: anything JSON-specific. Codable is a description of a type’s shape. JSONDecoder is just a thing that knows how to read that shape out of a sequence of bytes.</p><p>And when the shape doesn’t line up, there’s a ladder of escape hatches. Property names don’t match your JSON keys? Write the CodingKeys enum yourself with string raw values, or, if the mismatch is uniform, skip the enum and set keyDecodingStrategy = .convertFromSnakeCase. Need default values, or a flattened nested container, or “3 ft 2 in” turned into a Measurement&lt;UnitLength&gt;? Write init(from:) and encode(to:) by hand, pull a container off the decoder, and do it yourself. Which is more boilerplate than no boilerplate, but a lot less than guard let x = json[“x”] as? String else { return nil }, forty times over. So much <em>guard</em>. So many <em>angst</em>.</p><p>That’s it. That’s Codable. Its sweet spot is exactly what it was designed for: you have a backend, the backend speaks JSON, you’d like Swift types instead of JSON. Done. Ship it.</p><p>Now let’s take it somewhere it wasn’t designed for.</p><h4>A wildly cool part: it’s KVC, without the KV</h4><p>Here’s a thing I didn&#39;t appreciate in 2017, but came to appreciate a lot in 2019. Let’s talk about storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*buJ20o3vnoxEwwvN.jpeg" /><figcaption>Looking back at a step I took with the GarageStorage library</figcaption></figure><p>GarageStorage is a small open-source library — originally written in Objective-C by a former contributor at Wellframe — that stores arbitrary objects in <strong>Core Data</strong>. The Core Data entity is a generic box: it holds a JSON blob with a dab of metadata. You <em>park</em> an object in the garage; you <em>retrieve</em> it later. Two goals: simplify Core Data persistence for any kind of object, and eliminate xcdatamodel versioning and migrations entirely. Park whatever you want, whenever you want, no data model migration.</p><p>What makes it more than a JSON file is that the boxes can be uniquely identified, can hold references to other boxes stored separately, and can carry a sync status so you can fetch everything that hasn’t been pushed to a server yet.</p><p>To convert an object into and out of that JSON blob, the Objective-C implementation used Key-Value Coding. Every storable class conformed to a MappableObject protocol and returned an ObjectMapping: a dictionary mapping property names to JSON keys, plus an optional identifyingAttribute naming the property whose value serves as the object&#39;s identifier. Optional, because plenty of stored types don&#39;t need one. The encoder walked that dictionary calling valueForKey:; the decoder walked it calling setValue:forKey:, after instantiating the class from a string with NSClassFromString.</p><p>Which works! It also means: no type safety, stringly-typed property names (including that identifier), a runtime that has to be there, an if-then-else forest in the middle of the mapper probing every value to figure out what kind of thing it was, and support limited to the atomic types GarageStorage knows about directly.</p><p>Now look at Codable. Same job. Enumerate a type’s properties, convert them to and from a serializable representation, without the type having to write the conversion. Except the enumeration happens at <em>compile</em> time, the property names are checked, the types are checked, and the if-then-else forest is replaced by the compiler picking the right decode overload. It’s KVC without the KV. Without the runtime. Without the strings.</p><p><em>B’doiiing!</em> That’s the goal right there.</p><p>I wrote up the whole migration back in December 2019, in four parts, and the Codable addition was covered in <a href="https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3">Part 3: adding Codable</a> — so I won’t re-run all of it here. The short version is that a type that used to need MappableObject and an ObjectMapping and an @objc on every property could now be:</p><pre>struct Address: Codable {<br>    var street: String<br>    var city: String<br>    var zip: String<br>}</pre><p>That type knows nothing about GarageStorage. It doesn’t import it. It doesn’t conform to anything from it. And it can be stored in the garage. That’s the whole win, right there, in five lines.</p><h4>Some hairy and scary bits along the way</h4><p>Before we get to the hard problem, a few things that bit me. Because I am not the sharpest tool in the tool chest, and I sometimes get tripped up.</p><p><strong>Value types don’t do reference semantics, and your store might care.</strong> In Objective-C, everything in GarageStorage was a class. In Swift, once Codable shows up, structs are the obvious thing to reach for, and structs are copies. Decode the same nested address twice, and you have two addresses. For a genuinely value-ish thing like a street address, that’s fine. For a thing you expected to be shared, it is quietly wrong. GarageStorage ended up having to make that distinction explicit and visible in the type system, which — as we’ll see in a minute — turned into the central design question of the whole library.</p><p><strong>Types that were already NSCoding fight you.</strong> This came up first in RolePlayingCore, with Height and Weight, which are Foundation Measurement types over UnitLength and UnitMass. You know, because it’s cool to do that. NSCoding and Codable have never been reconciled (to the best of my knowledge), and trying to bolt one onto the other produces several kinds of hurt. The fix wasn’t to make the type Codable at all — it was to extend KeyedDecodingContainer with a decode(_ type: Height.Type, forKey:) overload (and decodeIfPresent, don’t forget decodeIfPresent) so the compiler would find it. Which, hold that thought, because adding an extension to a keyed decoding container is fraught with danger.</p><p><strong>And here’s one that made me feel genuinely dumb: infinite recursion.</strong> When you write a decode&lt;T: SomeProtocol&gt;() overload on KeyedDecodingContainer and then, inside it, call decode(T.self, forKey: key) to fall back to the default behavior — you don’t get the default behavior. You get <em>your own overload</em>, again, forever. The fix is a private shim that constrains T back down to plain Decodable, so overload resolution picks the standard-library implementation:</p><pre>private func decodeDefault&lt;T: Decodable&gt;(_ codable: T.Type, forKey key: Key) throws -&gt; T {<br>    return try decode(T.self, forKey: key)<br>}</pre><p>Duh. In hindsight, obviously. In the moment, wasted minutes and a stack trace that scrolled off the top of the debugger console.</p><h4>A hard limitation: object references</h4><p>OK. Here’s a hard problem, and it’s one I’d point at if somebody asked me what Codable can’t do.</p><p><strong>Codable has no concept of identity.</strong> It encodes trees. If object A holds a reference to object B, Codable will happily encode a complete copy of B inside A. If A and C both reference B, you get two copies of B. Decode it back and you have two Bs, which are now separate objects that will drift apart the moment anybody mutates one.</p><p>For a REST payload, none of this matters, because the server flattened the graph for you and handed you IDs. For an object store, it’s the whole ballgame.</p><p>Here’s why that’s harder in Swift than it was in Objective-C, and it’s a subtle point that took me a while to figure out.</p><p>In the Objective-C implementation, encoding and decoding were <em>direct</em>. GarageStorage owned the mapper. The mapper walked your properties itself. So when the mapper hit a property that was a MappableObject with an identifyingAttribute, it was already inside GarageStorage’s own code, holding a pointer to the garage, and it could just… go get the thing. The reference hook was a natural part of the library, because the library was doing all the work.</p><p>In Swift, GarageStorage doesn’t do all the work, JSONEncoder does. The traversal happens inside somebody else’s encoder and decoder implementation, and by the time your type’s init(from decoder: Decoder) gets called, you are deep inside a machine you don’t own and didn’t start. You have a Decoder. That’s all you have. You do not have a garage.</p><p>So the question becomes: <strong>how do you get context into a Codable traversal?</strong></p><p>The answer at the time was userInfo, and I’ll get to it in a moment. But first we have to talk about identity, because you can’t have a reference without one.</p><h4>Uniquing, or: what identifies a thing</h4><p>So: identity. In Objective-C, that was identifyingAttribute—an optional string, stringly-typed like everything else about that mapper. In Swift, I wanted it to be a real constraint. What I landed on in 2019 was a Mappable protocol:</p><pre>/// Protocol for providing a string id, to uniquely identify an instance of a reference Codable type.<br>///<br>/// This protocol is compatible with Identifiable where ID == String.<br>public protocol Mappable: Codable /*, Identifiable where ID == String */ {<br>    var id: String { get }<br>}</pre><p>Note the comment. And, especially, the <em>commented-out</em> part of the declaration. Clearly, I wasn’t at the top of my game, but hey, I was <em>trying</em>.</p><p>Swift 5.1 had shipped a few months earlier, alongside Xcode 11 and the first SwiftUI, and it brought Identifiable into the standard library - an associated type ID: Hashable and a single var id: ID. Which was exactly the thing I wanted. Almost. I needed ID to be specifically String because that&#39;s what the Core Data property holds, and I couldn&#39;t write protocol Mappable: Codable, Identifiable where ID == String at the time. Also, I get verklempt when it comes to templates, associated types, and existentials (oh my).</p><p>So I settled for implicit conformance: Mappable declared var id: String, which happens to satisfy Identifiable&#39;s requirement, so any Mappable type could declare conformance and it just worked. Not enforced by anything. Just… compatible, and a doc comment saying so.</p><p>And then, at some point in the last couple of years, I retired Mappable.</p><p>The current GarageStorage defines it as an empty protocol for convenience, but it’s no longer needed. It only needs Codable, and — for anything you want to park at the top level — either Hashable or Identifiable. Both of which are just… Swift. For example:</p><pre>class Person: Codable, Identifiable {<br>    // Map the identifier to a preferred property, if desired.<br>    var id: String { name }<br>    var name: String = &quot;&quot;<br>    var siblings: [Person] = []<br>}</pre><p>That’s the whole conformance list. Codable, Identifiable. Nothing from GarageStorage in it.</p><p>Which is the same trajectory as the Address struct from earlier, just finished: in 2017 a storable type needed MappableObject and an ObjectMapping; in 2019 it needed Mappable; today it needs two standard-library protocols and no knowledge about GarageStorage. Nine years of a library slowly getting out of a developer’s way.</p><p>The cost is that the constraint I couldn’t express in 2019 <em>still</em> isn’t precisely expressed in the type system — it just moved. Identifiable lets ID be anything Hashable, and the garage needs something it can write into a Core Data string column and read back. So the requirement is now: <strong>ID must be </strong><strong>String, </strong><strong>UUID, or </strong><strong>LosslessStringConvertible</strong> — checked at runtime, when you park the object, rather than by the compiler. It’ll throw an error indicating the requirement.</p><p>There’s more than one flavor of this, too, and sorting them out hurt my brain — so much so that I engaged with Claude to help figure things out, which only hurt my brain even more (that’s a story I’m saving for my debugging book).</p><p>OK, so. Objects come in these flavors:</p><ul><li><strong>Identified</strong> (Identifiable) — stored as its own Core Data object, referenced by id. There’s also an unidentified variant keyed by Hashable, but hash values aren’t stable across sessions, so you can’t use them to find anything later — it’s really only good for uniquing elements within an array.</li><li><strong>Anonymous</strong> (plain Codable) — serialized as inline JSON inside its parent. No separate object, not independently retrievable, and — this is the good part — it gets deleted along with its parent, because it <em>is inside</em> its parent.</li></ul><h4>The hook: userInfo</h4><p>OK. So we have identity. Back to the question: how do we get a garage into a Decoder?</p><p>JSONEncoder and JSONDecoder each expose a userInfo dictionary — [CodingUserInfoKey: Any]— that you populate before you start, and that gets carried along and made visible on every Encoder and Decoder handed to every type during the traversal. It&#39;s essentially a dependency-injection slot.</p><p>That’s it. That’s the whole mechanism.</p><p>So when the garage is about to encode or decode, it inserts itself:</p><pre>let decoder = JSONDecoder()<br>decoder.userInfo[Garage.userInfoKey] = self<br>// etc.</pre><p>And then a small convenience so nobody has to write the cast twice:</p><pre>extension Decoder {<br>    var garage: Garage? { self.userInfo[Garage.userInfoKey] as? Garage }<br>}</pre><p>Now, the other half. We need a decode that fires for identifiable properties specifically, and does the reference dance instead of the nested-value dance. Same trick as Height: extend KeyedDecodingContainer with a more specific overload and let the compiler find it. Here’s how it came out:</p><pre>func decode&lt;T: Decodable &amp; Identifiable&gt;(_ identifiable: T.Type, forKey key: KeyedDecodingContainer&lt;K&gt;.Key) throws -&gt; T {<br>    // If this decoder does not have a garage, decode as Codable does.<br>    let decoder = try superDecoder()<br>    guard let garage = decoder.garage else {<br>        return try decodeDefault(T.self, forKey: key)<br>    }<br>        <br>    // If the value wasn&#39;t encoded as a string reference (e.g., unsupported ID type<br>    // that was encoded inline), fall back to default decoding.<br>    guard let reference = decodeReferenceIfPresent(forKey: key) else {<br>     return try decodeDefault(T.self, forKey: key)<br>    }<br>    // If the reference resolves to a parked object, return it.<br>    if let object = try garage.retrieveDecodable(T.self, identifier: reference) {<br>        return object<br>    }<br>    // etc.<br>}</pre><p>Three things to note:</p><ul><li><strong>try superDecoder()</strong>. A KeyedDecodingContainer is not a Decoder. It’s a view onto one. superDecoder() is how you climb back up to the Decoder — and therefore to userInfo, and therefore to the garage. This is not obvious from the docs.</li><li><strong>The </strong><strong>guard let garage fallback</strong>. If there’s no garage in userInfo, we’re not being decoded with a garage — we’re being decoded by a plain JSONDecoder for a network call, or a test, or somebody’s debug dump. In that case, the type should behave like a plain Codable: encode its values inline, ignore the identifier entirely. Same type, two behaviors, selected by context. I like this more than I expected to. The type doesn’t have to know or care which world it’s in.</li><li><strong>decodeDefault</strong>. The anti-recursion shim from earlier.</li></ul><p>The encoding side mirrors this; you can <a href="https://github.com/mrlegowatch/GarageStorageSwift/blob/development/Sources/GarageStorage/Garage%2BCodableReference.swift">find it on GitHub</a>.</p><p>So: userInfo is the hook. It basically works, but it does have that “garage is an optional” limitation, which has its pros and cons.</p><h4>Another flavor: looking things up in tables built somewhere else</h4><p>GarageStorage’s references resolve against a store — the garage goes to Core Data and fetches. But there’s a second, more common version of this problem, and RolePlayingCore is where I ran into it.</p><p>Here’s the setup. RolePlayingCore reads D&amp;D-ish rules out of JSON: species, classes, alignments, abilities, dice. A Player has species traits and class traits. Those traits are *not* stored per player — they’re loaded once from configuration files into factories (Species manages SpeciesTraits, Classes manages ClassTraits, etc.), and every Player just points at the shared one. So when you decode a player, the JSON says something like “species”: “Rock Gnome”, and decoding has to mean “go find the SpeciesTraits named Rock Gnome in the table that was loaded five seconds ago at app startup.”</p><p>Same shape as the garage — resolve an identifier against a lookup — except there’s no store, no Core Data, no persistence at all. Just a dictionary somebody built at runtime, in memory, over there.</p><p>Now, here’s the timing joke. When I solved this in GarageStorage in 2019, userInfo was the only game in town. Then at WWDC 2021, Foundation shipped CodableWithConfiguration — a typealias for the pair EncodableWithConfiguration and DecodableWithConfiguration— which is the same idea, done more cleanly:</p><pre>public protocol DecodableWithConfiguration {<br>    associatedtype DecodingConfiguration<br>    init(from decoder: Decoder, configuration: DecodingConfiguration) throws<br>}<br>public protocol EncodableWithConfiguration {<br>    associatedtype EncodingConfiguration<br>    func encode(to encoder: Encoder, configuration: EncodingConfiguration) throws<br>}</pre><p>Instead of stuffing context into an untyped side channel and hoping it’s there, the type <em>declares</em> that it cannot be decoded without a configuration, and the configuration comes in as a typed parameter that the compiler will make you provide. There’s a @CodableConfiguration property wrapper for threading it down through nested properties, and container methods that take a configuration: argument, so you’re not hand-rolling the plumbing at every level.</p><p>So RolePlayingCore uses that. The configuration carries the lookup tables; init(from:configuration:) does the lookup. Here’s an example code snippet of a lookup of the Player’s speciesTraits by name:</p><pre>public required init(from decoder: Decoder, configuration: GameData) throws {<br>    let values = try decoder.container(keyedBy: CodingKeys.self)<br>    let speciesName = try values.decode(String.self, forKey: .speciesName)<br><br>    // three hours later...<br>    // Resolve speciesTraits from configuration<br>    guard let speciesTraits = configuration.species[speciesName] else {<br>        throw missingTypeError(&quot;species&quot;, speciesName)<br>    }<br><br>    // one day later...<br>    self.speciesTraits = speciesTraits<br>}</pre><p>For a notion of how this gets called, there is a GameData wrapper that loads an array of Players from a file and passes itself in as the decoder configuration:</p><pre>let jsonData = try bundle.loadJSON(fileName)<br>let players = try decoder.decode(Players.self, from: jsonData, configuration: self)</pre><p>One downside is that <em>it isn&#39;t automatic</em>. Every type in the chain that needs the configuration has to thread it through, which means every <em>containing</em> type also has to know about it, and it propagates up the graph. That’s real friction.</p><p>But look at what it buys, and look back at that userInfo complaint. With userInfo, forgetting to inject the context produces a runtime surprise. With a configuration, you can’t forget, because it won’t compile. Which is, I think, the correct verdict on userInfo: it was always the workaround, and now there’s a real answer.</p><h4>So. Nine years later.</h4><p>Where I’ve landed:</p><p>I still reach for Codable by default. For its intended use, it remains close to free, and I have written almost no JSON parsing by hand since 2017. Pretty sweet.</p><p>What it still doesn&#39;t do is identity and references. Codable encodes trees; object graphs are not trees. Every workaround for that — mine included — is a workaround. It works, and it’s maintainable, and I’ll probably reach for it the same way again, but it’s not a panacea.</p><p>So: can I believe I still think Codable is frickin’ awesome?</p><p>Honestly, a little. Nine years is long enough to fall out of love with most APIs, and I’ve fallen out of love with a few. What kept this one is that every time I hit a wall, there was already a seam, and the seams kept getting better. userInfo was a hack that Foundation eventually turned into a real feature. That’s a framework paying attention and evolving.</p><p>The exclamation point is gone, though. It’s a working relationship now.</p><h4>What say you?</h4><p>I’d like to hear other perspectives. What do <em>you</em> find awesome or deficient about Codable? Performance? Error messages, which can be unhelpful when a deeply nested optional goes sideways? Something I haven’t hit because I haven’t built the thing that hits it yet?</p><p>Tell me. Comments below, or reach out over <a href="https://www.linkedin.com/in/mrlegowatch/">LinkedIn</a>.</p><p>Happy Codable-ing. Still.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e46fc2f0bb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Off to the Races! Reviews for my debugging book’s examples, Part One.]]></title>
            <link>https://medium.com/@mrlegowatch/off-to-the-races-reviews-for-my-debugging-books-examples-part-one-2c590b2e8463?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c590b2e8463</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[technical-writing]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 20:23:34 GMT</pubDate>
            <atom:updated>2026-08-05T20:23:34.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNjHV6lDnJkvh04BRt1Z3g.jpeg" /><figcaption>Me, um. Racing.</figcaption></figure><p>This is the first entry in what I expect will become a short series about the content in the debugging book I’m writing. I previously <a href="https://medium.com/@mrlegowatch/current-status-of-my-book-about-the-art-of-debugging-47fa60556c6e">wrote about the book’s progress here</a>. Since then, I handed an actual chapter to strangers and asked them to tell me, straight up, whether it works. It did not go the way I expected, in some good ways and in a few humbling ways, and I’d like to share what actually happened, warts and all — and why I’m looking for a few fresh eyes for the next round at the end of this post.</p><h3>Why debugging matters, briefly</h3><p>Debugging is one of the best opportunities a developer has to grow, even though it can also be one of the most demoralizing parts of the job and one of the biggest sources of quiet burnout I’ve seen in this field. Getting unstuck, and getting better at remaining unstuck, is most of what this book is actually about. Debugging requires discipline, care, and follow-through, not just a hurried focus on the immediate problem. Everything below is what happens when you apply that premise to the book content itself and let others stress-test whether you actually followed it.</p><h3>Picking the example, and figuring out how to ask</h3><p>The book has ten worked failure scenarios (so far), each a full investigation into a real bug, and I needed to pick one to send out into the world first. “Off to the Races,” a Swift concurrency bug involving a session registry that crashes intermittently with an error message that has nothing obviously to do with concurrency, was the clear choice. It’s timely: many Swift developers are living through exactly this kind of pain right now as they adopt structured concurrency. That gave it a stronger hook for a community of working iOS developers than a more evergreen example might have had.</p><p>Figuring out how to ask for help turned out to be its own small design problem. My first draft of the pitch led with the mechanism itself. It came off clunky, so I iterated on it, and leaned into mystery and the “detective motif” writing style of the examples instead:</p><blockquote><em>“I’m deep in writing a book on debugging, and one of the scenario chapters is a bug I think a lot of you would enjoy chasing cold: code that looks completely correct, runs fine most of the time, and then occasionally crashes with an error message that has nothing to do with anything in your code.”</em></blockquote><p>I posted that to the iOS Folks Slack group, capped the ask at two or three people, and asked them to DM me rather than reply in-thread, partly to keep the channel tidy and to avoid ending up with fifteen volunteers and no graceful way to manage their feedback. I got twice as many responses than I needed, which I gladly accepted (you’ll see in a moment). When people responded, I sent along four short questions rather than an open-ended “what did you think”: asking where they first formed a theory about the cause, whether they got confused or bored anywhere, whether the reveal felt earned or came out of nowhere, and whether anything felt technically off. Small, specific, and roughly a ten-minute time commitment, since that’s what I’d promised.</p><h3>What came back, and how I dealt with it</h3><p>Several people who volunteered wound up dropping out anyway so the number remained manageable. We all have our reasons why we might offer to commit to something and then have life or work get in the way, and this was essentially volunteer work, but I have to admit that I was kind of hoping I’d hear from everyone, “something” that might resemble signal.</p><p>The feedback that came back covered a broader range than I expected, and reading it required more from me than I expected, too.</p><p>Some of it arrived like a scalpel: precise, technical, from people who clearly cared enough to read closely. One reviewer does this exact kind of debugging professionally and cuts straight to something specific: I’d asserted that a fix needed an auxiliary data structure without ever explaining why it was necessary. Fair and sharp. We’ll get to that in a moment.</p><p>Some of it arrived more like weather than critique: compressed, a little blunt, closer to a colleague thinking out loud in a design review than to a structured note. That left me convinced, on first read, that the reviewer wanted a fundamentally different, more best-practices-oriented book than the one I’m writing. I sat on it for a day before responding, and on a second pass the actual ask turned out to be narrower and entirely fair: not “add general design guidance” but “show your work for why this fix is correct.” Finding the real question beneath a first, prickly impression proved to be its own skill, separate from writing the chapter itself.</p><p>Some of the feedback was simply generous, the kind that costs the giver more than it costs you to receive. People who owed me nothing spent real time reading a stranger’s book chapter closely enough to catch things I’d missed. That’s not a small gift, and I don’t think I appreciated how exposed handing over a chapter would feel until it was actually out there, being read by people whose names I mostly didn’t know a month ago.</p><p>I always get a little nervous when receiving feedback. After decades in this field, the folks around me have mostly learned to treat me as the one with the definitive answer, the authoritative voice a problem eventually gets routed to. That reputation leaves little room to admit I don’t actually have the answer (which is often) or that I’d benefit from more pushback than I usually get. Even when I explicitly ask colleagues for constructive feedback, it tends to arrive softened, if it arrives at all. Asking perfect strangers turned out to be a useful antidote to exactly that, since they owe me none of that deference. It also surfaced a small, specific dread I hadn’t fully realized until after I’d hit post: what if the example I’d chosen was simply a bad one, or what if I’d built the narrative so transparently that the reveal was obvious to anyone paying attention, and some volunteer would tell me so, gently or not? There’s a moment, right after a pointed note lands, when my first instinct is to defend what’s already on the page rather than actually hear what’s being said. But debugging, done properly, is exactly this: showing your work to something — or someone — that doesn’t care about your feelings, for example, a stack trace, a failing test, or a reader who wasn’t in the room when you wrote it, and letting the result tell you something true instead of something comfortable. If the book is going to make that case to other people, I couldn’t write it from behind a wall of my own social awkwardness. So I posted it anyway and kept the conversations going through every round after that.</p><h3>What was in the chapter</h3><p>It helps to know roughly what the draft looked like going in. It opened with a session registry class, then moved to a discussion of a driver (a test-like command-line tool executable for the class) that crashed in several seemingly unrelated ways. A proper diagnostic unit test was added for finer-grained detection of the symptom, and then the narrative worked through a sequence of fixes: a naive lock, then a more careful lock paired with an auxiliary tracking structure, and finally an actor-based version, each run against the same stress test. Read on its own, it felt like a complete, reasonably careful investigation. It took other eyes and a fair amount of rerunning my own code to find out how much of that completeness was assumed.</p><h3>How the chapter actually changed</h3><p>The first and most instructive failure in this whole process wasn’t a reviewer’s. It was a mistake about what the accompanying code actually did, and it took two rounds of real evidence to correct.</p><p>The original draft I wrote claimed the crash was occasional without a deliberate random timing delay, and that adding one was what made it reliably reproducible. It read fine. It also wasn’t entirely true. I thought it was because that had been my experience with the real-life example it was based on. Plus, in just a handful of runs of the code with the driver, it failed to crash twice. It wasn’t until I looked for a more accurate statistic, such as how many times out of 10, 20, or more, that I realized the crash was hardly sporadic at all; it was crashing between nine and ten times out of ten. And when I actually created and ran the diagnostic test ten times against the unmodified code, it was as if the problem had fanned out: Instead of nine crashes consistently at the write line in the driver, the unit test found six crashes at the write line, three at the read line, and one run that neither crashed nor passed cleanly. Still 9–10 out of 10. The delay wasn’t necessary to make it more reproducible; the failure already was. The whole passage explaining why the delay mattered had to be removed and replaced with something grounded in what the runs actually showed.</p><p>As I continued exploring the code through the narrative beats, I found myself in exactly the reverse situation. After I added a lock around both the read and the write, the crash went away, but a different, quieter failure (duplicate session creation) kept surfacing sporadically, zero to three times in every ten runs. I already knew this failure was going to be there; it was already part of the narrative (which we’ll cover next), but I had no idea it was so sporadic. This was perfect. I had assumed the timing delay was now dead weight, since the race was already as exposed as it could get. Turning it on at this point demonstrated that the delay went from decorative to essential, turning a 0-to-3-in-10 failure into an 8-to-10-in-10 failure. The delay didn’t have one job across the whole chapter. It had no job at the start and a real one later, and the only way to know that was to keep running the code over and over again and look.</p><p>This whole roundabout exploration of two tangled-up faults in the code was a source of confusion for many reviewers. But it was a fresh reminder to me of several points I had already discussed elsewhere in my book, boiled down to this: debugging is messy because code is messy. If you’re learning how to become more effective at debugging, it’s best to face this reality rather than expect tidy examples that only explore clean relationships. For that reason, I decided to keep the two faults together in the same narrative, to drive this point home (despite the protestations of a reviewer).</p><p>The other real structural change to the narrative came directly from two reviewers who pushed on unearned claims from that secondary issue’s solution. The chapter said a lock solves concurrency problems, then introduced an extra structure, inFlight, alongside it with barely more justification than &quot;you can&#39;t hold a lock across an await.” I believed it because that had been my experience with the real bug this scenario is based on, but it’s not a reason for <em>that</em> structure. The actual answer was sitting there once I looked for it: release the lock to await the async creation, then reacquire it to store the result, and you&#39;ve reopened the exact race you started with, since two tasks can both pass the &quot;nothing here yet&quot; check while the lock is out. inFlight records that a creation is already underway, atomically, so a second task joins it instead of duplicating the work. That&#39;s a reason you can derive, rather than assert, and the chapter is better for having been made to earn it:</p><blockquote><em>“It isn’t there merely because a lock can’t be held across an await, though that’s true as well; it’s there so the moment you decide to create a session, that decision itself, not just its eventual result, becomes visible to every other task under the same lock.”</em></blockquote><h3>What’s next: volunteers wanted for Part Two</h3><p>I’m looking for two or three more volunteers to give the next scenario a reality-check:</p><p>Picture code that appears, ostensibly, to let go of something completely. A local variable set to nil. A list cleared out. Nothing left pointing at anything, as far as you can tell from reading the function that just finished. And yet, run enough real work through the system to see the pattern rather than a single clean, isolated case, and that supposedly finished thing is still very much alive, still responding to messages sent to it, as if nothing ever ended for it. All of them, in fact, standing around long after everyone involved thought they’d gone home.</p><p><strong>The Commitment:</strong></p><ul><li><strong>Time:</strong> ~10-minute read + 4 short feedback questions.</li><li><strong>Perks:</strong> I’ll return the favor with feedback on your work, and you’ll get a free early copy when the book is finished.</li></ul><p><strong>Interested?</strong> DM me on <a href="https://www.linkedin.com/in/mrlegowatch/">LinkedIn</a> or through <a href="https://www.muddypaddy.com/about/contact.html">muddypaddy.com</a> with “Part Two Review” and I’ll send the draft over!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c590b2e8463" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Current status of my book about the art of debugging]]></title>
            <link>https://medium.com/@mrlegowatch/current-status-of-my-book-about-the-art-of-debugging-47fa60556c6e?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/47fa60556c6e</guid>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 20:33:28 GMT</pubDate>
            <atom:updated>2026-07-11T20:33:28.451Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been writing about debugging for over twenty years now. Not in any organized way at first — mostly scattered across internal company wikis and Confluence pages, sometimes for my future self, and more often for others’ benefit. For most of that time, it was just how I processed the work. Something would go sideways, I’d chase it down, and afterward I’d want to write down what actually happened, not the sanitized postmortem version but the real shape of the investigation, including the dead ends. I think a lot of engineers do some version of this. Most of it stays scattered, though, and mine did too, for a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhzD_9dNIgcYuy2fpYPjXQ.jpeg" /><figcaption>Random notes on a whiteboard, me “waving hands” attempting to discuss design patterns to a new hire</figcaption></figure><p>Then, a little more than ten years ago, something shifted. The notes started fitting together. Themes I’d written about in different companies, different decades even, turned out to be related. An outline started to take shape in my mind, unbidden, the way outlines sometimes do when you’ve been circling a subject long enough without realizing you were circling it. I didn’t act on it right away. Life and work have a way of keeping that kind of project at arm’s length indefinitely.</p><p>What’s different now is time. With more of it on my hands lately, I’ve finally been able to sit down and turn that decade-old outline, and those twenty years of scattered notes, into actual chapters. Real content, not just structure. It’s evolving and coalescing, and that feels like a small miracle after so many years of the project living mostly in my head and internal wikis.</p><p>The book is about the art of debugging, aimed at software engineers at any level of experience, and it centers on the various steps involved in debugging. At a high level, it’s a way of thinking through a failure — of understanding and solving it. It may seem obvious written that way, but in practice it is not at all obvious, based on my own experience and my observations of many, many developers who have struggled with it. Most of the pain I’ve watched developers go through while debugging comes from reaching for a fix before the problem is actually understood. The guidance I provide exists to slow that reflex down just enough. I also provide tools and insights to debug more effectively, and perhaps even enjoy the ride.</p><p>Around that, the book is organized to walk through the whole arc of a debugging session: how to think about what’s actually happening when something breaks, the debugging process itself in some depth, a set of hands-on scenarios drawn from real failures I’ve either lived through or watched closely, and then a turn toward the harder cases, the ones that resist tidy resolution, along with some reflection on what debugging teaches you about writing, testing, and maintaining software in the first place. That last part matters more to me than I expected it to when I started. Debugging isn’t just cleanup work you do after the “real” engineering is finished. It’s a source of information about how to do the real engineering better next time, if you’re paying attention.</p><p>There’s also a thread running through the book with AI, and I’ve been spending serious “quality” time on that. A growing share of the code any of us debug now didn’t start as a human’s first draft, and that shifts the job in ways I don’t think we’ve fully reckoned with yet. AI-generated code tends to read with a confidence that a developer working through something unfamiliar rarely has — no hedging, no tentative naming, none of the usual tells that someone wasn’t quite sure. That surface polish can make it harder to know where to look first, right when knowing where to look matters most. My take, which the book argues in more depth, is that this makes human debugging skills more valuable, not less. Someone still has to close the gap when a failure reaches a user, and increasingly that someone is reviewing code they didn’t personally write. I’m treating AI as a partner in the process worth learning to use well, not a replacement for the judgment this book is trying to build.</p><p>Throughout my career, I’ve often ended up as the person people quietly hand the hardest problems to, the ones nobody else wants to touch, the ones with no obvious next step. I didn’t have a tidy name for that role until someone once called me the team’s “guerrilla debugger,” and that stuck, mostly because it was accurate. This book is my attempt to hand some of that experience off more deliberately than a wiki page ever could, in a form that might actually stick with someone the way certain books stuck with me.</p><p>I don’t have a publication date yet, but the time is fast approaching. What I have is steady progress, most days, and a project that finally feels like it’s catching up to the twenty years of thinking that came before it. I’ll keep sharing updates here as the manuscript takes further shape. For now, back to the writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47fa60556c6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Larry Tesler taught me about leadership]]></title>
            <link>https://medium.com/@mrlegowatch/what-larry-tesler-taught-me-about-leadership-7c1b49bdbbaf?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c1b49bdbbaf</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mac-app-development]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[leadership]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Thu, 27 Feb 2020 18:33:17 GMT</pubDate>
            <atom:updated>2025-09-05T17:52:52.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lr5fPeT_flypLqq5vtZrSA.jpeg" /><figcaption>“<strong>nomodes</strong>,” as surfaced in the “Phone Book edition” of the original Inside Macintosh documentation</figcaption></figure><p>With <a href="https://www.cultofmac.com/685669/larry-tesler-the-apple-employee-who-invented-cut-copy-paste-dies-at-74/">Larry Tesler’s recent passing</a>, I reflected on his impact on me, and on my career. Like many who cut their teeth in software development in the 1980&#39;s, Larry, indirectly, had a lot to do with how far I got in the first half of my career. And, more directly, he taught me important lessons about <em>leadership</em>, that I wanted to share, here, in a sort of rambling, self-indulgent sort of way, through <em>storytelling</em>. So, here goes.</p><blockquote>A long time ago, in a galaxy far, far away…</blockquote><p>From 1991 and all the way through 2005, my career was launched and propelled by the Macintosh, almost exclusively using the <a href="https://en.wikipedia.org/wiki/MacApp">MacApp framework</a>, that Larry Tesler was basically responsible for creating.</p><p>My origin story in software began with my first mentor, and coffee-and-bagel buddy, <a href="https://twitter.com/robchandhok">Rob Chandhok</a>, who, circa 1986, introduced me to MacApp, when I was a summertime Student Programmer at Carnegie Mellon University, working on a Mac email client of the <a href="https://en.wikipedia.org/wiki/Andrew_Project">Andrew Messaging System</a>. I wasn’t even a Computer Science major (well, I had been rejected, but… so… here we are, and, look at me, now), but I was very keen to understand how to program computers, and I was <em>sold</em> on the Mac — hence the summer job. So, naturally, I had one of these “phone book” editions of the <em>Inside Macintosh</em> programmer’s documentation, to help me along. But, Rob steered me in a different direction. He steered me towards MacApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZW7b3DUavDIZiz9V3GuPQ.jpeg" /><figcaption>*Yeah. I still have this. It’s very worn.</figcaption></figure><p>Let’s talk about the origins of MacApp for a moment. It goes something like this: First, Xerox invents the <a href="https://en.wikipedia.org/wiki/Smalltalk">Smalltalk</a> object-oriented language and runtime for developing graphical user interfaces on a computer nobody will ever buy; it’s too forward-looking and not practical enough (but, Jeebus, it’s got one heck-of-a dynamic runtime). This is all done by some very smart people, including Larry Tesler. Meanwhile (or rather, as a result), Apple starts working on this <a href="https://en.wikipedia.org/wiki/Apple_Lisa">Lisa</a> computer, and, gee, the Pascal language seems nice and all, so, they get Nicklaus Wirth (the inventor of Pascal, duh) to add Objects-and-Such to <em>that</em>. They, um, call that <em>Clascal</em>… you know, because it’s “<em>CLasses</em> in <em>pASCAL</em>”… but it doesn’t quite catch on because the Lisa’s too friggin’ expensive, and it bombs. So. Next they make the Mac. And, so. How about calling it <em>Object Pascal</em> instead? You know, because, <em>objects</em> sounds better than <em>classes</em>?</p><p>OK. So, circa 1986, there’s this new language, <a href="https://en.wikipedia.org/wiki/Object_Pascal"><em>Object Pascal</em></a>, and there’s this <em>MacApp</em> framework written in it, that will conveniently wrap all (or, most) of what’s described in that Inside Macintosh manual, in a way that’s super-efficient for developers to develop graphical user interfaces. And it’s not from Xerox, or called Smalltalk. But, it was still made by mostly the same smart people. Including Larry Tesler.</p><p>Or, something like that.</p><p>OK. So, I started using MacApp, and my head exploded. Programming was suddenly <em>smooth like buttah</em>. Super smooth, in fact. I was rockin’ it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*AfyUxK6KHGczcvx9TDD_2A.png" /><figcaption>The original MacApp logo, totally Susan Kare, aye?</figcaption></figure><p>A couple years later, I graduated with a degree in Mechanical Engineering, and got my first real job. Programming, naturally. That first real job, I also owe to Rob, who had pointed me in the direction of Ed Rubin and Max Henrion, in Carnegie Mellon’s <a href="https://www.cmu.edu/epp/">Engineering and Public Policy</a> department. They were looking for someone who had studied engineering (oh, hey! my degree was in mechanical) and could also program. So, I was programming professionally.</p><h4>Yay, and Ugh, HyperCard</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*i6b8Ekb6sv_qUMXXXpaXng.png" /><figcaption>HyperCard was a whole-lotta fun to program in… for a while</figcaption></figure><p>Weirdly, at that time, <a href="https://en.wikipedia.org/wiki/HyperCard">HyperCard</a> (a kind of harbinger of what the web would become) had become a thing, and for some stupid reason, we all bought into the idea that this was the future of computing. After two short years trying to implement a hierarchical influence diagram editor in that, my head <em>imploded. </em>It didn’t <em>scale</em>. It wasn’t <em>performant</em>. I had a mental breakdown, and I begged Max to consider switching to MacApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*INcSsWs98zzM0GHn-npKmA.png" /><figcaption>I dared to implement the predecessor to this Analytica modeling environment… in HyperCard… Yeah.</figcaption></figure><p>Max responded by asking me to fly out to California and give a demo of the influence diagram editor that I proposed developing with MacApp. In 2–1/2 weeks I had the demo ready, and a week later, I flew out to demo it. He then asked me if I would co-found a startup to commercialize <em>that</em>. Which begat <a href="https://lumina.com/">Lumina Decision Systems</a>, which is still around to this day. And! <em>Analytica</em> is <em>actually</em> <em>still using some of MacApp (on Windows, with MFC too, though)!</em></p><p>OK. OK. I know you want me to skip to the nugget about leadership. It’s coming. Hold tight. I’ve got some more <em>storytelling</em> to do.</p><h4>Aaaaand, then, there’s C++ on the brain</h4><p>Well, now, a couple-three more years go by, and around 1993, the <em>whole computing world shifts</em>, making way for another “new” language, C++, which was just C-plus-structs-renamed-as-classes-plus-vtables, but they couldn’t just call it CObject or CClasses (oh, sidebar: by this time Steve Jobs had already been ousted from Apple, and had caught onto another C-variant that was much more <em>dynamic</em> and Smalltalk-like, called <a href="https://en.wikipedia.org/wiki/Objective-C">Objective-C</a>, for NextStep, but, whatevs). So, naturally, Apple converts MacApp to C++. Just like that. Oh. And then, the <em>Macintosh shifts</em> from Motorola 68K processors to PowerPC. And, Object Pascal (or, importantly, the Object Pascal version of MacApp) doesn’t appear to be coming along for the ride.</p><p>Now, as the co-founder-and-also-main-programmer-with-no-real-title at Lumina, I’m in a mild panic. Because, I’d just invested several glorious years worth of code in Object Pascal with MacApp, and the world just changed to C++ and PowerPC, MacApp is now in C++, and Object Pascal is dead, like, as a doornail. Fuuuuuuuuuuuuuuu…dge.</p><p>Next, I did something crazy. A bit leader-y, perhaps. I forged <em>two paths forward</em>, one short term, and the other long-term. For the long term, I figured, we’re gonna convert <em>everything</em> to C++ and use the C++ version of MacApp, in order to stay relevant. And we started doing that, but the whole thing was going to take several years (2–1/2 to be more precise). In the short term, would it be possible to continue using MacApp in Object Pascal? And ship?</p><p>The short answer was yes, and yes. Because I said so. And, this is the part where Larry comes in.</p><h4>And then there’s the MacApp2PPC Developer’s Cooperative</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*Emv87YO-FRKFEIJrmzR1sQ.png" /><figcaption>The MacApp2PPC logo, designed by John Corbett</figcaption></figure><p>I formed the MacApp2PPC Developer’s Cooperative, a loosely-knit group of developers who were in the same situation—we all needed Object Pascal with MacApp ported to PowerPC in the near term, like in a year. We worked with a compiler vendor, Language Systems, who were willing to provide support for PowerPC, and proceeded to do the work of bringing MacApp to that.</p><p>After 10 months, we were getting close to finishing, but it became clear that we needed a stiff kick to get it—and our apps—to the finish line. So I did something else a bit leader-y: I decided to convene a three day hack session, at Lumina’s office in Mountain View, California.</p><blockquote>Sidebar: back then, WiFi didn’t exist, and we were about to have about 20 developers from around the world descend upon a very small office space that, at the time, only had a handful of computers and, like 8 ethernet outlets. We were going to need a lot more Ethernet switches and cables. I remember me and a co-worker scrambling over to Fry’s Electronics to buy and configure all of the necessary hardware, the day before everyone arrived.</blockquote><h4>OMG, It’s Larry $%#&amp;!! Tesler!</h4><p>OK. So, here’s the Larry part. Among the people who had RSVP’ed to this hack session was none other than Larry Tesler, who was Chief Scientist at Apple at the time. <em>Larry $%#&amp;!! Tesler</em>. And, I had no clue who he was, until <em>after</em> he had RSVP’ed, and someone else filled me in.</p><p>What I did know was, as with everyone else who came, he was there help finish the port, and to port some applications with his wife, that were written in Object Pascal with MacApp. He spoke with me several times briefly, and with others, and he was there the whole weekend. He picked up tasks that needed to be completed, and he ported code.</p><p>So. Wait. Hold a tick. Let’s repeat.</p><p>Larry <em>$%#&amp;!</em> Tesler <em>picked up tasks</em> to get MacApp2PPC over the finish line, and <em>ported code</em>. He didn’t have to be there. He didn’t know us from Adam. He could have just waited for the fruits of our labors, if all he needed was to port a couple of apps. And Apple certainly didn’t need MacApp2PPC in order to remain relevant; the C++ version of MacApp had over a thousand developers using it already, and there were tens of thousands more developers using Mac OS toolboxes directly (fools). But he was there, he was humble about it, and he was generous with his time. He got his hands dirty, and helped us, the <em>caboose of the developer community</em>, move forward into the future. And that eventually made a huge difference for a couple hundred developers.</p><h4>Say, what?</h4><p>In summary, we <a href="http://preserve.mactech.com/articles/mactech/Vol.12/12.02/PascalPPCMacApp/index.html">shipped a lot of MacApp applications on PowerPC</a>, after all was said, and done. And some time later, Lumina finished its C++ port.</p><p>Next, I went to Apple to work on the C++ version of MacApp as a Frameworks Engineer, which lasted until Steve Jobs returned to Apple, and canceled the MacApp project, eventually replacing it a few years later with Cocoa’s AppKit (the predecessor to UIKit, for those of you who are half my age, and only into mobile development). That’s a whole ‘nuther story.</p><p>After that, I worked at Media 100 on video editing applications written with the C++ version of MacApp, until 2005, when I finally put MacApp in my rear view mirror.</p><h4>OK, what’s the leadership nugget, already?</h4><p>So, through MacApp, Larry has been indirectly responsible for almost half of my career trajectory, through 2005, including working at Apple, on the MacApp framework itself.</p><p>But more importantly, Larry’s direct involvement during a three day hack session, taught me some very important lessons:</p><ul><li>never lose touch with developer needs,</li><li>get my own hands dirty, and</li><li>never lose sight of the caboose, when driving change.</li></ul><p>Oh, and to remain humble, and generous with my time. Those, too.</p><p>And, that’s what I learned about leadership from Larry Tesler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c1b49bdbbaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating to Codable GarageStorage (part 4 of 4)]]></title>
            <link>https://medium.com/@mrlegowatch/migrating-to-codable-garagestorage-part-4-of-4-b21148729ddf?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21148729ddf</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 02:34:38 GMT</pubDate>
            <atom:updated>2019-12-12T02:47:06.554Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Whereby Wellframe added support for data migration from the Objective-C compatible implementation to the Codable implementation.</em></p><p>This is a four-part article:</p><ul><li><a href="https://medium.com/@mrlegowatch/migrating-garagestorage-to-swift-part-1-of-4-5ee0744dbf6b">The <strong>first</strong> article</a> covered some background and the strategy</li><li><a href="https://medium.com/@mrlegowatch/garagestorage-uncovered-part-2-of-4-ff7c0356673e">The <strong>second</strong> article</a> went deeper into the implementation and how it changed in Swift</li><li><a href="https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3">The <strong>third</strong> article</a> covered how Codable support was added</li><li>This <strong>fourth</strong> article covers how data migration was handled</li></ul><p>To recap part 3, how Codable support was added:</p><ul><li>We added direct support for Codable, because, duh</li><li>We added a Mappable protocol, for identifiable types</li><li>We made Mappable types <em>references in JSON</em></li></ul><p>Oh, also, I’m working at Wellframe, blah, blah, blah, yadda, yadda yadda, and we’re hiring.</p><blockquote>Speaking of which, if you you want to make a difference in the world by improving other people’s lives, while reducing health care costs, now is a perfect time for you to join us. See <a href="https://www.wellframe.com/careers/">https://www.wellframe.com/careers/</a> for more.</blockquote><p>OK. We’re going to continue grooving on Codable in this article, building on top of the last article. If you’re relatively new to Codable, you may want a refresher: <a href="https://medium.com/@mrlegowatch/omg-codable-is-so-frickin-awesome-bb9ff33139da">OMG Codable is so frickin’ awesome</a>.</p><h3>Part the Fourth: Whither in-place migration?</h3><p>To the extent the following can be done (and, may God bless you if you actually come up with a way to test this), if I were to convert an actual MappableObject in the wild, from Objective-C into Swift, and have it conform to Mappable instead, I’d like for the new type to be able to decode from the MappableObject’s previously encoded data. In other words, ideally, I’d like to be able to perform <em>in-place data migration</em>.</p><p>Unfortunately, Objective-C and Swift don’t quite use the same naming strategy for the same named types in their respective languages, which gums up the whole matter, because GarageStorage counts on using the class name as a way to fetch objects.</p><p>Crap.</p><p>However, nested (MappableObject without identifyingAttribute) types are more anonymous, so it is actually possible to migrate those in-place. Just not the top-level types that are identifiable.</p><p>So, I say we do both—allow for in-place migration for nested MappableObject and explicit migration for objects that change names, and let’s see how the cards may fall.</p><h4>Milestone 4: Add migration support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0PklVCJ73PfxCPz623ZHhA.jpeg" /></figure><p>The parts in red (“Migrate!” and the “X”) are meant to indicate what happens next, after we add migration support. What it means is, if we successfully migrate to Swift-only types, we no longer require the Objective-C-compatible implementation, and we can safely remove it from GarageStorage (or alternatively, come up with a way to opt out of using it).</p><h4>In-place migration</h4><p>In the in-place migration scenario, there are several bits of gunk that need to be converted. The first, and easiest, is Date, because Codable already provides hooks for Date. The Date gunk looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bfc1dd5bb7f10a0e64fe65fa7ee2f74/href">https://medium.com/media/3bfc1dd5bb7f10a0e64fe65fa7ee2f74/href</a></iframe><p>All the Codable implementation should need is this:</p><p>encoder.dateEncodingStrategy = .formatted(Date.isoFormatter)</p><p>B’Boom. Except for the gunk between the Data and the transformableData, that needs to be decoded in place. So we need some kind of de-gunk-ifier in code, to eliminate the gunk in the Core Data storage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc5328f4a62f23686f715a2a6894a035/href">https://medium.com/media/bc5328f4a62f23686f715a2a6894a035/href</a></iframe><p>And, the decoder will be pointed at the custom decoding function:</p><p>decoder.dateDecodingStrategy = .custom(decodeTransformableDate)</p><p>Lather, rinse, repeat, for MappableObject references with identifyingAttributes.</p><h4>Another conundrum: what about anonymous MappableObjects?</h4><p>Now, I said we want to explore both in-place migration and explicit migration, but regarding anonymous (value-ish-type) MappableObjects that are migrated to simple Codable types (struct, enum, etc.), do we implement customizers (generics) in KeyedEncodingContainer and KeyedDecodingContainer for migrating anonymous MappableObjects without identifyingAttributes, or not?</p><p>If we do, one possible solution is to add a protocol, say Migratable, and the conform the new type to that protocol, such that migration would be automatic, if we follow a recipe that merges the Date migration with the Mappable references (only these aren’t references, just removing gunk).</p><p>But a consequence is that the new type will always attempt to migrate, everywhere it is used as a property of a Mappable. And, another consequence is that the type must explicitly conform to Migratable, which goes against our longer-term goal of reducing dependencies on GarageStorage.</p><p>So, I landed on a compromise, using a property wrapper. First, the gunk:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fc5f0b83dd91b696bd81b096da8d1af/href">https://medium.com/media/5fc5f0b83dd91b696bd81b096da8d1af/href</a></iframe><p>Then, the de-gunk-ifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9451aafcf48fe86200a8bef72d8caad/href">https://medium.com/media/b9451aafcf48fe86200a8bef72d8caad/href</a></iframe><p>And the migratable property wrapper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9aeba4d1aa72b0efc39b2f045502703/href">https://medium.com/media/c9aeba4d1aa72b0efc39b2f045502703/href</a></iframe><p>Now, I’ve been avoiding discussion of sync status, and we’ll continue to ignore it, to keep these articles moving, however it gets a bit more gunky in the context of data migration. Definitely, a future article…</p><p>So, going all the way back to part 2 for sample code, and combining it with parts 3 and 4, our migratable-from-ObjCPerson SwiftPerson class (with migratable-from-ObjCAddress SwiftAddress staying the same) ends up looking like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63c5c5cf44641ef4ab5608c104ee4886/href">https://medium.com/media/63c5c5cf44641ef4ab5608c104ee4886/href</a></iframe><h4>How to explicitly migrate</h4><p>Oh yeah. Right. How do you explicitly migrate a type whose name has changed? It looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/286da6ee259ee609891443a6f26c70b7/href">https://medium.com/media/286da6ee259ee609891443a6f26c70b7/href</a></iframe><p>If the old type (e.g., ObjCPerson) is no longer available, then whatever was previously returned from NSStringFromClass(), or whatever the name is in the Core Data store, can be passed in as a string, e.g., try garage.migrateAll(from: “ObjCPerson”, to: SwiftPerson.self). The idea is, migrateAll will find all objects in Core Data that previously had the class name “ObjCPerson,” decode it into aSwiftPerson and immediately re-encode it, in place. Gunk gone.</p><p>For each type that needs migrating, a migrateAll() is needed. Once all types have been migrated in the wild, the migrateAll() calls can be removed.</p><h4>Next step: The rubber hits the road</h4><p>So begins the next chapter for my team: to convert Objective-C code based on GarageStorage to Swift, and Codable.</p><p>Yeah, it’s a little messy, and contradictory. What do you expect? I’m Irish.</p><p>Thank you for reading. Please add your commetns below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21148729ddf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Codable support to GarageStorage (part 3 of 4)]]></title>
            <link>https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/1457a66864a3</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 00:05:15 GMT</pubDate>
            <atom:updated>2019-12-12T02:42:35.783Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Wherein Wellframe reimplemented GarageStorage to support Codable, while leaving its core bits shared with the MappableObject implementation</em></p><p>This is a four-part article:</p><ul><li><a href="https://medium.com/@mrlegowatch/migrating-garagestorage-to-swift-part-1-of-4-5ee0744dbf6b">The <strong>first</strong> article</a> covered some background and the strategy</li><li><a href="https://medium.com/@mrlegowatch/garagestorage-uncovered-part-2-of-4-ff7c0356673e">The <strong>second</strong> article</a> went deeper into the implementation and how it changed in Swift</li><li>This <strong>third</strong> article covers how Codable support was added</li><li><a href="https://medium.com/@mrlegowatch/migrating-to-codable-garagestorage-part-4-of-4-b21148729ddf">The <strong>fourth</strong> article</a> covers how data migration was handled</li></ul><p>To recap part 2, deeper into the implementation and how it changed:</p><ul><li>What’s a MappableObject, what makes one identifiable, have sync status</li><li><strong>Key milestone 1</strong>: Unit tests and improved Swift compatibility, like nonnull, NS_SWIFT_NAME(Blarg) and @objc(MYBlarg), etc.</li><li><strong>Key milestone 2</strong>: Actually converting GarageStorage to Swift</li><li>How the KVC sausage is made</li></ul><p>Oh, also, I’m working at Wellframe, blah, blah, blah, yadda, yadda yadda, and we’re hiring.</p><blockquote>Speaking of which, if you you want to make a difference in the world by improving other people’s lives, while reducing health care costs, now is a perfect time for you to join us. See <a href="https://www.wellframe.com/careers/">https://www.wellframe.com/careers/</a> for more.</blockquote><p>OK. We’re going to get a bit Codable in this article. If you’re relatively new to Codable, you may want a refresher: <a href="https://medium.com/@mrlegowatch/omg-codable-is-so-frickin-awesome-bb9ff33139da">OMG Codable is so frickin’ awesome</a>.</p><h3>Part the Third: Choices, choices</h3><p>When looking at the <em>slightly more idiomatic</em> Swift version of GarageStorage, it still leaves a lot to be desired. Specifically: it’s still relying on MappableObject and ObjectMapping to implement <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html">Key-Value Coding</a> for encoding an object’s properties. It would be <em>far more idiomatic</em> to</p><ul><li>leverage Codable, replacing ObjectMapping with CodingKeys</li><li>replace identifyingAttribute with an <a href="https://developer.apple.com/documentation/swift/identifiable">Identifiable</a>-compatible property</li><li>use generic (template) interfaces from top to bottom, stronger type-safety</li><li>make the APIs<em> that much more</em> type-safe</li></ul><p>This is a taller order than just getting Objective-C-compatible APIs implemented in Swift, but still achievable in an agile way, if we keep track of the Mikado Method steps for getting there.</p><h4>Milestone 3: Adding Codable support</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vj6lypY_zpRmyN2s7Uu8Mw.jpeg" /></figure><p>OK, so in building a parallel implementation, I chose to keep the Core Data model the same. What sits on top of that is what changed. For every MappableObject API, there would be an equivalent Codable-savvy API. We’d still need something similar to MappableObject for objects that require <em>identifying</em>, but Swift-only:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fcd5833ae1cdb94ff6af7000408cf2b/href">https://medium.com/media/7fcd5833ae1cdb94ff6af7000408cf2b/href</a></iframe><p>Now, if you didn’t blink, you might have deduced the following: anything that used to be MappableObject without an identifyingAttribute, could simply <em>conform</em> to Codable. So, the Address type which we saw in the previous article could now be a simple struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec7e00fecc6a01597e616344546d17d/href">https://medium.com/media/5ec7e00fecc6a01597e616344546d17d/href</a></iframe><p>B’doiiing. That’s the goal right there.</p><p>The cool thing about that is, the Address type doesn’t need to know (or depend on) anything about GarageStorage in order to participate in its storage. But, GarageStorage itself does need one more thing, if the type is stored as a root type (at the top level, directly, using a park API), which is some means to identify it, such as a hash value, so the Garage has a method with the signature park&lt;T: Encodable &amp; Hashable&gt;(_ object: T). If this Address type only participated as a property of another type that’s stored, it wouldn’t need the Hashable requirement.</p><p>So, what about types that have the <em>identifiable</em> requirement, that are now conforming to Mappable? GarageStorage maps them safely using Garage’s park&lt;T: Mappable&gt;(<strong>_</strong> object: T).</p><p>If you didn’t blink again, you might also notice that we’re enforcing type safety through the use of generics in the public API, which also gives the Codable implementation the advantage of knowing exactly what class to instantiate and decode, or encode, all the way down to the Core Data object. So, it no longer needs to know the class name (well, technically it still does, because it uses that as a form of lookup in the fetching APIs, plus it comes in handy for data migration, and as I have just contradicted myself, I’ll just stop there).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5335dace47780f3d01a5fe98a797244a/href">https://medium.com/media/5335dace47780f3d01a5fe98a797244a/href</a></iframe><h4>A funny thing happened while implementing Codable support</h4><p>Oh. Right. Something funny happened while implementing Codable support. The implementation got a lot simpler.</p><p>Since Codable just recursively encodes and decodes every nested structure conforming to Codable, there are no more raging if-then-else blocks in its implementation, no more urban sprawl of dictionaries-holding-references, transformable-types (of which there was only one, NSDate), and the like, and no more limitations on intrinsic-ish types. Because, Array and Dictionary conform to Codable if all of their elements also conform to Codable, and because Mappable conforms to Codable, just about any data type can participate, without needing to extend GarageStorage. Also, Date is supported directly, along with a customizable data formatter, so we didn’t need to carry-over GarageStorage’s Objective-C NSDate baggage. For the most part, this was awesome!</p><p><em>Except for one problem</em>: identifiable objects (MappableObject with an identifyingAttribute) are supposed to be encoded and decoded as references, not as nested values. Gah.</p><p>And so, the Codable implementation also got a bit more complicated, just in different ways.</p><p>So, to support storing and retrieving <em>references </em>to<em> identifiable </em>objects, we had to extend KeyedEncodingContainer and KeyedDecodingContainer, for types conforming to Mappable, to be able to look up for decoding (or park before encoding) the reference. Here’s a piece of the decoding part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b190e7e81ec251c5ad5304cae2bd07d0/href">https://medium.com/media/b190e7e81ec251c5ad5304cae2bd07d0/href</a></iframe><p>Just an FYI: The extra hoop you see where the decode&lt;T: Mappable&gt;() calls a decodeDefault&lt;T:Decodable&gt;() if there’s no garage, which just turns around and calls decode() again, is two-fold:</p><ul><li>The Mappable is effectively downgraded to Codable, so that the Codable decode() implementation can be called, instead of accidentally calling the Mappable implementation (which is, as I learned, duh, infinite recursion).</li><li>The Mappable can still be used directly as Codable, ignoring its identifier, for example, to make or receive network calls that require the use of JSON.</li></ul><p>By the way, the <a href="https://forums.swift.org/t/decodable-protocol-conformance-and-generics-how-to-dumb-down-a-conforming-type-to-call-the-right-implementation/29851">Swift Forums</a> is an excellent place to ask technical Swift questions of this sort, as I got more than one good answer to my questions, like the answers above. Don’t be shy, participate, and ask questions. And, the responders are <em>much friendlier and helpful </em>than on StackOverflow (suddenly, the author of this article ducks, and runs…).</p><h4>Summing up</h4><p>OK, so now we have one GarageStorage library with two implementations, an Objective-C compatible one requiring MappableObject (we’ll call it the <em>Objective-C-compatible </em>implementation), and a Swift-only one (we’ll call it the <em>Codable</em> implementation). Both use the same GarageStorage infrastructure, and both use the same underlying Core Data storage.</p><p>What’s next? <em>Migration</em>. Migration is what’s next.</p><p>Because, remember those if-then-else statements, and that urban sprawl? It resulted in a lot of extra information being stuffed into the JSON. In the Codable implementation, we didn’t need such nonsense. But if we want a Codable implementation to <em>replace</em> a MappableObject implementation in our code, like at runtime, in a software update, we’ll need a way to convert the extra information into the more compact world. The good news is, it’s all just JSON, so it’s feasible.</p><p>So, next we’ll move on to support data migration from MappableObject to Mappable, or to plain Codable, depending on how each type was used. This is the last piece of the puzzle, before we can start converting our application source code from Objective-C to Swift in earnest. And it’s the subject of the last article.</p><p>Thanks for reading this far! <a href="https://medium.com/@mrlegowatch/migrating-to-codable-garagestorage-part-4-of-4-b21148729ddf">The fourth article covers migration</a>. Please share your comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1457a66864a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GarageStorage uncovered (part 2 of 4)]]></title>
            <link>https://medium.com/@mrlegowatch/garagestorage-uncovered-part-2-of-4-ff7c0356673e?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff7c0356673e</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 00:04:42 GMT</pubDate>
            <atom:updated>2019-12-12T02:40:47.530Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Where Wellframe goes into detail on how Wellframe navigated changing an iOS production data storage system from Objective-C Key-Value Coding to Swift Codable.</em></p><p>This is part 2 in a four-part article:</p><ul><li><a href="https://medium.com/@mrlegowatch/migrating-garagestorage-to-swift-part-1-of-4-5ee0744dbf6b">The <strong>first</strong> article</a> covered some background and the strategy</li><li>This <strong>second</strong> article goes deeper into the implementation and how it changed in Swift</li><li><a href="https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3">The <strong>third</strong> article</a> covers how Codable support was added</li><li><a href="https://medium.com/@mrlegowatch/migrating-to-codable-garagestorage-part-4-of-4-b21148729ddf">The <strong>fourth</strong> article</a> covers how data migration was handled</li></ul><p>To recap part 1, the background and strategy:</p><ul><li>We want to keep our code base current, in part by migrating it to Swift, because reasons;</li><li>We are migrating this local storage system to Swift, because it’s tightly coupled with our code base, and it’s not a lot of code; and</li><li>We’re following the Mikado Method, which is like playing pick-up sticks for refactoring or rewriting code in an agile, continuously integrating way.</li></ul><p>Oh, also, I’m working at Wellframe, blah, blah, blah, yadda, yadda yadda, and we’re hiring.</p><blockquote>Speaking of which, if you you want to make a difference in the world by improving other people’s lives, while reducing health care costs, now is a perfect time for you to join us. See <a href="https://www.wellframe.com/careers/">https://www.wellframe.com/careers/</a> for more.</blockquote><p>OK. We’re going to get a bit “cody” in this article.</p><h3>Part the Second: The current (Objective-C) state</h3><p>The Objective-C implementation of GarageStorage provides several protocols that enable it to leverage Objective-C <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html">Key-Value Coding</a> (or KVC), for encoding an object’s data in JSON, before it is stored in a generic Core Data object. We’ll get to how it leverages KVC in a moment. First, what do these protocols look like in the wild?</p><h4>The MappableObject</h4><p>The primary interface, or protocol, is MappableObject, which is required for any non-intrinsic-ish type (intrinsic-ish types being the usual suspects:NSNumber, NSString, NSArray, NSDictionary, NSDate). Any class that you wish to store in GarageStorage must conform to MappableObject. Its main job is to provide an array of which properties should be encoded, in an ObjectMapping that it returns from a class method (property).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c52c9e6b839f2eabdfaea79caace86e4/href">https://medium.com/media/c52c9e6b839f2eabdfaea79caace86e4/href</a></iframe><p>OK, oops, I have to pause here, and admit that I’ve already cheated a little bit, and just showed you one of the small tweaks made in the initial Mikado steps. That is the @property (class, readonly) declaration for objectMapping in the protocol. It was originally + (GSObjectMapping *)objectMapping; but when making the API more “swift-compatible” I made this change to a class property, which didn’t affect any existing clients in Objective-C, but this subtle change made it more idomiatic in Swift.</p><p>Here is an example client declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a47978180d9a817f2546082b70faf008/href">https://medium.com/media/a47978180d9a817f2546082b70faf008/href</a></iframe><h4>Making objects identifiable</h4><p>If there are objects that must be unique, or reference<em>-able</em> for fetching, then the optional identifyingAttribute property in the ObjectMapping can be set to indicate which property uniquely identifies it.</p><h4>Tracking objects that have sync status</h4><p>If there are objects that are synced with a remote storage system (e.g., a back-end cloud service), then an optional, additional protocol, SyncableObject may be used to track the sync status of the object. GarageStorage will store that status in the underlying Core Data object for the purpose of fetching. In the interest of keeping these articles focused on transition, we’ll gloss over sync status for the remainder of these articles. (Maybe for a future article?)</p><p>Together, the sample code below illustrates an identifiable object that has references to other identifiable and mappable objects, with sync status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee2ac998678c67651c46d2f1c84185a4/href">https://medium.com/media/ee2ac998678c67651c46d2f1c84185a4/href</a></iframe><h4>OK, I’m getting the idea that GarageStorage is Objective-C-centric</h4><p>Yes. If you have spent any time in Swift, you can probably guess that using GarageStorage in that state isn’t going to be particularly <em>idiomatic</em> (or, natural to use) in Swift. Because, all the types would have an <em>unnecessary</em> GS prefix, as in let garage = GSGarage(), and all the calls would be <em>wordy,</em> as ingarage.parkObjectInGarage(nick). Department of Redundancy Department. Yes, I get it, I’m parking an object into this garage’s, uh, garage. And also, just about every parameter and return value is optional (or nullable) by default, because that’s the default behavior for Objective-C. And we haven’t even discussed handling errors, yet, but a lot of APIs may (or <em>should</em>) generate an NSError. However, some of the APIs don’t conform fully to <a href="https://developer.apple.com/documentation/swift/cocoa_design_patterns/handling_cocoa_errors_in_swift">Apple guidelines</a> for Swift error interoperability.</p><h3>Key milestones</h3><h4>The first key milestone: improved Swift compatibility</h4><p>Let’s remember the Mikado Method graph I created for a moment, to avoid stumbling down rabbit holes, and the first key milestone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8WIQcGOrhP-iMbuZ_cW2bQ.jpeg" /></figure><p>The first key milestone included:</p><ul><li>locking down the existing implementation with unit tests, initially written in Objective-C for maximum compatibility with the existing API, and</li><li>fixing up the Objective-C APIs so that Swift code will be somewhat more idiomatic (so, no prefixes, no redundancy in method names, assume non-null, etc.).</li></ul><p>Oh! By the way, if you’re currently on a path converting Objective-C code to Swift, Apple has great documentation for this, notably, starting at <a href="https://developer.apple.com/documentation/swift/objective-c_and_c_code_customization">https://developer.apple.com/documentation/swift/objective-c_and_c_code_customization</a>. It includes such hits as:</p><ul><li>NS_ASSUME_NONNULL_BEGIN ,NS_ASSUME_NONNULL_END , nullable, etc.</li><li>NS_SWIFT_NAME(...)</li><li>NS_REFINED_FOR_SWIFT</li></ul><p>You should sprinkle the heck out of your Objective-C code with these things, before you get too far along in a conversion to Swift. The nullability helps eliminate optionals where the APIs shouldn’t have them. The Swift naming helps drop prefixes, e.g. the GS prefix, and drop redundant terms in names, e.g., the words object, in, and garage. And, that last trick, NS_REFINED_FOR_SWIFT, can be used to allow for stronger type safety with Swift generics, which I used, for example, in extending the retrieve methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cdab3f10b69112d18d8c1502dc21714/href">https://medium.com/media/2cdab3f10b69112d18d8c1502dc21714/href</a></iframe><p>Also, don’t forget the trick of converting class methods, or even instance methods that don’t require parameters, and are <em>O(1)</em>, to declare them as readonly properties for Swift, to make them more idiomatc in Swift, reduce parentheses, etc.. The implementation can stay the same in Objective-C.</p><p>OK. So, the tests were still passing, the annotated Objective-C version of GarageStorage was integrated, if we were to start writing Swift code for it, it would have sucked less. Most importantly, we still had shippable code.</p><h4>The second key milestone: actually converting GarageStorage to Swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PzMk6hJTfWQF_86r9e8ZtA.jpeg" /></figure><p>For this milestone:</p><ul><li>a second set of unit tests were created in Swift, based on the Objective-C version of the unit tests; and</li><li>the whole implementation was flipped from Objective-C to Swift.</li></ul><p>Once converted, the naming annotations were reversed. For example, where there had previously been Objective-C declarations like NS_SWIFT_NAME(Garage) class GSGarage, there were now Swift declarations like @objc(GSGarage) class Garage. And, there were a handful more Swift-only declarations leveraging generics, because the implementation had made it easier to add them. And both languages’ interfaces were now covered with unit tests.</p><h3>How the KVC sausage is made</h3><p>Let’s dive deeper into GarageStorage’s parkObjectInGarage and retrieveObjectOfClass implementation for a moment, to understand how they makes use of KVC, and how they got converted to Swift.</p><p>OK, so the public APIs delegate implementation details to a helper class ObjectMapper. Blah, blah, blah, implementation, details, details, details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f55499dadd0fa9513d44f429dc4224c0/href">https://medium.com/media/f55499dadd0fa9513d44f429dc4224c0/href</a></iframe><p>So, when encoding, basically, it iterates over the given keys in the ObjectMapping, and calls the valueForKey: KVC method to fetch each property value. Snipped from the above are details for recursion over dictionaries, arrays, and any referenced MappableObjects. And dates.</p><p>So, how did that change when converted to Swift?</p><p>The Swift implementation does basically the same thing, except it achieves it by casting to NSObject instead of id in order to use the value:forKey: KVC method. Also, because reasons, I folded the ObjectMapper (which we haven’t really talked about, or explained, but hey, just go with the flow) back into the Garage class, preferring instead to implement a MappableObject-specific extension to Garage. We’ll get to why when we get to Codable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ce81cfcbc918f8ed4ffd5afeb69ddb/href">https://medium.com/media/36ce81cfcbc918f8ed4ffd5afeb69ddb/href</a></iframe><p>OK, so, basically the same thing, but implemented in Swift. Check.</p><p>What’s slightly more complicated is what happens when decoding. The Objective-C implementation relies on the class name string, using [NSClassFromString(className) new], and then iterating over the mappings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e66a437253cf74808e72af44a720fafb/href">https://medium.com/media/e66a437253cf74808e72af44a720fafb/href</a></iframe><p>In the Swift version, we have to be careful to cast the class into both the MappableObject protocol and NSObject. If we don’t do this, there’s a way to get code to still compile, but fail to link with an obscure linker error in NSSet. I couldn’t give justice to explain why, here. Compiler toolchains are beyond my pay grade to comprehend, but Googling for obscure linker errors isn’t.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2104a4bb0245409cc36e7a1b9b6c6c58/href">https://medium.com/media/2104a4bb0245409cc36e7a1b9b6c6c58/href</a></iframe><p>Now this all may seem exhausting—just imagine if you were the one doing the work—but it didn’t take very long to do, because of Objective-C Swift interoperability. I took the time to rename things as I went, as I came to understand the code better, which helped speed things up. What did take long to do was, how to write a parallel implementation for Codable, in Swift.</p><p>And that’s for the next article, <a href="https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3">linked here</a>. Thanks for reading part 2! Comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff7c0356673e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating GarageStorage to Swift (part 1 of 4)]]></title>
            <link>https://medium.com/@mrlegowatch/migrating-garagestorage-to-swift-part-1-of-4-5ee0744dbf6b?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee0744dbf6b</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Sun, 08 Dec 2019 22:58:00 GMT</pubDate>
            <atom:updated>2019-12-12T02:39:01.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Or, how Wellframe navigated changing an iOS production data storage system from Objective-C Key-Value Coding to Swift Codable.</em></p><p>This is a four-part article:</p><ul><li>This <strong>first</strong> article covers some background and the strategy</li><li><a href="https://medium.com/@mrlegowatch/garagestorage-uncovered-part-2-of-4-ff7c0356673e">The <strong>second</strong> article</a> goes deeper into the implementation and how it changed in Swift</li><li><a href="https://medium.com/@mrlegowatch/adding-codable-support-to-garagestorage-part-3-of-4-1457a66864a3">The <strong>third</strong> article</a> covers how Codable support was added</li><li><a href="https://medium.com/@mrlegowatch/migrating-to-codable-garagestorage-part-4-of-4-b21148729ddf">The <strong>fourth</strong> article</a> covers how data migration was handled</li></ul><h3>Part the First: some background</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*MjLzZbE-89nuJagOHgW26g.png" /><figcaption>The Wellframe experience</figcaption></figure><p>Hey! I recently joined <a href="https://www.wellframe.com/">Wellframe</a>, a Boston-based health technology company that delivers a mobile-enabled health care management platform. The mobile app connects people with care managers, supporting a variety of health needs. Building on our recent success, we’re now blazing new trails that will transform health care. My part in this story is in figuring out how to scale up our mobile app offerings. This is a very exciting time for us.</p><p>Because we have some existing code that we’d like to build upon, there are some challenges. For example, we need to start keeping our code bases current, so that we can innovate, avoid “code rot”, simplify maintenance, and reduce training for new hires. And, we’re going to have a lot of new hires.</p><blockquote>Speaking of which, if you you want to make a difference in the world by improving other people’s lives, while reducing health care costs, now is a perfect time for you to join us. See <a href="https://www.wellframe.com/careers/">https://www.wellframe.com/careers/</a> for more.</blockquote><p>Alright. So. Keeping our mobile code bases current includes using the mobile vendors’ preferred programming languages and SDKs. For Google Android, that means <strong>Kotlin</strong>, and for Apple iOS, that means <strong>Swift</strong>.</p><h4>Aaaand, there lies the rub.</h4><p>As with most mobile apps that have been around for a handful or so years, the iOS code base is written mostly in Objective-C. Like, 93%, at the time of this writing. By comparison, 82% of the Android code base is written in Java. Which isn’t so great, either. We’ve been a bit behind the curve on adopting the new languages, so to speak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*vyS63rZ01h0m5p77KCIaeA.png" /><figcaption>Modern language adoption in our mobile apps. Gah.</figcaption></figure><p>This is looming tech debt. The next generation of native user interfaces are going to be based on <a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> in Kotlin, and <a href="https://developer.apple.com/xcode/swiftui/">SwiftUI</a> in, duh, Swift. If we expect to continue innovating, we need to prepare our code base for that future.</p><p>Because we don’t have a lot of code in these new languages, it’s been easy to do the most important thing, which is to update to the latest compiler version; Kotlin 1.3 and Swift 5.1, as of the time I wrote these words. Keeping our library dependencies current is the next most important thing. For example, on Android, we recently moved to <a href="https://developer.android.com/jetpack/androidx">AndroidX</a>, and started replacing the Java-based Bolts library with <a href="https://kotlinlang.org/docs/reference/coroutines-overview.html">Kotlin co-routines</a>.</p><h4>What is GarageStorage?</h4><p>On iOS, we use a specific open-source library for local storage, called GarageStorage. It was created by a former <em>Wellie</em>, <a href="https://www.linkedin.com/in/sam-voigt-36446749/">Sam Voigt</a>. GarageStorage lets you store and retrieve any kind of data, and helps you synchronize it between local storage and a remote server.</p><h4><strong>How does GarageStorage work?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*WSMLv5CUQ2tqSKzn_60LGw.png" /><figcaption>Imagine yourself, storing your data in, um, a garage…</figcaption></figure><p>GarageStorage transforms object properties to JSON format, and stores that in <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html">Core Data</a>. The Core Data object is a generic data container, so it’s as if you stuffed your data into a <em>box</em>, and stored that in a garage. What makes GarageStorage a little different is, is that these <em>boxes</em></p><ul><li>may be uniquely <em>identified</em>,</li><li>may contain <em>references</em> to other <em>boxes</em>, each stored separately, and</li><li>may have <em>sync status</em> stored as metadata, so that objects, for example, may be fetched based on sync status.</li></ul><p>Additionally, GarageStorage allows a means for applying <em>encryption</em> to the stored objects, if there’s such a need. (We do, because we’re in health care).</p><h4>OK, so why convert GarageStorage to Swift?</h4><p>To start, we want to continue to support storing and retrieving arbitrary objects… <em>in Swift</em>. And, we want our Swift code to be <em>idiomatic</em>. That is, native to the language, not saddled with Objective-C-isms. The Swift <a href="https://medium.com/@mrlegowatch/omg-codable-is-so-frickin-awesome-bb9ff33139da"><strong>Codable</strong></a> protocol, for example, is the more natural way for mapping data to other formats. Whereas, the Objective-C implementation of GarageStorage relies on <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html"><strong>Key-Value Coding</strong></a>, which ties it to the Objective-C language and runtime.</p><p>After scratching my head for a while, I decided that it would probably be cheaper and smarter to convert GarageStorage to Swift, rather than replace it with something else that is supported better in Swift. One reason being, it’s not a lot of code; it’s basically just a wrapper on Core Data. And, it fulfills our current data storage requirements. And, it’s tightly coupled with our code base. Migrating GarageStorage to Swift and leverage Codable will significantly reduce that coupling, making it easier to replace in the future, should our requirements change. Which they probably will. <em>See, we’re thinking about simplifying maintenance…</em></p><h3>Now, for some strategy: the Mikado Method</h3><p>There are many strategies for making significant changes to code. One strategy that I’m familiar with is the Mikado Method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*hwF0DyTzWeRGy0w6U00WmQ.png" /><figcaption><a href="https://www.manning.com/books/the-mikado-method">https://www.manning.com/books/the-mikado-method</a></figcaption></figure><p>The Mikado Method is a refactoring strategy akin to the game of <a href="https://en.wikipedia.org/wiki/Pick-up_sticks">pick-up sticks</a>, with “undo.” When you start to refactor or rewrite code, there’s a tendency for one change to require another change, then another, in an endless cascade, where your code is <em>constantly</em> in a <em>broken</em> state, until you’re finished. If you’ve ever fallen down that rabbit hole, let me help you. Read the book. It will give you techniques and tools to map out the order in which you can refactor or rewrite code, such that at each node, you have submittable, working code. Really.</p><p>It works like this: first, set a goal, then naïvely start to make the change. When that change surfaces other related, necessary changes, you document those other changes as pre-requistites, <em>then you undo the first change</em>. You then iterate on each of those other changes individually, surfacing more changes, and undoing, until you finally reach the leafiest changes that don’t require other necessary changes. You do each of those and submit. When all of the prerequisites of a change are done, you can now make that change, and submit that. And so on, all the way back to the root change (your goal or objective). This is a very powerful, stable technique for making large-scale changes in an agile, continuously integrated way.</p><p>So, I used the Mikado Method to incrementally migrate the GarageStorage code, one small bit at a time. At work. In between meetings. OK, sometimes during meetings. Don’t judge me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXdxOXCY7QzHH8loTHi4Ng.jpeg" /><figcaption>Oh, Jiminy, that’s a lot of refactoring steps.</figcaption></figure><p>Above is a snapshot of the Mikado graph covering much of what I plan to talk about in this short series of articles. The graph is a mind map, created using <a href="https://mindnode.com/">MindNode</a> by IdeasOnCanvas GmbH—it’s a fantastic app, available on the Mac App Store.</p><p>Now that graph is a lot to parse, and it doesn’t help communicate how we were able to make the changes in shipping code. So, I created a simplified GIF of the high-level milestones coresponding with integrations into our git develop branch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*6uzUugWE-TYrHf50zMOXAQ.gif" /><figcaption>High-level milestones in the GarageStorage migration</figcaption></figure><p>What this shows is, we first added unit tests in Objective-C, to ensure that nothing (or as little as possible) would break during the conversion. Then, we set out to annotate the implementation, so that it would be somewhat easier to use in Swift, and converted the unit tests to Swift. This was the first baby step in enabling our future Swift code to be more idiomatic. It was also a fallback, in case the conversion went sideways. Then we converted GarageStorage to Swift, maintaining its Objective-C-based Key-Value Coding implementation. Then we added Codable support—and we could now follow <a href="https://en.wikipedia.org/wiki/Test-driven_development">TDD</a> for that, since this was all new code.</p><p>The last step is actually migrating our existing Objective-C code that depends on GarageStorage to Swift. That process could take a year or so to work through. But now we have multiple options for incremental migration, on a case by case basis: either keep using the Objective-C-compatible classes in Swift, or migrate to new Swift-only Codable classes. Eventually, because Codable is so frickin’ awesome, our code base will be completely Swift-only, and a future version of GarageStorage will deprecate its Objective-C support.</p><p>Whew! That was a lot of background and strategy. If you’d like to learn more about the GarageStorage implementation, and how it changed for Swift, please continue to the second article in this series.</p><p>Thanks for reading, so far! <a href="https://medium.com/@mrlegowatch/garagestorage-uncovered-part-2-of-4-ff7c0356673e">Here is the second article in this series</a>.</p><p>Feel free to ask questions in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee0744dbf6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Something very odd about my iOS App downloads in China]]></title>
            <link>https://medium.com/@mrlegowatch/something-very-odd-about-my-ios-app-downloads-in-china-f793bd6cab4c?source=rss-c9ad72f0a207------2</link>
            <guid isPermaLink="false">https://medium.com/p/f793bd6cab4c</guid>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[download]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[china]]></category>
            <dc:creator><![CDATA[Brian Arnold]]></dc:creator>
            <pubDate>Mon, 04 Sep 2017 14:18:05 GMT</pubDate>
            <atom:updated>2017-12-16T15:32:38.250Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s something very odd happening right now with my two free iOS App downloads in China. Like, downloads are up 1000% since August 17, 2017, and they’re being downloaded at about the same rate since then, even though they are both in English, and cater to very different audiences.</p><p>For the record, they’re both fairly niche apps that lack a marketing budget, so the download rates have been historically very low worldwide, 1 or 2 per day—“in the noise,” if you will. Neither of the apps are localized, so they’re primarily downloaded in countries that speak English as their primary language. Both of the apps have a very low session count and non-existent in-app purchase rate. Neither app presents ads.</p><p>One app, <a href="https://itunes.apple.com/us/app/what-the-walrus-knows-a-guide-to-beastie-energies-free/id827427351?mt=8">What the Walrus Knows: A Guide to Beastie Energies—FREE!</a>, is about animal totems. The other app, <a href="https://itunes.apple.com/us/app/vicars-drummer-jokes-celebrity-musician-guessing-game/id688628181?mt=8">The Vicar’s Drummer Jokes and Celebrity Musician Guessing Game</a>, is, well, about drummer jokes and guessing the names of celebrity musicians. The two apps couldn’t be more different.</p><p>I’m not trying to plug them, here, what I’m trying to do is point out that someone—or something—is downloading both of these apps at an alarmingly high and similar rate relative to the entire time these apps have been available (circa 2013 and 2014 respectively), in China, for reasons unknown to me.</p><p>Earlier this year, I noticed a modest increase in downloads for the Drummer Jokes app from 1–2 a day to about 20 a day, starting around May 20th (here is the 3 month period of April-July):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*fWev5ubSEhUpKYkGOC65YQ.png" /></figure><p>I didn’t really think much of it, at the time; maybe English classes in China were suggesting to download this app to students or something, but it carried on through the middle of August, so it started to seem odd.</p><p>And then, starting on August 17, downloads suddenly increased again, to 50–60 downloads a day (this is the month of August):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*BJ8Pf7VLZLhCk5szuN63aw.png" /></figure><p>Curiously, on the exact same date, my other free app, What the Walrus Knows FREE, increased from its 1–2 a day rate to about the same download levels as the Drummer Jokes app, 50 to 60 a day:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Uo8wAeNsxk7RNs783G94ew.png" /></figure><p>Notice that they both also peaked in downloads at around 110 and 115 on the same day, August 25. And, this is occurring exclusively from the China App Store, no other country stores are showing an increase in downloads (Walrus app):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ivfuGegQHBGI-QvLR46jXA.png" /></figure><p>China is 93% of all downloads for the month of August, 95% since August 17.</p><h4>This makes no sense at all</h4><p>If we dig into App Store product page views, e.g., for the Walrus app, we see that they remained flat during August, so there is no correlation whatsoever between page views and the increase in downloads, and it’s not at all due to word-of-mouth (which would be nice) or advertising (which I don’t do for these apps):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*JyuHBGnLBVN-nZ2EGz7rQw.png" /></figure><p>The device sessions are similarly flat. There is also no change in in-app purchases. For comparison, my other four paid apps enjoy the same download rates as before.</p><p>In iTunes, I changed the store to China and peeked at my apps, but I did not see any new app ratings. And, according to AppFigures, these apps don’t even rank in the top 400 for their categories, even with the increase in downloads.</p><p>So, what’s going on, here? If you have free apps, have you noticed an uptick in downloads in China?</p><h4>October 2017 Update</h4><p>The problem appears to have corrected itself around September 29–30; downloads dropped from 60–70 a day to 5–10 a day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f793bd6cab4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>