<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    <title>Jason Larsen — Engineer</title>
    <subtitle>Thoughts about the art of software engineering and design.</subtitle>
    <link rel="self" type="application/atom+xml" href="https://jarsen.engineer/atom.xml"/>
    <link rel="alternate" type="text/html" href="https://jarsen.engineer"/>
    <generator uri="https://www.getzola.org/">Zola</generator>
    <updated>2026-02-15T15:59:07+00:00</updated>
    <id>https://jarsen.engineer/atom.xml</id>
    <entry xml:lang="en">
        <title>Not Enough Code Was Never the Problem</title>
        <published>2026-02-15T15:59:07+00:00</published>
        <updated>2026-02-15T15:59:07+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/not-enough-code-was-never-the-problem/"/>
        <id>https://jarsen.engineer/not-enough-code-was-never-the-problem/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/not-enough-code-was-never-the-problem/">&lt;p&gt;A new term has been making the rounds, one anybody who has been using agents to do any serious work over the past year will immediately understand:&lt;br /&gt;
&lt;br /&gt;
Cognitive Debt.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;“…by weeks 7 or 8, one team hit a wall. They could no longer make even simple changes without breaking something unexpected. When I met with them, the team initially blamed technical debt: messy code, poor architecture, hurried implementations. But as we dug deeper, the real problem emerged: no one on the team could explain why certain design decisions had been made or how different parts of the system were supposed to work together. The code might have been messy, but the bigger issue was that the theory of the system, their shared understanding, had fragmented or disappeared entirely. They had accumulated cognitive debt faster than technical debt, and it paralyzed them.” -&lt;/em&gt; &lt;a rel=&quot;external&quot; href=&quot;https://margaretstorey.com/blog/2026/02/09/cognitive-debt/&quot;&gt;Margaret-Anne Storey&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I love this term. Feels like what I’ve been calling “&lt;em&gt;AI Brain-Fog&lt;/em&gt;.” It’s this weird feeling—which I imagine to be almost like some amnesia or Alzheimer’s—where I can’t quite put my finger on how something is working or why, or am surprised when some module can or can’t do something unexpected. It’s like, “I know this component’s name intimately, I grew up with it, but all of a sudden I can’t remember the name of the school we went to together.” And sure, when you work long enough in a system you will always have “I have no memory of this place” moments where you git blame and realize you wrote this code, but not with this frequency or depth.&lt;/p&gt;
&lt;p&gt;One might argue that all you need to do is go &lt;em&gt;deeper&lt;/em&gt; into the crevasse, that “more AI is the solution!” Or folks familiar with moving up the human abstraction ladder (management) might say this is just like having to let go of the implementation details, that it’s about the verification/feedback loops in place and measuring actual product outcomes. Every good engineer knows you should measure things before you optimize. Clean code is a spectrum, and &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/what-is-good-code-in-the-age-of-agents/&quot;&gt;the goal of clean code is working code that is easy to change&lt;/a&gt; so as long as the product works well and we can continue to change quickly… is there debt?&lt;br /&gt;
&lt;br /&gt;
And I would agree with a lot of that (I do think leadership has a lot of overlap with agent management), &lt;em&gt;but&lt;/em&gt;… the problem is humans are still the real ones with agency. Humans are the ones who will make the judgment calls about what to build and why, and be held accountable for those decisions. The AI will never be accountable. You could say the AI will make the judgment calls about what to build and why… but &lt;strong&gt;can you imagine being the human who is accountable, but not responsible for what is built?&lt;/strong&gt; No, that is hellish. The incentives will never allow it. No one will ever allow themselves to long term be in a position of accountability over a system they do not drive.&lt;br /&gt;
&lt;br /&gt;
Human value, good judgement, and wisdom remain as valuable as ever. AI will never change this. It might make them more rare, but that will only increase it’s value.&lt;/p&gt;
&lt;p&gt;And all this forgets something important, something every high performing software team and organization has always known: &lt;strong&gt;Writing code was never the bottleneck.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;This was the common argument for Pair Programming. The argument was “why would I have &lt;em&gt;two&lt;/em&gt; developers working on the same task when I could parallelize them onto separate tasks?”&lt;/p&gt;
&lt;p&gt;Leaving aside the complexities of parallelization and arguments about at what scale you actually see system improvements in throughput, the main argument in favor of Pair Programming boiled down to: &lt;strong&gt;two heads are better than one.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;With Pair Programming you essentially have &lt;em&gt;built-in, continuous code review. C&lt;/em&gt;ode review has always been one of the real bottlenecks in software. And what should you do when something hurts? &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/bliki/FrequencyReducesDifficulty.html&quot;&gt;Do it more often.&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
So going “slower” in this way actually can make us go faster. This will surprise no one familiar with the Theory of Constraints, or who from Goldratt’s that you should put the slowest Boy Scout in front.\&lt;/p&gt;
&lt;p&gt;Pair Programming also helps with another category of problem—the &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Bus_factor&quot;&gt;Bus Factor&lt;/a&gt; risk. When done right, after Pair Programming not only did two people design a better system, two people now are intimately familiar with and have working mental models of the new system. If someone in the pair is sick, switches teams, or moves companies, we still have someone who helped build the thing around. Every person who has moved up the human abstraction ladder understands what a bad idea it is for business to have only one person who understands the thing.&lt;/p&gt;
&lt;p&gt;In stark contrast to that in overly AI assisted programming workflows you are already at Bus Factor of 0. Sure you can spin up an army of agents to try to “understand the system” or bring you up to speed, but that’s still expensive and more importantly you are in &lt;strong&gt;the darkness of unknown unknowns&lt;/strong&gt;. You have to know you need to know something before you know to ask the AI for it. Having Humans with working mental models is key for keeping things in the realm of knowns and known unknowns.&lt;br /&gt;
&lt;br /&gt;
I don’t think this is a case of Pair Programming VS. AI Agents, I think there are ways to work with AI that are less conducive to this Cognitive Debt problem. It includes &lt;strong&gt;spending more time at whiteboards&lt;/strong&gt;. &lt;strong&gt;Spending MORE time doing code review.&lt;/strong&gt; Not just more time doing code review but getting better at detecting and &lt;strong&gt;reviewing the right things&lt;/strong&gt; (like focus on core architectural and design decisions, not getting lost in the weeds of naming and other bikeshedding type activities). Of course there are many ways AI can already and will continue to make code review easier+cheaper. But in the same way working out smarter not harder can get your body better results… you can never outsource the actual workout. Your trainer can not lift the weights for you.&lt;br /&gt;
&lt;br /&gt;
Writing code was not only about the ends (working code), but the means was an end in and of itself (building understanding of the socio-technical system). If we throw out too much, we remove some very important benefits.&lt;br /&gt;
&lt;br /&gt;
I think Pair Programming is a very interesting practice to explore in conjunction with agents—perhaps it can counter-balance the cost of abstraction. Martin Fowler &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/fragments/2026-02-13.html&quot;&gt;muses&lt;/a&gt; the same thing:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;There seems to be a common notion that the best way to work is to have one programmer driving a few (or many) LLM agents. But I wonder if two humans driving a bunch of agents would be better, combining the benefits of pairing with the greater code-generative ability of The Genies.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I am really interested in Pairing with another human. I had already been finding my XP Pair Programming skills valuable with agents. Thinking of the AI as the driver and of myself as the navigator, or trying ping-pong-esque TDD. Doing this with two humans might become more like Mob Programming than Pairing, but it would be really fun to experiment with.&lt;/p&gt;
&lt;p&gt;But anyways, back to the main point:&lt;br /&gt;
&lt;br /&gt;
Code has always been relatively cheap. People forget this. Or they are folks who never actually understood software development and always just wondered “why does this take so long?” And then they finally set up OpenClaw and are riding the initial high. People post about how they cloned Twitter/Reddit in a day (now clone the user base), or how Garry Tan spend a bajillion tokens and a week building a… newsletter?… when in 2005 DHH posted a video on how to use Ruby on Rails to make a blog in 15 minutes.&lt;br /&gt;
&lt;br /&gt;
Always explore and embrace new ways of working. Have fun, play! But the more things change, the more they stay the same. There are certain immutable laws here at play and you will not change them. We are rediscovering things we already knew faster than ever.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>AI Sidecar Workspaces</title>
        <published>2026-02-13T18:20:23+00:00</published>
        <updated>2026-02-13T18:20:23+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/ai-sidecar-workspaces/"/>
        <id>https://jarsen.engineer/ai-sidecar-workspaces/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/ai-sidecar-workspaces/">&lt;p&gt;&lt;em&gt;Creating a (buzzword warning&lt;/em&gt; 🤢&lt;em&gt;) “AI-Native” workspace without touching existing stuff or giving a fully autonomous agent unhinged access.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A few weeks ago, I sat down to help show our Head of Product how he could use Claude Code for… Not Code. I gave the usual rant about how it was poorly named, and to back up my argument days later Anthropic released Claude CoWork which is extra-sandboxed Claude Code with an opinionated UX and friendly name.&lt;br /&gt;
&lt;br /&gt;
Anyway, after walking through and setting up an environment with him (which ended with him submitting his first teeny PR fix within an hour of starting) I thought about how I might help other colleagues (data, compliance, marketing) set up similar workspaces… and I realized that I should put together something everyone at work could just copy and share.&lt;br /&gt;
&lt;br /&gt;
And so our new internal AI tool Seis Leches (inside joke), or &lt;code&gt;leches&lt;/code&gt; for short, was born.&lt;/p&gt;
&lt;p&gt;Within the week I would turn around and see it up on the data teams screens next to a browser with snowflake. Soon our Head of Compliance was telling his friends how in love he was with his new Claude Code workflows.&lt;br /&gt;
&lt;br /&gt;
This pattern, which I will call the AI Sidecar pattern, took people from mostly just using ChatGPT to doing real workflows within a week. And it did it without breaking any existing workflows, requiring modifications to any existing repositories, or giving unhinged levels of autonomous access to a bot running on a mac mini (lol). You don’t need a team of cracked engineers spending cycles building and maintaining a &lt;a rel=&quot;external&quot; href=&quot;https://builders.ramp.com/post/why-we-built-our-background-agent&quot;&gt;complicated new internal background agent tool&lt;/a&gt;. I did this in a few hours, and has required almost no support once set up. (It also relies on the strength and expertise of the frontier AI labs, without needing AI engineering expertise in-house, your own evals, etc.)&lt;br /&gt;
&lt;br /&gt;
It may require someone with a little more intermediate technical skills to do the initial bootstrapping, but once done people who have never opened a terminal in their life can use the workspace. It works with Claude Code (terminal or desktop app), Claude CoWork, and any other agentic harness your team might want to use (Codex, OpenCode, Amp, etc).&lt;br /&gt;
&lt;br /&gt;
It is deeply customized from the get-go to your org, your software and data stack, your rules, procedures, and compliance. It runs all on individual employees hardware and the AI Provider’s cloud of choice (if you were really crazy+technical you could move this to your own AI inference). Employees are monitoring and in-the-loop, with only the level of access they have/give to the agent.&lt;br /&gt;
&lt;br /&gt;
Note: this is not how I would set up a brand new product/team/repository (I will write about that at a later date), but I think this is the best option I know of for people who already have existing systems.&lt;br /&gt;
&lt;br /&gt;
Anyway, enough yapping. Let’s dive in.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;the-ai-sidecar-pattern&quot;&gt;The AI Sidecar pattern&lt;/h2&gt;
&lt;p&gt;In a nutshell, it looks something like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.
├─ CLAUDE.md              # shared workspace-level instructions
├─ claude.local.md        # gitignored. user specific customization
├─ .claude/
│  └─ skills/
│     └─ snowflake/       # skills on how to use your db and analytics tools
│        └─ SKILL.md
│     └─ setup/           # skill to help the agent set up its env
│        └─ SKILL.md
├─ repos/                 # clone everything from github into this dir
│  ├─ backend/
│  ├─ mobile/
│  └─ docs/
├─ scripts/               # anything programatic the agent can use/repeat
│  ├─ check-setup.sh
│  └─ setup.sh
├─ shared/                # shared artifacts for team
│  ├─ reports/
│  └─ prds/
└─ private/               # gitignored. contains drafts, personal work
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let’s talk about the most critical pieces first:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;You want a shared &lt;code&gt;CLAUDE.md&lt;/code&gt; (or &lt;code&gt;AGENTS.md&lt;/code&gt;, etc. you can symlink and use other tools but this tutorial is claude-specific for brevity’s sake). This is useful because most folks who are new to agents need help setting up a good CLAUDE.md file. You can get a decent start from &lt;code&gt;/init&lt;/code&gt; inside CC itself, but there is a lot more to maintaining a good CLAUDE.md. This lets people who just want to do work and not think about what goes on under the hood (yet) get started right away. We could write articles about theory on how to make good instruction files for agents. We don’t have time or space for that here.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;repos/&lt;/code&gt; – this is where you put everything from github. this had our backend monorepo, our mobile apps, and we had an internal kb repo and external customer facing articles repo. all were in here. No git submodules, just a directory with all the repos cloned. This is important because it doesn’t require any changes to any existing development, build, or deployment processes and pipelines. You just cloned the repos where CC can find it, without having to to use &lt;code&gt;/add-dir&lt;/code&gt; and/or constantly deal with annoying permissions to read directories outside the initial project root.&lt;/li&gt;
&lt;li&gt;Data and Analytic tools &lt;code&gt;skills/&lt;/code&gt; - we used snowflake and mixpanel, so I set up the snowflake cli tool and the mixpanel MCP server, and gave skills instructions on how to use them best (including where to look for schema definitions in the repos). This piece is likely the trickiest in any org—you might have differing rules around who can read what data, and you certainly don’t want write access from this thing. For us, at a small org, everyone already had snowflake access so that gave us a read-only replica. You could create all sorts of controls you need with this sort of layer.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And honestly you could get started with just these 3 things. The Code and the Data are The Ultimate Source of Truth™. Not docs. Not mental models or tribal knowledge. This is what you want to give to the agent above all. If your agent can read code and query real data, it’s going to give non-technical people a good feedback loop before they need to hit up the data or eng teams.\&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;setup-and-self-healing&quot;&gt;Setup and Self-Healing&lt;/h2&gt;
&lt;p&gt;&lt;br /&gt;
We could stop there, but less technical users may not be able to set this all up by themselves. That’s where the &lt;code&gt;scripts/&lt;/code&gt; dir and skill start to come in.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;setup&lt;/code&gt; script sets up any tools and mcp servers you want to give to people. It clones the repos. Not pictured, but it is also useful to have some &lt;code&gt;check-sync&lt;/code&gt; and &lt;code&gt;sync&lt;/code&gt; type scripts to help git pull the repos at some regular interval so that people don’t get too behind the current source of truth.&lt;br /&gt;
&lt;br /&gt;
&lt;code&gt;setup/SKILL.md&lt;/code&gt; – markdown is sometimes referred to as the “new programming language” and I think this has a lot of truth to it. Having a good setup markdown file allows the agent to troubleshoot its own setup. This way the system can more effectively self-heal, which is very ideal when working with less-technical folks.&lt;br /&gt;
&lt;br /&gt;
Even though markdown may be “the new programming language”, it is not deterministic. There are certain activities that can be deterministic, and that’s what goes in the &lt;code&gt;scripts/&lt;/code&gt; dir. These are things I don’t need the LLM to spend context on in sessions. (use the agent to bootstrap these bash scripts though).&lt;br /&gt;
&lt;br /&gt;
Another pattern I have been using is I have two scripts here for each activity the first script returns the state of things, and the second does the things. This is a pattern I have been using with agents so that the agent can decide whether or not to do something.&lt;br /&gt;
&lt;br /&gt;
So for example, the &lt;code&gt;CLAUDE.md&lt;/code&gt; tells the agent to always run &lt;code&gt;check-sync&lt;/code&gt; if it thinks it’s important to check the freshness of the code for the users current task. If it thinks that it’s too stale, it will run &lt;code&gt;sync&lt;/code&gt;. I like this pattern as it decomposes things a bit and makes the UX better when you are working from within agents.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;storing-work&quot;&gt;Storing Work&lt;/h2&gt;
&lt;p&gt;Now we have a system that can set itself up, do work against the source of truth, and self-heal and sync.&lt;/p&gt;
&lt;p&gt;But it gets a lot more useful if you have somewhere to store your work. That’s where &lt;code&gt;shared/&lt;/code&gt; and &lt;code&gt;private/&lt;/code&gt; come into play.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;shared&lt;/code&gt; is for… well, putting documents that you want shared.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;private/&lt;/code&gt; is gitignored so nothing ever makes itself upstream. This is great for work that is either a draft, or that I am using right now but would be noise for other folks.&lt;br /&gt;
&lt;br /&gt;
You can add skills for docs, reports, prds—whatever workflows are useful for your org—and let the agent know about shared vs private. It will help the users create and put these docs in the right places, follow any consistent formatting or workflows.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;extras&quot;&gt;Extras&lt;/h2&gt;
&lt;p&gt;Things that are not necessary, but that I set up and thought were cool/promising (not necessarily proven to be productive yet).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;a “commit”/sync upstream skill – this is very untested, but I wrote a skill that would help be unfamiliar with git to rebase and push to github (yes, main. not a production app and things are in VCS so I was not worried about it at our scale). Things that were in &lt;code&gt;shared/&lt;/code&gt;, or changes from the reflect skill (later) need to make it back to github so everyone else can get them.&lt;/li&gt;
&lt;li&gt;semantic search with &lt;code&gt;qmd&lt;/code&gt; - Agents do amazing search with only grep. However, if you could have semantic search on your docs, reports, etc., you might get more powerful and relevant results. For this, I setup &lt;a rel=&quot;external&quot; href=&quot;https://github.com/tobi/qmd&quot;&gt;qmd&lt;/a&gt; by [Tobi](&lt;a rel=&quot;external&quot; href=&quot;https://x.com/tobi&quot;&gt;https://x.com/tobi&lt;/a&gt;) (Shopify CEO). &lt;code&gt;qmd&lt;/code&gt; uses local models to do embeddings so it has not extra cost. This does require that everything people are putting into your directories are markdown. Power users could theoretically use qmd to index and query other documents outside the AI Sidecar monorepo as well.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;pandoc&lt;/code&gt; + &lt;code&gt;pdftotext&lt;/code&gt; for non-markdown documents — I didn’t get deep into this, but as proof-of-concept I set up skills to convert our existing compliance docs to markdown. these were then indexable for qmd. I would have the markdown become the source of truth, and setup skills/scripts to re-generate pdfs/docx files when markdown files are more recently updated than their counterpart.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;interview&lt;/code&gt; skill - if the &lt;code&gt;claude.local.md&lt;/code&gt; did not exist, I set up the agent to ask the user a few questions (name, role, tasks, AI experience level) and set up the personal instructions file. I think this has potential but is unecessary.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;reflect&lt;/code&gt; skill - This skill extract learnings from session, and automatically updates instruction files, suggesting whether it thinks its useful to share (add to &lt;code&gt;CLAUDE.md&lt;/code&gt; ) or if it feels like a more user-personal instruction (&lt;code&gt;claude.local.md&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Progressive disclosure with nested &lt;code&gt;CLAUDE.md&lt;/code&gt; files – you can add &lt;code&gt;CLAUDE.md&lt;/code&gt; files with more context relevant to particular subdirectories. This can be useful for the agent so that it loads more context relevant to directories it may be working in. This is particularly useful for the code repos.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;handoff&lt;/code&gt; skill – a skill that generates a handoff prompt for a user, and uses &lt;code&gt;pbcopy&lt;/code&gt; (if on mac) to put the it automatically in the system clipboard to the user can just paste it (this helps with weird markdown rendering stuff you often get copying from agents). This skill is really unnecessary, but I personally like it because it starts to teach less AI-literate folks to watch their context-windows for the “dumb zone”, and to start new sessions before just waiting for compaction.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;gh&lt;/code&gt; - github cli tool. even if people aren’t devs, i think this tool is useful. easy way for non-technical users to clone repos after logging in via web (no manual ssh key creation), and it can read issues if you use those, scan PRs which can be useful for knowing who to ask about something or understand what is in WIP.&lt;/li&gt;
&lt;li&gt;MCP servers for your ticketing system (Linear, etc.) – this could require an integration user or incur more cost from seats, but I think can be neat if you want to be transparent about planning, WIP, or let other folks create/update tickets and requests.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;p&gt;And that’s it, really. There’s a lot of opportunities and room for creativity and customization to your needs and your orgs needs.&lt;br /&gt;
&lt;br /&gt;
I think the core principles are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Put all the repos in one place, and figure out how to get access to reasonable production data. This creates the Ultimate Source of Truth feedback loop.&lt;/li&gt;
&lt;li&gt;Use the agent to bootstrap, set up and maintain its own environment, skills, etc. This helps ensure it is usable by less-technical teammates, and that they can begin to tailor it to their own needs without engineering help.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Hopefully this helps someone, or at least gives someone who has been thinking about doing the same thing the interest/confidence to try it out! Our team loved it and many people said they wished they had it sooner.&lt;br /&gt;
&lt;br /&gt;
What do you think? let me know on &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/jarsen&quot;&gt;Twitter&lt;/a&gt;.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Pay Attention to Incentives</title>
        <published>2026-02-08T19:50:14+00:00</published>
        <updated>2026-02-08T19:50:14+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/pay-attention-to-incentives/"/>
        <id>https://jarsen.engineer/pay-attention-to-incentives/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/pay-attention-to-incentives/">&lt;p&gt;Have you ever seen one of those YouTube videos from some 21 year old day trader standing in front of a (rented) lambo, selling you a course on how to become rich?&lt;br /&gt;
&lt;br /&gt;
Have you ever asked yourself, “if they are so rich from day trading, why are they selling me a course?” You would be asking the correct question.&lt;br /&gt;
&lt;br /&gt;
But at the same time there are some great YouTubers sharing really valuable information on personal finance that do it because they genuinely love the topic. And there are lots of legitimate people who think: “Why not find ways to side hustle sharing my passions? Win-win.”&lt;/p&gt;
&lt;p&gt;So how do you tell the difference? How do you know what voices to listen to?\&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;br /&gt;
&lt;br /&gt;
This last month has been a bit of a dumpster fire in a whirlwind. Ralph, rushing to buy mac minis for Clawdbot-&amp;gt;Moltbot-&amp;gt;Openclaw, claude vs codex arguments, Anthropic nuking Opencode, $20k mac studio setups running kimi 2.5 locally, Co-Work, new Cursor desktop, Claude Code teams, Opus 4.6 and Codex 5.3 minutes later…&lt;br /&gt;
&lt;br /&gt;
And when I get on AI twitter / build in public indie hacker twitter, it starts to feel like that YouTuber problem: &lt;em&gt;If you have discovered the secret to multi agent-swarms, replaced 30 business roles with your sub-agents, or have a lobster bot building you brand new companies filled with bots as you sleep… why are you tweeting about it and telling me how to do it instead of doing it?&lt;/em&gt;&lt;br /&gt;
&lt;br /&gt;
Getting overwhelmed and shutting off, getting distracted by playing with AI tools instead of building… all of these have worse productivity costs than the gains most people are getting from AI.&lt;/p&gt;
&lt;p&gt;\&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;br /&gt;
How do you decide who to follow, and who to tune out? For me, it’s all about thinking about the incentives. If I were this person, what incentives could I have for sharing this? What are they selling?&lt;br /&gt;
\&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Do they sell a course?\&lt;/li&gt;
&lt;li&gt;Do they work at an AI Lab?\&lt;/li&gt;
&lt;li&gt;Do they sell a tool? (especially an AI tool)\&lt;/li&gt;
&lt;li&gt;Do they have a newsletter/blog (does it have a paid tier or ads)?&lt;br /&gt;
&lt;br /&gt;
These are obvious ways someone could make money off your time and attention, or your wallet. Other incentives include building a network or resume.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;br /&gt;
None of these reasons by themselves, however, mean something nefarious is going on. Who doesn’t want to make money or build an awesome career? Who doesn’t want to be seen, acknowledged, respected? Many of my favorite posters work at labs or have newsletters.&lt;br /&gt;
&lt;br /&gt;
I have my own incentives writing this too—probably along the lines of I want to look smart, and say wise things so that people respect me and say “great post, Jason!” Maybe those people will want to work with me some day too.&lt;br /&gt;
&lt;br /&gt;
So, looking at incentives is not enough. It’s a reminder to take things with nuance and consider them ourselves, but it doesn’t tell us whether or not we should follow/unfollow this person on X.&lt;br /&gt;
&lt;br /&gt;
The next step for me if looking at how the post made me feel. Did the post make me feel excited? Or did it make me feel afraid? This part is more vibey, but I think that people who are trying to play positive sum/win-win games with you will not try to trigger your fear buttons. People who want to manipulate you will press those fear buttons. People who want to play positive sum games will try to inspire you. They will also be clear about their conflict of interests.&lt;br /&gt;
&lt;br /&gt;
A good example for me is &lt;a rel=&quot;external&quot; href=&quot;https://x.com/thorstenball&quot;&gt;Thorsten Ball&lt;/a&gt;. He tweets a lot of interesting things about AI, and he works at Amp. So, he definitely has an incentive to say things that promote AI. But he doesn’t try to scare you into it. His weekly newsletter is called &lt;a rel=&quot;external&quot; href=&quot;https://registerspill.thorstenball.com/p/joy-and-curiosity-73&quot;&gt;Joy &amp;amp; Curiosity&lt;/a&gt;. Curiosity is a key word here for me — curiosity drives creativity, excitement, exploration.&lt;br /&gt;
&lt;br /&gt;
Are the voices you see curious? Or are they authoritative know-it-alls? Do they question themselves? Do they constantly tweet about how SWEs are cooked? Do they share failures? Or is their feed a curated instagram-style look at me shipping all day win win win win win?\&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;br /&gt;
But you probably already know all of this. You probably have well refined BS detectors. The things is, in the modern world, with the pace of AI news and social media… our BS detectors can’t keep up with the deluge.&lt;br /&gt;
&lt;br /&gt;
And so even though I feel like I am easily detecting “that’s build in public bullshit hype they want to sell me their newsletter”… that doesn’t stop the subtle creeping feeling of overwhelm and being behind.&lt;br /&gt;
&lt;br /&gt;
The only thing that can mitigate that is consuming less, and creating more.&lt;br /&gt;
&lt;br /&gt;
Stop following so many people. Mute liberally on twitter. I have a pretty strict 1-strike rule. If you hype it up, and I have not ever gotten value from you, you’re out. Get out of the algorithm, use your following and list features. Follow great, moderate voices. People who are pushing themselves with AI, but also discuss the tradeoffs. I’ll add a list of some favorites below.&lt;br /&gt;
&lt;br /&gt;
Above all, learn to pause, be in silence, trust your own gut, and build your own things. This is what I tell myself, anyway. Easier said than done.\&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;X Starter Pack (in no particular order):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/simonw&quot;&gt;Simon Willison (@simonw)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/dillon_mulroy&quot;&gt;Dillon Mulroy (@dillon_mulroy)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/thorstenball&quot;&gt;Thorsten Ball (@thorstenball)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/mitsuhiko&quot;&gt;Armin Ronacher (@mitsuhiko)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/badlogicgames&quot;&gt;Mario Zechner (@badlogicgames)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/thdxr&quot;&gt;Dax Raad (@thdxr)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/aidenybai&quot;&gt;Aiden Bai (@aidenybai)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/GergelyOrosz&quot;&gt;Gergely Orosz (@GergelyOrosz)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://x.com/mitchellh&quot;&gt;Mitchell Hashimoto (@mitchellh)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Getting Into Vibes</title>
        <published>2026-01-08T05:26:29+00:00</published>
        <updated>2026-01-08T05:26:29+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/getting-into-vibes/"/>
        <id>https://jarsen.engineer/getting-into-vibes/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/getting-into-vibes/">&lt;p&gt;So it’s the year of our Lord 2026 and you’ve decided you procrastinated understanding how AI is going to change your career as a software engineer for too long. Now you want to learn to vibe code or vibe engineer or whatever people are calling it these days…&lt;br /&gt;
&lt;br /&gt;
Well, depending on your attitude I have bad or good news for you… even Andrew Karpathy, the man who coined “vibe coding,” &lt;a rel=&quot;external&quot; href=&quot;https://x.com/karpathy/status/2004607146781278521&quot;&gt;tweeted&lt;/a&gt; that he feels behind:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;I’ve never felt this much behind as a programmer. The profession is being dramatically refactored as the bits contributed by the programmer are increasingly sparse and between. I have a sense that I could be 10X more powerful if I just properly string together what has become available over the last ~year and a failure to claim the boost feels decidedly like skill issue. There’s a new programmable layer of abstraction to master (in addition to the usual layers below) involving agents, subagents, their prompts, contexts, memory, modes, permissions, tools, plugins, skills, hooks, MCP, LSP, slash commands, workflows, IDE integrations, and a need to build an all-encompassing mental model for strengths and pitfalls of fundamentally stochastic, fallible, unintelligible and changing entities suddenly intermingled with what used to be good old fashioned engineering. Clearly some powerful alien tool was handed around except it comes with no manual and everyone has to figure out how to hold it and operate it, while the resulting magnitude 9 earthquake is rocking the profession. Roll up your sleeves to not fall behind.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;So, where should a mortal even hope to start? How does one get rolling without absolutely drowning in the deluge of AI hype and noise?&lt;/p&gt;
&lt;p&gt;I’ve been talking to several people, and the following is the opinionated advice I’ve settled on. It’s not “right,” it’s just good and I think will get momentum in the right direction.&lt;br /&gt;
\&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Just get the&lt;/strong&gt; &lt;a rel=&quot;external&quot; href=&quot;https://claude.com/pricing/max&quot;&gt;&lt;strong&gt;$100/mo Claude code max subscription&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;.&lt;/strong&gt; Yes, really. The $20 plan is not good enough. You probably won’t hit the rate limits on the $100 plan unless you start going psycho multi-agent, so you don’t need the $200 plan. It might feel expensive, but this is an important investment in yourself. If you’re lucky your employer will pay for it. There are other great models but Opus 4.5 is the only one you should start with.\&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pick a CLI:&lt;/strong&gt; &lt;a rel=&quot;external&quot; href=&quot;https://claude.com/product/claude-code&quot;&gt;&lt;strong&gt;Claude Code&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt;, or&lt;/strong&gt; &lt;a rel=&quot;external&quot; href=&quot;https://opencode.ai/&quot;&gt;&lt;strong&gt;Opencode&lt;/strong&gt;&lt;/a&gt; if you really want to jump straight into something hackable. If you have to think longer than 5 seconds about it, or need minimal friction, you should start with Claude Code. Amp is a wonderful CLI tool as well but has its own token based pricing model that will probably make you nervous if you are getting started, and the free mode is not right for us. Both Claude Code and &lt;del&gt;Opencode will let you log in with your Claude max subscription&lt;/del&gt; (update, 1 day after I posted this, Anthropic cracked down on Claude Max outside of Claude Code, so just use Claude Code getting started). Both of these have desktop versions, and there are other good apps like Cursor, but the reason to pick a CLI client is because it is not well integrated with any IDE. We’ll dive in more later, but you will force yourself to work in better modes with agents if you can’t be in your IDE. Once you achieve some more mastery you can be allowed to use an IDE again (but you may not want to).&lt;br /&gt;
2.5 (bonus) Install &lt;a rel=&quot;external&quot; href=&quot;https://ghostty.org/&quot;&gt;ghostty&lt;/a&gt;. iterm belongs in our hearts and memories, not on our computers. You don’t need Warp because your agent is going to run all your bash commands for you anyway. We will allow wezterm or kitty.\&lt;/li&gt;
&lt;li&gt;Pick a project, and commit to using agentic workflows as much as possible. Just like the best way to learn vim is by taking away your mouse, you need to go through some pain to finally see the light. If you can’t use it for work either because of policies or it really is slowing you down right now, then start a new side project. If you are starting a side project, consider that agents are particularly good with more popular languages, and excel when given a framework. (claude code, open code, and amp code and seemingly everything now are typescript+&lt;a rel=&quot;external&quot; href=&quot;https://bun.com/&quot;&gt;bun&lt;/a&gt;. if you find yourself in paralysis about what stack to pick try it and you’ll be in good company).\&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Whether you are going greenfield or brownfield, the first thing you will want to do is run &lt;code&gt;/init&lt;/code&gt; in Claude Code or Opencode. This will generate a &lt;code&gt;CLAUDE.md&lt;/code&gt; or &lt;code&gt;AGENTS.md&lt;/code&gt; respectively. Yes, we are already into the world where every tool has its own config and dotfiles and we have no standards in sight. Go ahead and stop and read the file after it’s generated. This is the file your agent is going to load up every conversation, it is going to be its compass as it navigates your application. Use your agents to keep this file up to date as your app evolves.&lt;br /&gt;
&lt;br /&gt;
Now, we are going to try to do our first task. To do that, we need to talk about workflows. There are many stages of development, and the stage you’re at will greatly influence your workflow. Steve Yegge gives a great framework for understanding levels in his article about his insane new multi-agent orchestration tool &lt;a rel=&quot;external&quot; href=&quot;https://steve-yegge.medium.com/welcome-to-gas-town-4f25ee16dd04&quot;&gt;Gas Town&lt;/a&gt; (that you should not use):&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Stage 1: &lt;strong&gt;Zero or Near-Zero AI:&lt;/strong&gt; maybe code completions, sometimes ask Chat questions&lt;br /&gt;
Stage 2: &lt;strong&gt;Coding agent in IDE&lt;/strong&gt;, permissions turned on. A narrow coding agent in a sidebar asks your permission to run tools.&lt;br /&gt;
Stage 3: &lt;strong&gt;Agent in IDE, YOLO mode:&lt;/strong&gt; Trust goes up. You turn off permissions, agent gets wider.&lt;br /&gt;
Stage 4: &lt;strong&gt;In IDE, wide agent&lt;/strong&gt;: Your agent gradually grows to fill the screen. Code is just for diffs.&lt;br /&gt;
Stage 5: &lt;strong&gt;CLI, single agent. YOLO&lt;/strong&gt;. Diffs scroll by. You may or may not look at them.&lt;br /&gt;
Stage 6: &lt;strong&gt;CLI, multi-agent, YOLO&lt;/strong&gt;. You regularly use 3 to 5 parallel instances. You are very fast.&lt;br /&gt;
Stage 7: &lt;strong&gt;10+ agents&lt;/strong&gt;, &lt;strong&gt;hand-managed&lt;/strong&gt;. You are starting to push the limits of hand-management.&lt;br /&gt;
Stage 8: &lt;strong&gt;Building your own orchestrator&lt;/strong&gt;. You are on the frontier, automating your workflow.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;We are going to jump straight to Stage 5. It’s going to work.&lt;br /&gt;
&lt;br /&gt;
Here is your workflow:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Start a new chat. Tell the agent “I want you to help me plan my next feature. At the end of this we are going to write a PRD to our &lt;code&gt;.ai/prd&lt;/code&gt; directory.” Then describe the next feature/task to the AI and hit enter. Have a conversation with it. You will begin to see how it works. Stop to expand some of its collapsed thinking blocks to see the details. Look at what bash commands it runs. When you get to a point you are happy with and you think it mostly gets it, tell it it’s done and to write the file. If it’s not getting it, open a new chat and start over. This is all vibes. It will take more or less practice depending on your AI experience and how your brain works. Try to forget for a moment it’s an AI and talk to it like a human. Let it infer some of your meaning. Ask it questions when you don’t know what to do next.&lt;/li&gt;
&lt;li&gt;When you have your PRD written, open a new chat. It is very important it’s a new chat. Every agent has a Context Window, which is the amount of memory it’s currently holding from all the files its read, tool calls its made, web pages its fetched, and your messages. Once you start getting over a certain threshold, even as low as 60ish%, your AI will get into what we now call the “dumb zone.” Avoid it, you want to stay low in context %. (run &lt;code&gt;/statusline&lt;/code&gt; in claude code and make sure it sets up showing you what your context window % is. open code already shows the context window by default).&lt;/li&gt;
&lt;li&gt;Tell the new agent chat to read the PRD you just wrote, and to implement it. Don’t bother telling it bullcrap like “you are an expert Rails developer with 15 years of experience.” Just give it the PRD and watch it go. Give it permissions yes or no as it works. Look at the diffs. If you see it going the wrong direction, let it go for a teeny bit. See if it course corrects itself. If you don’t believe in it, hit escape to interrupt it. Tell it what it’s doing wrong, or ask it why it’s doing something a certain way. Keep going.&lt;/li&gt;
&lt;li&gt;Eventually your task will either be completed, or you will start getting into the “dumb zone.” As you get into the dumb zone, pause the agent. Tell it to help you generate a ‘handoff prompt’ that you are going to give to another agent to continue the work. It will print out a blob of text for you. Copy it. Create a new chat. Paste. Enter. Rinse and repeat until your task is done.&lt;/li&gt;
&lt;li&gt;But wait, how do we know when it’s “done?” this becomes increasingly difficult, especially as tasks span multiple chats. The way I like to do this is github. Your agent can use the &lt;code&gt;gh&lt;/code&gt; cli tool. It’s very good at it. Have it constantly commit to a branch. Tell it to open a PR. Review the PR, leave comments. Open a new chat. Tell it to use &lt;code&gt;gh&lt;/code&gt; to look at the comments you just left and fix them. Your agent is now your team member and you are its team lead. Guide it, give it some autonomy. Verify.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Do this a bunch of times, for a few days. Really really try to not write a line of code with your own fingers, even if you really want to.&lt;br /&gt;
&lt;br /&gt;
You will find you start to anticipate where the agent will get stuck. Other times it will blow your mind and do something surprising. You’ll get excited when it succeeds, you’ll get frustrated when it keeps ramming against the same problem.&lt;/p&gt;
&lt;p&gt;As you and the agent learn, the one thing you’ll want to do is keep updating your &lt;code&gt;CLAUDE.md&lt;/code&gt; or &lt;code&gt;AGENTS.md&lt;/code&gt; file. But don’t do this by hand—instruct the agent to do it. Have a session where the agent really struggled to figure out how to run an individual test? Tell it to update the &lt;code&gt;CLAUDE.md&lt;/code&gt; with what it learned. Tired of having to remind the agent to commit and push after it does something substantial? Ask the agent to encode that in the &lt;code&gt;AGENTS.md&lt;/code&gt; file. There is a lot of other stuff you’ll hear about – custom commands, custom agents, claude skills, MCP servers… hold off on those for a little bit. Hold off until you feel like you really have the hang of this loop, and now you are ready to learn some power user keybinds.&lt;br /&gt;
&lt;br /&gt;
Think about feedback loops. For the agent flywheel really to get get going—it needs to be able to create its own feedback loops. Having tests is one of the best ways to do this. AI is great at writing tests. Encourage it to do so. You may even consider starting with tests, or go as far as having your PRD define specs from a product point of view (and like that, we have come full circle to TDD/BDD, except now AI people who think it’s new call it “spec-driven development”).&lt;br /&gt;
&lt;br /&gt;
And that’s it. That’s my advice for someone just getting into vibes. Get Claude Max $100/mo. Get a CLI tool (probably Claude Code). Init your your &lt;code&gt;CLAUDE.md&lt;/code&gt;. Use the agent to plan to the work into a markdown file. Use other agents to implement the plan. If a chat gets to 60%+ context window, start getting a handoff prompt to give to the next agent chat. Update your meta repository and AI learnings in the &lt;code&gt;CLAUDE.md&lt;/code&gt;. Loop.&lt;br /&gt;
&lt;br /&gt;
If you get really comfy, maybe you start to learn about claude skills, or open up another tab to run a second Claude Code at the same time. Maybe you dare to learn what the hell “Ralph loops” are. If you do get to any of this, let me know! Hopefully this can be helpful to someone. And if you have lots of experience, what do you think about this approach? Any different advice? Drop me a line on &lt;a rel=&quot;external&quot; href=&quot;https://x.com/jarsen&quot;&gt;twitter&lt;/a&gt;.&lt;br /&gt;
\&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>What is &quot;Good&quot; Code in the Age of Agents?</title>
        <published>2026-01-01T16:20:11+00:00</published>
        <updated>2026-01-01T16:20:11+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/what-is-good-code-in-the-age-of-agents/"/>
        <id>https://jarsen.engineer/what-is-good-code-in-the-age-of-agents/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/what-is-good-code-in-the-age-of-agents/">&lt;p&gt;At a work offsite in mid-2023 I gave a talk to the engineering team about how AI was already changing coding. I advised that, like all change in the industry before it, there was no reason to be afraid, but you need to stay on the board and ride the wave or you are going to get left behind.&lt;br /&gt;
&lt;br /&gt;
Last year was insane. Even without model improvements, just the growth in our understanding of agentic workflows pushed us faster than I could have believed. We are so beyond tab completions. Now, on Jan 1, 2026, I am more bullish than ever.&lt;br /&gt;
&lt;br /&gt;
At heart I am a software craftsman. I care deeply about the flow and poetry of my code. I care about design patterns. I care about testing, and pair programming. This can sometimes present a level of cognitive dissonance when surrendering to the machine.&lt;br /&gt;
&lt;br /&gt;
AI doesn’t do it the way I would have done it (sometimes for the better, usually worse.) Fortunately I’ve had some experience letting go, as I’ve spent years in more senior leadership and technical positions, where you need to let go of certain levels of design decisions so that the people who will be maintaining the code are the ones who choose how to design it. You can offer guidance, and occasionally make demands – but aligning the incentive loops for people with the most skin in the game will lead to the best teams and software. Engineers start to care a lot more about code quality when they are on-call and feel ownership.&lt;br /&gt;
&lt;br /&gt;
So, delegating to another intelligence doesn’t feel so dramatic to me. I keep the same sort of checkpoints with it for now as I would any engineer on my team—I give it direction and then I review it at different intervals, dependent on the complexity of the task and my intuition about the agent’s relative capabilities.&lt;br /&gt;
&lt;br /&gt;
What can feel dramatic to me is an idea I see thrown around online quite a bit, that &lt;strong&gt;clean code doesn’t matter anymore&lt;/strong&gt;. I can’t get behind this… but also I recognize something is shifting.&lt;br /&gt;
&lt;br /&gt;
The basic argument goes like this: in a world where an AI agent can one-shot any prompt you have and make no mistakes, the old adage of “never rewrite your code” and need for thoughtful careful refactoring goes out the window. Because now you can truly just rewrite the whole thing from scratch. So, if you can just trivially rewrite the whole thing with no risk, you don’t need design patterns or legible code in the same way we moved from assembly to compilers (almost never) need to read machine code anymore.&lt;br /&gt;
&lt;br /&gt;
Talking about “clean code” has always been tricky, because no one really can agree on what it is. It’s always been a vibe. If Kent Beck and Martin Fowler coined “code smells” today it probably would have been called “bad code vibes.” Clean code is often an ethereal sense of taste.&lt;br /&gt;
&lt;br /&gt;
My favorite and most useful definition of clean code comes from David Thomas in the 20th anniversary edition of The Pragmatic Programmer: &lt;em&gt;good code is code that is easy to change.&lt;/em&gt; It doesn’t completely remove the vibes, but it gets down to first principles about it in a way that my brain screams “YES” to. Good design patterns have always been about making code easier to change—because especially in software—the only constant is change.&lt;br /&gt;
&lt;br /&gt;
Thinking about the future of code in terms of how easy code becomes to change helps me think about the future of design patterns. Now when I say “design patterns” – I don’t mean just OOP, gang of five college text book patterns. I mean generally any good patterns you find naturally emerging and repeating. Breaking down files, classes, large functions into smaller chunks. Organizing and managing dependencies to all point inwards and avoid cycles (e.g. DDD, onion, and hexagonal architectures).&lt;br /&gt;
&lt;br /&gt;
AI won’t change the fundamental laws of physics. I feel there are similar principles at the heart of design that won’t change, even if it comes up with new ways to apply them. Maybe AI can invent new ways of space travel one day, but it won’t eliminate the first law of thermodynamics.&lt;br /&gt;
&lt;br /&gt;
It’s hard to know exactly what these principles of software design are that won’t change. But I am pretty confident principles like Coupling and Cohesion will always be important in software systems. Maybe SOLID won’t. I have a feeling decomposition, abstraction, will always be important. Just like they help humans manage context, agents will need to be able to manage context as they work in large systems and relying on higher levels of abstraction will be critical to make changes well. Maybe that means principles like Single-Level of Abstraction will remain important. Architectures like Model View Controller may stay useful, because they will help agents be able to define thin vertical slices where they can complete end to end tasks while managing context.&lt;br /&gt;
&lt;br /&gt;
Anyway, just a quick start of the year post. I’m hoping to write a lot more this year. Not in a new years resolutions sort of way, just in a been meaning to for a while but never do it because I start planning and organizing my posts. Vs Twitter where I stream-of-consciousness vomit and never have a problem publishing my thoughts. So here it is, no editing, just hitting Publish. Happy New Year!&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Beauty of Fragility</title>
        <published>2021-04-24T00:00:00+00:00</published>
        <updated>2021-04-24T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/the-beauty-of-fragility-2/"/>
        <id>https://jarsen.engineer/the-beauty-of-fragility-2/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/the-beauty-of-fragility-2/">&lt;h2 id=&quot;and-learning-to-love-legacy-systems&quot;&gt;And Learning to Love “Legacy” Systems&lt;/h2&gt;
&lt;p&gt;Antifragility has been an incredibly important idea to me over the &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/finding-peace-in-a-world-of-unknowns&quot;&gt;past year&lt;/a&gt;. It has deeply influenced how I think about things ranging from my career, to my finances, to my relationships with loved ones, myself, and my spirituality.&lt;/p&gt;
&lt;p&gt;To me, the value behind the principle of antifragility is summed up in Taleb’s words, &lt;strong&gt;“I want to live happily in a world I don’t understand.”&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I want to learn to live peacefully in a world full of volatility and chaos. But I cannot control the world. I can only “control” me. Antifragility is not ordering the system around myself to keep me safe. Antifragility is learning to embrace change.&lt;/p&gt;
&lt;p&gt;Modern industrial society feels based on the idea that humanity lives in competition with the natural world. Humanity seeks to subjugate nature through its understanding of empirical principles gathered through scientific discovery. The principles often sit on top of consumerist values: what we have is never enough, and we always need to find ways to produce more and/or better things for consumption. Nature itself is one of those consumables.&lt;/p&gt;
&lt;p&gt;As our quality of living has improved (?) and gained momentum over the past couple centuries, we sometimes begin to operate under the illusion that we are winning. It takes a dramatic event—an earthquake, unexpected weather, disease, perpetually &lt;a rel=&quot;external&quot; href=&quot;https://www.cnn.com/2021/03/30/business/suez-container-ship-sizes-ever-given/index.html&quot;&gt;larger ships&lt;/a&gt; creating new patterns and clogging a canal—to remind us that we not, in fact, running the show. All the world’s a stage, but there is no human director.&lt;/p&gt;
&lt;p&gt;The idea that humans are in control is a coping mechanism for existential angst at scale. We live in a world of unknowns, but one thing we know for sure is that we all die. The fear of death and anxiety around the unknown is an extremely powerful motivator—&lt;em&gt;perhaps the fundamental motivator&lt;/em&gt;—and is deeply reinforced into our very being via evolution. Seeking to play the meta-game through our abilities of pattern recognition is what has led us to not just survive, but thrive. The evolutionary gift of anxiety may be a great gift for survival, but evolution did not design us to find peace in a world of volatility.&lt;/p&gt;
&lt;p&gt;People who still maintain deeper rooted connections to the earth—farmers, mariners, serious outdoors folk, or those in developing countries who don’t have the luxury of the illusion that humans are in charge, etc.—all understand that attempting to tame nature is a ultimately a fools errand. If your purpose is some variation of rule over nature, you will die unfulfilled.&lt;/p&gt;
&lt;p&gt;This doesn’t mean that humans should just keel over and give up. It means is that we need to replace fragile philosophies seeking to dominate nature with antifragile philosophies that create systems in &lt;em&gt;harmony&lt;/em&gt; with the world.&lt;/p&gt;
&lt;p&gt;Those who work in software often find themselves somewhere on an analogous spectrum when it comes to technical debt and “legacy” systems. There is an eternal tug-of-war between the ideal that we at least control this world of our own creation, and the recognition that software is never purely technical. Software is part of the real-world human systems that create, maintain, and operate it.&lt;/p&gt;
&lt;p&gt;There is certainly more to life than our occupation, but our occupation is part of our life. Learning to love—to work in alignment with (harmony), instead of against (dissonance)—the systems we work with a form of radical acceptance that will improve of our lives, and our software.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;wabi-sabi&quot;&gt;Wabi-sabi&lt;/h2&gt;
&lt;p&gt;I think many are familiar with the pop-sensation around Marie Kondo and her techniques for tidying. What I wasn’t familiar with—and still only have a terribly basic understanding of—are the deeper principles from traditional Japanese philosophies in which her tidying practices are rooted.&lt;/p&gt;
&lt;p&gt;One of these key philosophies is &lt;a rel=&quot;external&quot; href=&quot;https://konmari.com/wabi-sabi-and-the-art-of-kintsugi/&quot;&gt;wabi-sabi&lt;/a&gt;. Wabi-sabi is a philosophy stemming from Zen Buddhism that celebrates the transient nature of reality—it is focused on finding beauty in change over time.&lt;/p&gt;
&lt;p&gt;“Wabi-sabi nurtures all that is authentic by acknowledging three simple realities: nothing lasts, nothing is finished, and nothing is perfect.” — &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Wabi-sabi&quot;&gt;Wikipedia&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;One of the most observable practices based on wabi-sabi is &lt;a rel=&quot;external&quot; href=&quot;https://japanahome.com/journal/how-to-kintsugi-dyi-japanese-art-of-kintsukuroi-repair/&quot;&gt;kintsugi&lt;/a&gt;—which means “golden joinery.” Kintsugi is the practice of taking broken pottery and putting it back together with beautiful golden lacquer. The result is a new iteration of the object that not only respects the original object and the service it provided, but &lt;em&gt;celebrates&lt;/em&gt; the cracks and age by highlighting the faults and enables it to serve further. The “new” item is perhaps even more beautiful than before, and the lengthened history of service increases the connection between the object and the user.&lt;/p&gt;
&lt;p&gt;This celebration is a critical principle that often gets missed when we watch Marie Kondo on Netflix. Mostly Westerners see a technique for achieving a sort of minimalism of only living with things that bring us joy—but just as critical is the practice of taking the time to thank the objects being removed for the service they provided. The value is the connection between humans and their environment underneath, not the practices on the observable portion of the iceberg.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;memento-mori&quot;&gt;Memento Mori&lt;/h2&gt;
&lt;p&gt;Similar ideas can be found in western philosophy. There is a latin saying common in stoicism: memento mori. It means “remember that you die.”&lt;/p&gt;
&lt;p&gt;Many stoics will carry around physical trinkets, get tattoos, or adopt practices such as visiting cemeteries to serve as a reminder to meditate on life and death. This meditation is a chance to ponder our mortality, and to refocus energy on the things that really matter in our short, unpredictable lives.&lt;/p&gt;
&lt;p&gt;While not specifically referencing the stoic formulation of the philosophy, I think we see the same underlying principles present when we display urns, photos of lost loved ones, genealogy, etc.&lt;/p&gt;
&lt;p&gt;The recognition of death is at the same time a recognition of life—as two sides of the same coin one cannot exist without the other. Memento mori is a &lt;a rel=&quot;external&quot; href=&quot;https://whatisstoicism.com/stoicism-resources/memento-mori-reminder-to-live/&quot;&gt;reminder to live&lt;/a&gt;, fully (whatever that means to you), and in harmony with the world around us.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;legacy-software-systems&quot;&gt;“Legacy” Software Systems&lt;/h2&gt;
&lt;p&gt;The principles behind &lt;a rel=&quot;external&quot; href=&quot;https://agilemanifesto.org/principles.html&quot;&gt;agile&lt;/a&gt;, &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Extreme_programming#Principles&quot;&gt;Extreme Programming&lt;/a&gt;, &lt;a rel=&quot;external&quot; href=&quot;https://continuousdelivery.com/principles/&quot;&gt;Continuous Delivery&lt;/a&gt;, and DevOps all embrace change. But they are more than that: just as life and death are two parts of a whole, antifragility is just as much about non-change as much as it is change. &lt;strong&gt;Antifragility is embracing the whole&lt;/strong&gt;. Don’t purposely drop a bowl for an excuse to do kintsugi. Don’t wait for loved ones to leave to appreciate them.&lt;/p&gt;
&lt;p&gt;Antifragile things love change, but if a thing breaks under the status quo how can it hope to survive change? A working-philosophy of software that struggles to approach “technical debt”—both on how to accept it and how to pay it off—can only lead to personal stress and anxiety, and poor business outcomes. Agile, XP, and CD all seek to help us live happily in a world of actual software systems. They are philosophies for iteration that encourage us to ponder the transience of our software, and to identify the most important thing to try to change next, while accepting the rest—for now.&lt;/p&gt;
&lt;p&gt;The very first value of Extreme Programming is humanity. As we shift our views around the systems we work with, we must recognize that code is an artifact produced by human systems. Software Architecture is a sociotechnical system, not a purely technical one. Trash-talking the systems they wrote can damage the social system. It is also a blinding act of ego—I can’t tell you how many times I thought I understood and was going to redesign an amazing new solution… and in the process rediscovered the wisdom of the original authors. Amazing how many times technical debt means “code &lt;em&gt;I&lt;/em&gt;don’t understand.”&lt;/p&gt;
&lt;p&gt;We need to learn acceptance, but also we want to continuously improve. We need to develop the wisdom to know what to change, and when. We need to learn to work in harmony with the sociotechnical system, rather than in dissonance.&lt;/p&gt;
&lt;p&gt;I don’t need to big-bang “refactor” the status quo. In fact, Martin Fowler would like to remind you:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Every refactoring is a change that is so small that it’s not worth doing.” — Martin Fowler&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;In other words, any change you are making that you cannot commit and move on from at a moment’s notice is not a refactor. Small, iterative changes to a working system are more likely to bring about the changes to the system that we desire in a sustainable way.&lt;/p&gt;
&lt;p&gt;“Legacy” is often used to describe software systems as a pejorative, but the classic joke is also that “legacy code means the code that makes money.” What legacy almost always seems to mean is: the way things actually are, but not the way I want them to be. This dissonance between what I want and what is, is the source of unhappiness.&lt;/p&gt;
&lt;p&gt;There are myriad of reasons why we have an emotional response to “tech debt” and “legacy code.” The dissonance between us and perceived tech debt can certainly cause friction. This misalignment causes actual pain, and we do need strategies to tackle it. I want to tackle these strategies more in depth in the future.&lt;/p&gt;
&lt;p&gt;For now I will generalize and say that we often don’t understand legacy systems—and that fear from the lack of understanding is the software development version of existential angst. All systems will fail. We should think about systems memento mori often—not in manner resigned to a fated, cynical view that all computers are trash—but in a way that allows us to be realistic about what we can expect from complex systems generated by humans.&lt;/p&gt;
&lt;p&gt;Finding harmony in the give-and-take of our expectations and the reality of the systems we live with/in will start us on the path of internal peace.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>antifrAGILE: Continuous Delivery</title>
        <published>2021-01-25T00:00:00+00:00</published>
        <updated>2021-01-25T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/antifragile-continuous-delivery/"/>
        <id>https://jarsen.engineer/antifragile-continuous-delivery/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/antifragile-continuous-delivery/">&lt;blockquote&gt;
&lt;p&gt;Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.&lt;br /&gt;
&lt;br /&gt;
— First Principle of the &lt;a rel=&quot;external&quot; href=&quot;https://agilemanifesto.org/principles.html&quot;&gt;Agile Manifesto&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Breaking up work into small chunks and &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/antifragile-continuous-integration&quot;&gt;continuously integrating&lt;/a&gt; them back together is an energizing way to work. The smaller batches help make changes with reduced risk and enable agility. To fully enable our tight feedback loops, we need the ability to deliver software on a dime.&lt;/p&gt;
&lt;p&gt;Continuous Delivery (CD) is a practice focused on developing business processes and software architectures that enable teams to deliver software frequently, rapidly, and sustainably. CD makes deployment quotidian; deployment becomes second nature, and happens so often we stop paying attention. The boring and uneventful nature of deployment then enables us to focus on problems core to our business.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;deploy-vs-release&quot;&gt;Deploy vs Release&lt;/h2&gt;
&lt;p&gt;In order to talk about delivery effectively, we need to decouple two crucial ideas: deployment and release. Sometimes these words are used interchangeably, but we should apply rigor to them—the distinction is vital.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Deploy: new code/infrastructure is pushed to production.&lt;/li&gt;
&lt;li&gt;Release: new code/infrastructure is made accessible to users.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We can deploy without releasing. We can only release what is deployed.&lt;/p&gt;
&lt;p&gt;This distinction is important because deployment should become a behind-the-scenes engineering implementation detail—much in the same way users don’t care if you use git or mercurial. Users care about what they can use. We can deploy things that can’t be used.&lt;/p&gt;
&lt;p&gt;The act of releasing new things to use is a business decision. Releasing a new feature is done when Product is satisfied. Perhaps a release is timed as part of some event for marketing purposes. Every business will have their own strategies around the release process, the key is for the product development cycle to be aligned with this strategy, without becoming blocked by it.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;two-ways-to-release&quot;&gt;Two Ways to Release&lt;/h2&gt;
&lt;p&gt;There are two broad ways to release to users. The first is to deploy new functionality that is enabled. The second method is to toggle on functionality that you deployed in a disabled state.&lt;/p&gt;
&lt;h3 id=&quot;releasing-via-deployments&quot;&gt;Releasing via Deployments&lt;/h3&gt;
&lt;p&gt;Dead code is safe to deploy—deploying dead code cannot release new behavior, because it is, by definition, unreachable. You can write as much dead code as you’d like, call it from the safety of tests, and deploy as much dead code as you like to production.&lt;/p&gt;
&lt;p&gt;To release dead code, call it. As soon as a path opens up so that the code can be executed and that change is deployed to production—the once dead code is now released to users.&lt;/p&gt;
&lt;p&gt;One example is the &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/bliki/KeystoneInterface.html&quot;&gt;Keystone Interface&lt;/a&gt; approach. Keep deploying dead “backend” (whatever that means to you) code, and then a final deploy releases the “frontend” code that calls the backend code. Once the “frontend” code is deployed to production, the backend code becomes accessible through the frontend code and is thus released.&lt;/p&gt;
&lt;p&gt;Not all “backend” code has a corresponding “frontend.” One example might be a message queue and background workers. In these cases, the code may be dead until a change is deployed that allows the workers to begin running in production. Similarly, infrastructure such as a new database can be safely deployed as long as it is not being used.&lt;/p&gt;
&lt;p&gt;Releasing via deployment marries together the behaviors of deploying and releasing. However, we must be careful not to let the ideas of deployment and release become synonymous. Releasing via deployment is only one of the delivery tools at our disposal. It is simple, but inflexible. If our “frontend” component is large, doing this in a CI fashion will be next to impossible—we do not want to block deploys because one area of the code is not ready to be deployed. Not blocking deploys is at the heart of CD.&lt;/p&gt;
&lt;h3 id=&quot;releasing-via-feature-flags&quot;&gt;Releasing via Feature Flags&lt;/h3&gt;
&lt;p&gt;Another way to make code inaccessible to the user is by the &lt;a rel=&quot;external&quot; href=&quot;https://www.youtube.com/watch?v=V3Mt8n3pC5c&quot;&gt;cunning use of flags&lt;/a&gt;. By using a feature flag system (please do not use this system for account configuration), code can be made effectively dead. Toggling feature flags dynamically enables/disables functionality in production.&lt;/p&gt;
&lt;p&gt;Robust feature flag systems will allow you to even release to small subsets of users, allowing you to test in production and perform gradual, monitored, roll outs of new features. Although often complex, you can take similar approaches to roll out new infrastructure, perhaps writing to two databases until you flip a toggle to switch the source of truth.&lt;/p&gt;
&lt;p&gt;There is no such thing as a free lunch, so again we face tradeoffs. We must now manage a new tool (the feature flag system), and we must exercise eternal vigilance to clean up released feature flags. Unkept feature flags become a rat king of entangled artifacts, obfuscating the codebase, adding exponential complexity of possible configurations, and giving ourselves the ability to accidentally ‘unrelease’ in the future if someone flips a toggle they shouldn’t have.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;continuous-delivery&quot;&gt;Continuous Delivery&lt;/h2&gt;
&lt;p&gt;We knowing the difference between deploy and release, and understanding methods to release. However, we are left with the elephant in the room: how can we make sure that the code is always ready to deploy?&lt;/p&gt;
&lt;p&gt;The goal of CD is to make sure that the code is always in a deployable state. To this end, CD espouses &lt;a rel=&quot;external&quot; href=&quot;https://continuousdelivery.com/principles/&quot;&gt;5 principles&lt;/a&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Build quality in&lt;/li&gt;
&lt;li&gt;Work in small batches&lt;/li&gt;
&lt;li&gt;Computers perform repetitive tasks, people solve problems&lt;/li&gt;
&lt;li&gt;Relentlessly pursue continuous improvement&lt;/li&gt;
&lt;li&gt;Everyone is responsible&lt;/li&gt;
&lt;/ol&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;build-quality-in&quot;&gt;Build Quality In&lt;/h2&gt;
&lt;blockquote&gt;
&lt;p&gt;“Cease dependence on mass inspection to achieve quality. Improve the process and build quality into the product in the first place.” — W. Edwards Deming&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;It’s trite, pithy, and potentially problematic, but the best way to not deploy bugs is to not write bugs.&lt;/p&gt;
&lt;p&gt;“Don’t write bugs” is an oft spurned pipe dream. Perhaps for good reason—it can be interpreted in way that creates an unsafe work environment. Allowing ourselves to be human and accept mistakes is key to a healthy team. But also, &lt;em&gt;what if we could improve just one thing so we could introduce fewer bugs?&lt;/em&gt; If we kept improving just one thing continuously, could we approach “no bugs?” There may be some sort of asymptote as we approach 0, but the closer we get to 0, the safer the product—and our teams.&lt;/p&gt;
&lt;p&gt;We can approach the asymptote of 0 bugs by building quality into our software from the start. The start of what? The start of everything. This concept is referred to in many circles (like QA and Security) as &lt;em&gt;shifting left&lt;/em&gt;. I like to call it smooshing. We want to continuously look at our software development cycle and ask “how can we smoosh this together?” Smooshing together processes traditionally modeled as separate activities by methodologies like Waterfall is at the heart of Agile and Extreme Programming.&lt;/p&gt;
&lt;p&gt;What does this mean for your team? I don’t know. Ask them! Start the conversation on your team. This may mean realizing, “Oh, we didn’t even pull in QA or think about security in our feature planning.” Even further left: “We didn’t pull in QA or think about security before we prioritized this effort.” Smooshing may mean your team practices more pairing/mobbing (pair programming and pairing between other roles). It almost certainly will involve reshaping your delivery pipeline to include sufficient automated tests and security checks before allowing deployment to production.&lt;/p&gt;
&lt;p&gt;There is so much to think about around building quality in. There are books full of inspiration (and books full of traps). All I can say is: start the conversation with your team, and never stop it.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;work-in-small-batches&quot;&gt;Work in Small Batches&lt;/h2&gt;
&lt;p&gt;We’ve talked about the benefits of small batches as we’ve discussed &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/antifragile-continuous-integration&quot;&gt;Continuous Integration&lt;/a&gt;. One of the intangible benefits of CI is the way it starts to change how your brain thinks about problems—trying to break a problem down into small, individually deployable components.&lt;/p&gt;
&lt;p&gt;CI tackles how engineers focus on breaking down the implementation of the solution. We should seek small batches throughout all areas of our cross-functional software development cycle.&lt;/p&gt;
&lt;p&gt;Often I feel a tendency to resist small batches in favor of larger batches. Perhaps this is because many of us were taught (indoctrinated?) about the marvels of the Industrial Revolution in school (itself modeled after the Industrial Revolution in many ways). American education evangelizes the genius of Henry Ford and his army of specialized assembly line workers. We learn about economies of scale and the efficiencies they enable, horizontal and vertical integration, etc. The lesson often is that efficiency involves large batches of work and siloed, specialized roles. This is true, if you are trying to maximize for output. We do not want to maximize for output.&lt;/p&gt;
&lt;p&gt;In the latter part of the last century, Toyota began crushing American auto manufacturing. Many of their philosophies led to the craze of Lean Manufacturing. The methods move away from large batches towards a more made-to-order model. Large batches can incur waste of their own, and Lean Manufacturing is about cutting out waste. Toyota believed that the increased overhead of smaller batches was outweighed by the benefits and flexibility (agility) of a reduction in inventory. If you think about it, excess inventory in certain regards is a liability. It many ways it becomes negative optionality—my only option really is to try and sell it. If I develop a new product, I need get rid of my old inventory? If I need to make improvements, and I have a bunch of excess, that becomes expensive. This means lots of attempts at prediction so I don’t end up with too much or too little inventory.&lt;/p&gt;
&lt;p&gt;I’m obviously not a lean manufacturing/six-sigma expert (I read some wikipedia articles), but one of the holy grails is something called single-piece flow. Single-piece means that work is moved through the system without any in-between Work-In-Progress states. This concept of single-piece flow is also called one-piece flow, or &lt;em&gt;continuous flow&lt;/em&gt;. The ideal is for the work to move through the system without ever getting blocked. This includes quality assurance gates.&lt;/p&gt;
&lt;p&gt;Toyota instituted bizarre-seeming processes that fly in the face of our learned intuitions. One such example is the Andon Cord. The Andon cord is a physical cord that any employee is required to pull when they encounter a problem in the line. If a line manager cannot resolve the problem within a certain time frame (like a minute), the entire assembly line stops. Everyone then swarms on the problem until it solved.&lt;/p&gt;
&lt;p&gt;This sort of intense friction seems wasteful. The philosophy behind it is that the alternative—not immediately eliminating known problems from our process—is far more wasteful. You can see how tightly this blends into the first principle: Build quality in. All the principles are highly interconnected. The pain of stopping the world to fix a problem in the process is worth it if it can lead us closer to the world of continuous flow.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“If it hurts, do it more often.”&lt;br /&gt;
&lt;br /&gt;
— Martin Fowler, &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/bliki/FrequencyReducesDifficulty.html&quot;&gt;Frequency Reduces Difficulty&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;CD looks to optimize for the continuous flow of small batches of work from inception to deployment. We want to remove any human bottlenecks that are not problem-solving—anywhere work-in-progress can queue up.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;computers-perform-repetitive-tasks-people-solve-problems&quot;&gt;Computers perform repetitive tasks, people solve problems&lt;/h2&gt;
&lt;p&gt;Every time someone has to run a full end-to-end manual regression test you should collapse in tears. When a ‘feature team’ washes its hands and passes work off to an ops team to deploy, somewhere a fairy dies. ✨💀&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“If you are doing manual regression testing in 2013, all the computers are getting together and laughing at you. It’s 2013, we should not be doing this stuff manually anymore.”&lt;br /&gt;
&lt;br /&gt;
— Jez Humble, in his 2013 &lt;a rel=&quot;external&quot; href=&quot;https://www.youtube.com/watch?v=ZLBhVEo1OG4&quot;&gt;talk&lt;/a&gt; (still one of the best)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The real leverage of the Industrial Revolution was automation from machines—not humans. The real leverage of our current information age is automation by computers (computers are a very adaptable machine). Whenever we try to leverage humans like machines we burn them out. It’s inhumane, and it’s bad business. In the software industry we should hire humans and build teams for their creative problem solving potential.&lt;/p&gt;
&lt;p&gt;QA folks are incredible problem solvers, and widely known for their ability to push limits and discover new problems. We should push automated testing on our teams to free QA to do the types of testing only humans can do. Exploratory testing and representing user needs/pains are two uniquely human super powers.&lt;/p&gt;
&lt;p&gt;Ops teams are not FedEx for bits. Ops engineers are talented engineers who more likely than not love infrastructure. They should be equipped to be solving organizational infrastructure needs, not managing deployments.&lt;/p&gt;
&lt;p&gt;There are many examples in your org where humans could be freed by computers to accomplish creative, meaningful tasks. What are they?&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;relentlessly-pursue-continuous-improvement&quot;&gt;Relentlessly pursue continuous improvement&lt;/h2&gt;
&lt;p&gt;Continuous Delivery is not a checkbox on your list of things that “high-performing” software organizations do. Continuous Delivery is not an end; it is an infinite loop.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Continuous Delivery is a people, not a place.” — DevOps Heimdall&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There is no checklist of “do these things and now you are practicing CD.” CD is as an honest, ongoing conversation. The team should always be asking, “Where are we now? What’s our next step?” In this way, CD is a process that is able to respond to change: changes in the team, changes in tooling, changes in delivery needs. The infinite loop of CD is a feedback loop.&lt;/p&gt;
&lt;p&gt;Although we may map out our team processes in terms of simple diagrams (if we’re lucky), the real system is a complex, living thing. Systems thinking is hard.&lt;/p&gt;
&lt;p&gt;My lower back gets really tired when I deadlift. I used to think the reason was as simple as: I’m lifting poorly, or my back is weak. My coach helped me understand it may be both or neither of these things. It could be that my hamstrings are weak and I compensate with my back—another part of the system of the posterior chain. As my technique has improved we’ve slowly been leaning towards the weak-link hamstrings theory. It’s surprising, because my intuition was that if my hamstrings were weak, my hamstrings would have been sore.&lt;/p&gt;
&lt;p&gt;Our teams are complex living systems. We need to spend time observing as a team, and evolving together. We may feel pains in areas where it may be difficult to identify the root problem. “Fixing” a problem always puts us on a new plane with new problems to solve. If we are not continuously improving, we are continuously degrading thanks to entropy.&lt;/p&gt;
&lt;p&gt;Continuous Improvement is a key differentiating factor in a competitive business environment. Toyota practiced the Toyota Kata and did not worry too much about people stealing their process/plans—by the time someone would be able to copy it, Toyota had already learned and improved. They would always be ahead.&lt;/p&gt;
&lt;p&gt;CD is not a checklist of practices you can just read a book about or copy from someone else. Every team has to evolve to suit their own people and needs. You can delegate and copy many some things in life. You can not delegate your personal fitness or copy a world-class athlete’s workouts and expect results. Similarly, you have to build your own CD muscles through experience and team communication over time. There is no shortcut.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;everyone-is-responsible&quot;&gt;Everyone is responsible&lt;/h2&gt;
&lt;p&gt;Sure, perhaps some sort of an Engineering or Product Manager may ultimately be held accountable for business outcomes. An IC may be held accountable for individual efforts. But ultimately, the team is a team. The team must swim or sink together.&lt;/p&gt;
&lt;p&gt;“Failure” to deliver represents a learning opportunity for the whole team. What processes do we need to change next as part of our continuous improvement efforts to remove some risk of failure in the future?&lt;/p&gt;
&lt;p&gt;Everyone is responsible for the teams outcomes. Everyone should be invested, and empowered by a sense of team ownership.&lt;/p&gt;
&lt;p&gt;QA/Testers are not responsible for quality. Everyone is responsible for building quality in. Quality is a business decision—the business decides what level of defects are acceptable based on our customers and priorities.&lt;/p&gt;
&lt;p&gt;Everyone is responsible for UX. Although in current parlance, Designers are often ‘UX Designers,’ User Experience is broad and encompasses the entire experience of a user using the product. Load times that are too slow are bad UX. Bugs that result in data loss or confusion are bad UX.&lt;/p&gt;
&lt;p&gt;Everyone is responsible for the product. Engineers are not mere ticket-takers that turn caffeine into code. Engineers should ask product questions, champion for the user, good UX, and build quality in rather than throwing “dev-done” code over the wall to QA.&lt;/p&gt;
&lt;p&gt;Everyone is responsible for the code. Cross-functional as teams are, we need to understand that the code and infrastructure running in production are our product. Non-engineers should be invested in understanding “engineering” concerns and not feeling comfortable to just glaze over when things get technical. They should ask engineers challenging questions. Engineers should learn the language of the business and the product and &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/bliki/UbiquitousLanguage.html&quot;&gt;use these words&lt;/a&gt; in their communications and in the code base.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Continuous Delivery is about optimizing for the flow of work through our teams. The goal is not to optimize the productivity of each individual, it is to drive outcomes that will profit the business. CD is putting ourselves in a position where we can adapt quickly to deliver outcomes, rather than hamstring ourselves with an inventory of mere outputs. In order to drive outcomes, the whole team needs to focus on the principles of CD to create quick, healthy feedback loops.&lt;/p&gt;
&lt;p&gt;One way to make the feedback loops even quicker is to automatically deploy at the end of your deployment pipeline. This process is known as Continuous Deployment (often also abbreviated as CD and conflated with Continuous Delivery). Continuous Deployment is worthy of its own future article, but for now let it suffice to say: Continuous Delivery means &lt;em&gt;we can deploy every commit&lt;/em&gt;, Continuous Deployment means &lt;em&gt;we do deploy every commit automatically&lt;/em&gt;. You cannot have Continuous Deployment without Continuous Delivery.&lt;/p&gt;
&lt;p&gt;All of this starts with conversations, and must involve conversations forever. Modern software development is a team sport. There are no lone wolf code heroes in software development at meaningful scale. The most important thing your team can do is learn to talk.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>antifrAGILE: Continuous Integration</title>
        <published>2020-12-17T00:00:00+00:00</published>
        <updated>2020-12-17T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/antifragile-continuous-integration/"/>
        <id>https://jarsen.engineer/antifragile-continuous-integration/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/antifragile-continuous-integration/">&lt;h2 id=&quot;big-changes-are-fragile&quot;&gt;Big Changes Are Fragile&lt;/h2&gt;
&lt;p&gt;Big changes carry more risk than small changes.&lt;/p&gt;
&lt;p&gt;Ambitious, “big bang” style changes often fail, or generate more organizational ill-will than they do business value. There’s a reason just whispering the word refactor can send a Product Manager into a fugue state.&lt;/p&gt;
&lt;p&gt;Merging and deploying months worth of work is much riskier than merging in a days worth; a 5 line PR is less risky than a 500 line PR.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/i/web/status/1332679390212263945&quot;&gt;Referenced post on X&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Does that mean that a bad 5 line PR can’t do more damage than a 500 line one? Of course not. But the human brain is much better at handling small changes—at being able to contextualize and model one thing at a time.&lt;/p&gt;
&lt;p&gt;We just understand small changes better. This is why software teams are incredibly intuitive and accurate when estimating in the short term, and terrible with anything more than a week or two out.&lt;/p&gt;
&lt;p&gt;Dealing with large and/or long term changes is more fragile, because it involves more prediction. Prediction is fragile. Prediction tries to deal in the probability of a particular outcome, and can never account for Black Swan events swimming in the tails of the bell curve. Hell, it doesn’t even take Black Swans, just sustained mild volatility will break many predictive models.&lt;/p&gt;
&lt;p&gt;Antifragility views prediction as a distraction at best, and instead focuses on building options so that no matter what, you have good choices.&lt;/p&gt;
&lt;p&gt;By focusing on making our changes small, we become antifrAGILE, and able to change quickly.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;continuous-integration&quot;&gt;Continuous Integration&lt;/h2&gt;
&lt;p&gt;Continuous Integration (CI) is a practice to reduce risk by making changes small and continuous.&lt;/p&gt;
&lt;p&gt;CI is a practice first introduced by Extreme Programming. Over the past decade, the term CI has begun to be misused to refer to build servers and services that form an important part of CI. But &lt;strong&gt;CI is not something you can buy, CI is a practice you must develop.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;What does it mean to “integrate?” Integrate means integrate your work with the work of everyone else on your team. Continuous means, in this context, frequent. You must be merging everyone’s code frequently.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The Extreme Programming practice of Continuous Integration encourages all members of a development team to integrate their work daily, instead of developing features in isolation for days or weeks.” — Martin Fowler&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Jez Humble, author and influential member of the DevOps movement, likes to ask folks who believe they are doing CI three questions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Does every developer check their work into the main branch (master, trunk, etc.) at least once a day?&lt;/li&gt;
&lt;li&gt;Does every checkin to the main branch result in an automated build and test?&lt;/li&gt;
&lt;li&gt;If the build fails, is it back to green within 10 minutes?&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If you cannot answer yes to all of these questions, you are not practicing Continuous Integration (even if you own a CircleCI license and you run all your integration tests on every commit to your feature branch 😢).¹&lt;/p&gt;
&lt;h2 id=&quot;sounds-wild&quot;&gt;Sounds Wild.&lt;/h2&gt;
&lt;p&gt;If you’re like me a year and a half ago, this revelation feels radical—wrong somehow. Merge conflicts are awful, I’d like to deal with that less, so I’ll wait longer to merge, thank you very much. Also, how can I just merge into main? What about my bugs?! Where does QA fit in? What if it’s not done?&lt;/p&gt;
&lt;p&gt;The intuition is that merging daily will lead to smaller, but more frequent merge conflicts, resulting in the same amount of work—just perhaps distributed into more manageable amounts. The reality is that the relationship here is non-linear. Volatility, randomness, time, chaos, change—they all compound. Counterintuitively, more frequent integration will result in not only smaller merge conflicts, but also fewer merge conflicts.&lt;/p&gt;
&lt;p&gt;One of Martin Fowler’s favorite phrases is “If it hurts, do it more often.” He gives three reasons to do it more often: First, many tasks become more difficult to do as the amount of work to do increases. Second, we need feedback. We cannot receive feedback if we are not doing the thing. Third, we need practice. Often practice will refine our process and help us really understand.&lt;/p&gt;
&lt;h2 id=&quot;an-attempt-at-analogy&quot;&gt;An attempt at analogy.&lt;/h2&gt;
&lt;p&gt;Imagine you need to collaborate on a presentation. The most frustrating way to do this is to set up an email chain where everyone keeps emailing new versions of the document and you need to integrate everyone else’s changes while also incorporating your own.&lt;/p&gt;
&lt;p&gt;The simplest and most collaborative way for me to do this is use a Google Doc where I can see everyone editing in real time. I rarely have conflicts, and if I do I know before I make the changes and I am communicating with someone who recently made the conflicting change. This conflict is a conceptual conflict—a departure in ideas or direction—not an editing conflict. The live nature of the document has helped bring the conflict to the forefront where we can discuss it before moving on.&lt;/p&gt;
&lt;p&gt;The more continuously you integrate, the more you are turning your main branch into a Google Doc.&lt;/p&gt;
&lt;h2 id=&quot;scale&quot;&gt;Scale&lt;/h2&gt;
&lt;p&gt;“Ok, Jason. But I work at X Big-Co. Maybe that works for small teams, but we have 1000 engineers. We can’t all be editing the same Google Doc at the same time!”&lt;/p&gt;
&lt;p&gt;Honestly, I haven’t experienced CI at this scale. But as I understand, Google, Facebook, and many very large codebases work this way. It takes some more tooling, but also… can you imagine the massive game of car-chicken over merging pull-requests between 1000 engineers? Hopefully at this point you have developed some good boundaries if you are still developing in a monorepo.&lt;/p&gt;
&lt;p&gt;Fast Feedback Loops&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/i/web/status/1338898497634848773&quot;&gt;Referenced post on X&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;(Don’t get me started on how rad darklang is philosophically. A newsletter for another time.)&lt;/p&gt;
&lt;p&gt;One of the keys to any successful agile practice is feedback loops. How you you know when to zig if you aren’t paying attention, let alone zag?&lt;/p&gt;
&lt;p&gt;Feature Branches receive certain types of feedback. Perhaps there was already feedback collected by UX research before implementation even began. Perhaps I got a code review at the end—or even review or a pair of eyes along the way. This is all great feedback. But one very important bit of feedback is missing: does it blend?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Until I’ve integrated my code with the work that everyone else is doing, I don’t know if my code works.&lt;/strong&gt; My code might work perfectly and pass QA on my feature branch, but I have no clue how it will interact one I merge with trunk, let alone the feature branches of my colleagues.² (Does your QA vet the merged artifact?!)&lt;/p&gt;
&lt;p&gt;Or perhaps, like in the Google Doc analogy, there’s been an important misalignment in direction or intent of an interface or service, and we’ve spent weeks or worse pulling in different directions. Integrating early and frequently provides feedback that brings these conceptual conflicts to the surface sooner.&lt;/p&gt;
&lt;p&gt;Finally, forcing ourselves to start to think small leads to smaller experiments. As Charity pointed out in her tweet: we shrink the lead time to get something into product to be so quick that we can go from idea, to implementation, to running in production and observing the results of our product hypothesis in no time.&lt;/p&gt;
&lt;h2 id=&quot;continuous-integration-is-for-teams&quot;&gt;Continuous Integration Is For Teams&lt;/h2&gt;
&lt;p&gt;It may go without saying, but Continuous Integration is probably not a very useful idea for solo development—there aren’t many things to integrate with.&lt;/p&gt;
&lt;p&gt;But what this means it that CI is a practice specifically designed for teams.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/i/web/status/1335595612159553537&quot;&gt;Referenced post on X&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;(Trunk Based Development is a key requirement for CI)&lt;/p&gt;
&lt;p&gt;It feels pretty smooth to throw on a headset and go heads-down for a week after Monday planning meetings, surfacing here and there for a morning standup. You knock out your tickets, pat yourself on the back, and throw it over the wall for QA to test in some sort of temporary staging environment. You pick up your next story, only to be interrupted by QA when it’s approved and you’re ready to merge. Hopefully there’s no merge conflicts. Or oops, QA found a bug and now you gotta context switch back to where you were a week ago. Either way, minor inconvenience for you.&lt;/p&gt;
&lt;p&gt;Now multiply this by the number of people on your team/in your code base. The cost is worse than that, because again with volatility, the response is non-linear. We want practices that optimize for the flow of the product, not for individual productivity. (Optimization for individual flow is one reason Cal Newport has declared the &lt;a rel=&quot;external&quot; href=&quot;https://www.newyorker.com/tech/annals-of-technology/the-rise-and-fall-of-getting-things-done&quot;&gt;fall of GTD&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;One teamwork analogy I heard growing up was about yokes and oxen. Imagine a covered Conestoga wagon being pulled by two oxen. Those oxen probably are not the same strength—it’s very likely that one could be pulling faster. But it couldn’t be pulling more without its partner. Even though the yoke slows down one of the oxen, they can pull more together.&lt;/p&gt;
&lt;p&gt;Teams are the same way. You may be a “rock star”/ninja programmer and you can code way faster on a feature branch and if you merge first maybe you avoid conflicts. But you can’t out-code your whole team. Continuous Integration optimizes for team flow.&lt;/p&gt;
&lt;h2 id=&quot;i-m-still-worried-about-quality&quot;&gt;I’m Still Worried About Quality&lt;/h2&gt;
&lt;p&gt;One of the big concerns with most folks learning about the Truth of Continuous Integration is quality. This is good. This means you are a good engineer—you want to deliver quality software that your customers want to pay for.&lt;/p&gt;
&lt;p&gt;The concern is that Continuous Integration bypasses many of the common quality assurance steps we may be used to. If we are all merging daily into trunk, how do we make sure we have something reliable to deploy?&lt;/p&gt;
&lt;p&gt;Remember that one of the three keys of practicing CI is that every commit to the trunk triggers an automated build and test. Your automated tests should be a good signal that your existing features are working as intended.&lt;/p&gt;
&lt;p&gt;But even with tests, there are some things that having passing tests, but are not done. They are not ready to be released! And if everyone is doing this all the time, how do we ever end up with an artifact that we can release? A code freeze??&lt;/p&gt;
&lt;p&gt;Alas, it is 11PM the night before the Thursday morning this newsletter will go out and it is past my bedtime. This got a lot longer than I expected. I was hoping to get into the next topic to answer this question, but it will have to wait! I will give you a hint though, it starts with Continuous and ends with elivery.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;resources&quot;&gt;Resources:&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;This is a very good &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/articles/continuousIntegration.html&quot;&gt;guide&lt;/a&gt; to read about Continuous Integration. You might notice I keep referencing Martin Fowler. Sorry, but he writes a lot of good stuff.&lt;/li&gt;
&lt;li&gt;If you want to get deep into the patterns for branching, read &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/articles/branching-patterns.html&quot;&gt;Patterns for Managing Source Code Branches&lt;/a&gt; by… Martin Fowler. 😅&lt;/li&gt;
&lt;li&gt;Read XP Explained, by Kent Beck.&lt;/li&gt;
&lt;li&gt;I wrote a little bit about CI earlier this year on my &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/ship-faster-with-this-one-weird-trick&quot;&gt;blog&lt;/a&gt;. There’s some other inspiring quotes and stuff there.&lt;/li&gt;
&lt;/ol&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>antifrAGILE: Software Teams</title>
        <published>2020-12-10T00:00:00+00:00</published>
        <updated>2020-12-10T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/antifragile-software-teams/"/>
        <id>https://jarsen.engineer/antifragile-software-teams/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/antifragile-software-teams/">&lt;p&gt;A Black Swan is an unpredictable event—a massive shock to our systems.&lt;/p&gt;
&lt;p&gt;Things that are fragile do not like change. Change hurts. Chaos, volatility, randomness, entropy, the unknown, time—all involve friction and forces that pull at the seams, threatening to destroy the fragile. Sometimes the destruction is abrupt and impossible to predict (what Taleb calls a Black Swan). Sometimes its death by a thousand cuts.&lt;/p&gt;
&lt;p&gt;When we think of things that are not fragile, we tend to think of things that are robust and resilient. Robust things are not affected negatively by change. They yawn as the tides of chaos break on their shores, and shrug as they recede.&lt;/p&gt;
&lt;p&gt;However, robust things are also not affected by change positively. In their apathy towards the waves of volatility, they fail to recognize and take advantage of opportunities as they briefly flit in and out of the unknown.&lt;/p&gt;
&lt;p&gt;Antifragile things are affected by change positively. They clap their hands giddily as they watch the ebb and flow. Their systems are designed to profit from the waves. They evolve and become stronger.⁰&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“The only constant in life is change.” – Heraclitus&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The market is a realm of exceptional volatility. The needs and wants of customers evolve rapidly. Competitors surprise us. Teams shift. Technology constantly changes, and innovation accelerates the rate of future change.&lt;/p&gt;
&lt;p&gt;This is not new. We’ve known this for a long time. In software development, the Agile movement began as attempt to position teams and businesses so they could &lt;em&gt;respond quickly to change&lt;/em&gt;. Sometimes we mistake agility for speed or velocity. Agility is the ability to quickly change direction while moving—not the ability to sprint as quickly as possible from A to B. Agile is about fast feedback loops and iteration while continuously delivering value.&lt;/p&gt;
&lt;p&gt;The Heraclitus quote may be a cliche, but we often still don’t get it. We cannot avoid volatility, so we must learn to embrace it. We should focus on investing our time and energy in building antifragile systems so that we can thrive in a world of unknowns.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;optionality&quot;&gt;Optionality&lt;/h2&gt;
&lt;p&gt;We take advantage of volatility and build antifragile systems by collecting options.&lt;/p&gt;
&lt;p&gt;In his book, &lt;a rel=&quot;external&quot; href=&quot;https://thedeepdish.org/optionality-book/&quot;&gt;Optionality&lt;/a&gt;, Richard Meadows defines an option as &lt;strong&gt;the right, but not the obligation, to take a given action&lt;/strong&gt;. By collecting options, we position ourselves to expose opportunities from volatility, and even to pivot and ride the wave created by a Black Swan.&lt;/p&gt;
&lt;p&gt;Not all options are worth collecting. We want to prioritize options that have limited downside, but unlimited potential for upsides. This &lt;em&gt;positive asymmetry&lt;/em&gt; is the key attribute we’re looking for as we build. Building something that could have multiple uses, but is easy to maintain is something that gives us options. Delivering the simplest possible solution for our users’ hardest problem limits the potential downside for wasting time with a solution that won’t fulfill user needs, but has the massive potential upside that it will solve the problem enough to generate massive value and feedback that leads to more value.&lt;/p&gt;
&lt;p&gt;There is also such thing as too many options—&lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/let-constraints-set-you-free&quot;&gt;constraints can create more freedom&lt;/a&gt;. At some point you need to exercise options, you cannot explore and collect indefinitely. Options go stale or rot. We may dive deeper into theories and nuances of which options to collect and exercise in a future article, but for now if you can’t wait you can start with &lt;a rel=&quot;external&quot; href=&quot;https://medium.com/@kentbeck_7670/decisions-decisions-or-why-baskets-of-options-dominate-9ac63658b593&quot;&gt;Decisions, Decisions or Why Baskets of Options Dominate&lt;/a&gt; by Kent Beck (or read Antifragile by Taleb or Optionality by Meadows).&lt;/p&gt;
&lt;p&gt;We want to avoid making decisions that have negative optionality. Examples of these can include &lt;a rel=&quot;external&quot; href=&quot;https://m.signalvnoise.com/options-not-roadmaps/&quot;&gt;roadmaps&lt;/a&gt; and client commitments. If we are not careful, we end up in the build trap. Rigid roadmaps and commitments give us the obligation, but not the right, to take an action. This “&lt;a rel=&quot;external&quot; href=&quot;https://melissaperri.com/book&quot;&gt;build trap&lt;/a&gt;” has serious ramifications in terms of opportunity cost: it leaves us shackled and unable take (or perhaps even see) better options as they arise.&lt;/p&gt;
&lt;p&gt;In sum, we want to grow our systems so that as randomness and Black Swans happen, we have valuable options. Maybe that Black Swan is a 0-day vuln, a competitor move, or your app getting &lt;a rel=&quot;external&quot; href=&quot;https://www.howtogeek.com/297651/what-does-it-mean-when-a-company-sherlocks-an-app/&quot;&gt;sherlocked&lt;/a&gt;. Do you have options to respond that can turn it into a positive? Or maybe the Black Swan is your app going viral on ProductHunt, a call from an investor, or a competitor failing opening up a huge opportunity. Do you have options available to take advantage of? We can’t possibly prepare for every Black Swan—they are, by definition, unpredictable—but we can gather options so we have the best chance possible.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;frameworks-for-antifragility&quot;&gt;Frameworks for Antifragility&lt;/h2&gt;
&lt;p&gt;We know what antifragility is and hopefully we can agree that it is desirable. We know we need optionality in order to take advantage of volatility. So, how do we build optionality in our software and software organizations?&lt;/p&gt;
&lt;p&gt;Fortunately, we are not the first people to realize options are good. People have intuitively been building antifragile systems since the dawn of humankind, without a word or perhaps even concept for antifragility. In the last decades, we have seen formalized business frameworks and mental models arise including the Lean Manufacturing, Toyota Kata, Agile, and DevOps movements. By studying these methodologies, and applying principles and practices in the name of antifragility, we can build a system to profit from chaos.&lt;/p&gt;
&lt;p&gt;One of my favorites is Extreme Programming. The canonical Extreme Programming Explained has antifragility right on the cover in the subtitle: “Embrace Change.” XP loves change. There’s so much to love about XP’s values, principles, and practices… Chef’s kiss. However, Extreme Programming has one achilles heel: its name.&lt;/p&gt;
&lt;p&gt;The name “Extreme Programming” I think ultimately detracts from the framework. The “Programming” bit distracts from the reality that it is not a framework about programming! It is much broader than just writing code and is about building products and teams. And though I like personally like it because it sounds kinda metal, “Extreme” is probably not that attractive, even if you understand the context.&lt;/p&gt;
&lt;p&gt;But if we can get over that hump, the principles and practices are all explicitly designed to optimize teams to thrive in chaotic environments.&lt;/p&gt;
&lt;p&gt;Continuous Delivery is another framework for building antifragility. In fact, one of the first places I ever saw the the term “antifragility” was right on Jez Humble’s &lt;a rel=&quot;external&quot; href=&quot;https://continuousdelivery.com/2013/01/on-antifragility-in-systems-and-organizational-architecture/&quot;&gt;marketing site for his book&lt;/a&gt;.¹&lt;/p&gt;
&lt;p&gt;I’m no DevOps history expert, but it seems like a lot of the folks writing the books came right out of the Continuous Delivery group, and I tend to think of it as an evolution of Continuous Delivery (I see a lot of XP influences in DevOps as well).&lt;/p&gt;
&lt;p&gt;One of the easiest ways to build optionality is to read and to study. It’s an activity that has limited downsides, but potential for unbounded upsides. Over the this series of articles, I want to explore and study together what I see as the most impactful values, practices, and principles of these frameworks. By doing this we begin to fill out our toolbox, storing away options for ourselves and our teams, so that as opportunities for continuous improvement arise, we see opportunities and are able to capitalize. Join me next week (oops a commitment) as we dive into one of my favorite practices: Continuous Integration.&lt;/p&gt;
&lt;hr /&gt;
&lt;ol start=&quot;0&quot;&gt;
&lt;li&gt;One of my favorite examples from Antifragile was the example of receiving a package in the mail that says “FRAGILE” (Italian leg lamp??). You know that package doesn’t want to be shaken, thrown, or dropped. Imagine receiving a package that says “ANTIFRAGILE.” This package contains something that wants to be shaken. The example that stuck out to me the most to compare robust with antifragile is the Phoenix vs. Hydra. Chop off the Phoenixes head and it is reborn from its ashes. Chop off a head of the hydra and it grows 3 more in its place.&lt;/li&gt;
&lt;li&gt;And now that I reread Jez Humble’s page I’m realizing he makes the Embrace Change connection. I totally thought that I came up with that while reading Antifragile months later… but maybe it was incepted there all along. I just wasn’t ready yet.&lt;/li&gt;
&lt;/ol&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Let Constraints Set You Free</title>
        <published>2020-06-18T00:00:00+00:00</published>
        <updated>2020-06-18T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/let-constraints-set-you-free/"/>
        <id>https://jarsen.engineer/let-constraints-set-you-free/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/let-constraints-set-you-free/">&lt;p&gt;This morning I rested my chin on the sill of the open window as I showered. The lights were off and the only illumination came from the soft warm glow of the early sun rising over the distant mountains, filtered through the trees. Gazing aimlessly into the backyard through the steam, I wondered, as I have for months, is this the right thing to do?&lt;/p&gt;
&lt;p&gt;I closed my eyes and let the hot water rush over me. I breathed deep to inhale the crisp morning air, still humid from a night of warm summer thunderstorms. Taking in the smell of the damp trees and earth, I held my breath as long as I could, knowing that I could never have that exact moment again. Then I exhaled.&lt;/p&gt;
&lt;p&gt;Tomorrow we are listing our home for sale. Yes, &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/castles-of-abstraction&quot;&gt;the one that has dirt under it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Our home was built in 1931 and has “character.” I love that character, even if said character sometimes means costly maintenance. I love the giant, old trees that line our neighborhood. I love the smell of them, even if my sinuses do not agree with their pollens. I love the experiences we’ve had here, in our first home. I love that my home is a duplex: we have had some fun experiences as Airbnb hosts, with guests from all over the world staying next door.&lt;/p&gt;
&lt;p&gt;A thing about old homes—well, probably all homes, but especially old homes—is that they come with an endless list of projects.&lt;/p&gt;
&lt;p&gt;Monday night, as my wife and I sat exhausted on the floor, we surveyed all the things we (with the help of our amazing neighbor) had accomplished that day. I was overwhelmed by strange, difficult competing emotions… Regret? Relief? Frustration? Peace? Loss? Freedom? In a single day, we knocked years worth of items from our endless todo list. But now we were enjoying them on borrowed time.&lt;/p&gt;
&lt;p&gt;We didn’t have to spend four years with wires sticking out of the hole in the wall where the old thermostat was. All we needed was 15 minutes of focus.&lt;/p&gt;
&lt;p&gt;The time pressures of the impending sale gave us the constraints we needed to focus on the problem. It was the constraints that set us free from our procrastination.&lt;/p&gt;
&lt;p&gt;It feels counter-intuitive that the things that limit our options can give us more freedom.&lt;/p&gt;
&lt;p&gt;The constraint of 140 characters pushed us to communicate in new, creative ways. I think it made some of us better writers.&lt;/p&gt;
&lt;p&gt;The constraints of an opinionated framework like Ruby on Rails are frustrating to those who like to build their whole web stack from scratch and have control over every layer. But, viewed another way, the constraints let you focus on other important problems—focusing on the core competencies of the business.&lt;/p&gt;
&lt;p&gt;Most of us are familiar with the paradox of staring numbly at infinity movies and TV shows on Netflix and finally shutting the Apple TV off because we couldn’t find a single thing to watch. Yet children immediately know exactly which two movies they want to watch every single time. (I recently watched The Black Cauldron on Disney+ and was stunned by how many things I could quote, despite not having watched the movie in over 20 years.)&lt;/p&gt;
&lt;p&gt;I’m really bad at science, but I think there are some parallels. In &lt;a rel=&quot;external&quot; href=&quot;https://www.youtube.com/watch?v=fJefjG3xhW0&quot;&gt;fluid dynamics&lt;/a&gt;, as fluid begins to travel through a narrow space it goes faster. If you focus light through a magnifying glass, it gets real strong and can burn stuff. There is probably other science stuff to be said here, but let’s just say: Our attention is a form of energy that goes faster and burns leaves when focused.&lt;/p&gt;
&lt;p&gt;Find constraints that motivate you to create, and to focus on the things that matter. Don’t let yourself live in a home you love for four years with wires sticking out of the wall.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Finding Peace in a World of Unknowns</title>
        <published>2020-06-10T00:00:00+00:00</published>
        <updated>2020-06-10T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/finding-peace-in-a-world-of-unknowns/"/>
        <id>https://jarsen.engineer/finding-peace-in-a-world-of-unknowns/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/finding-peace-in-a-world-of-unknowns/">&lt;p&gt;I’ve been thinking a lot about change of late.&lt;/p&gt;
&lt;p&gt;At work, I’m always thinking about change: how to communicate about changes, how to plan changes, and how to implement change.&lt;/p&gt;
&lt;p&gt;The last few years for me have been a fraught with major personal life changes.&lt;/p&gt;
&lt;p&gt;Socially… Well, it feels like it’s been a long, downward spiral (since 2016?), picking up momentum at a dizzying pace.&lt;/p&gt;
&lt;p&gt;And finally, the events of this year—and in particular the events of the past few weeks—have me staring blankly at the wall.&lt;/p&gt;
&lt;p&gt;After all this, I’m left asking: How can I create lasting change in a world that is constantly changing? How can we live—and find peace—in a world of imperfect knowledge? A world of imperfect systems? A world of imperfect people?&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“I want to live happily in a world I don’t understand.”&lt;br /&gt;
&lt;br /&gt;
— Nassim Nicholas Taleb, Antifragile&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Antifragile is a thought provoking book by Nassim Nicholas Taleb.&lt;/p&gt;
&lt;p&gt;What is fragility? Something is fragile if it is averse to change. See a giant red FRAGILE sticker on a package? Don’t shake it; it doesn’t like it. Did you lose your life savings investing in Beanie Babies? That was a fragile investment. Does your team keep getting paged at 2AM to deal with issues in production? That’s a fragile system. Do we have to periodically bail out the same organizations that are “too big to fail?” That’s a fragile system.&lt;/p&gt;
&lt;p&gt;What is the opposite of fragility? Most of us, without reading Antifragile, would respond with words like robust, or resilient. Robust packages, investments, and systems are not harmed by change.&lt;/p&gt;
&lt;p&gt;But wouldn’t the opposite of something that is harmed by change be something that benefits from change? Lacking a proper word for that, Taleb proposes antifragility. Something is antifragile if benefited by chaos, disorder, and randomness.&lt;/p&gt;
&lt;p&gt;A phoenix is to robustness as a hydra is to antifragility. When a phoenix falls it rises from the ashes as if nothing happened; when you chop off the head of a hydra it becomes stronger than ever.&lt;/p&gt;
&lt;p&gt;I won’t attempt to rehash the book—I’d do it injustice and I am not finished reading yet. But my takeaway so far is this: the key to peace in a world of unknowns is to build something that is antifragile.&lt;/p&gt;
&lt;p&gt;You want to become a person that grows from experience; don’t be the helicopter-parent that overprotects their child. Make diverse investments that limit your risk and give you lots of room for growth. Be a team that learns and grows from its mistakes. Build systems and governments that support people without becoming helicopter-parents for “job creators.”&lt;/p&gt;
&lt;p&gt;Antifragility is recognition that attempting to predict the future is dangerous and futile. Antifragility is building things that get stronger under pressure. We want to live in a system where we look forward to failure and stressors, as they are stepping stones to greater things.&lt;/p&gt;
&lt;p&gt;In the sentence immediately preceding the quote about living happily in a world of unknowns, Taleb says something else profound:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“The chief ethical rule is the following: Thou shalt not have antifragility at the expense of the fragility of others.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;To me, this is becoming a unifying theory that describes the things I feel are most wrong with our society.&lt;/p&gt;
&lt;p&gt;Many of the richest among us—and health insurance companies!—have grown richer than ever during an international pandemic and economic crisis. This is antifragility.&lt;/p&gt;
&lt;p&gt;Law enforcement agencies have been strengthened, militarized, and receive astronomical budgets boosts over the past decades in spite of increasing allegations, protests, and lawsuits. A clear antifragile system. (Meanwhile other public services are gasping for air and teachers are forced to buy school supplies so their students can learn.)&lt;/p&gt;
&lt;p&gt;America has been built on the backs of slaves working land looted from the native population. America has prospered through wars that revived the economy, and made private contractors rich. Corporations take without reservation from the earth, and our society returns islands of plastic to the sea.&lt;/p&gt;
&lt;p&gt;A common theme here is this: systems designed by the rich and powerful (and overwhelmingly white) to strengthen their riches and powers—to build fortunes and legacies that continue to grow even during times of duress.&lt;/p&gt;
&lt;p&gt;All of this at the expense of the most vulnerable.&lt;/p&gt;
&lt;p&gt;I don’t have the answers, but we must change. We have to shake these systems and show that antifragility built upon the fragility of others cannot stand.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Castles of Abstraction</title>
        <published>2020-05-28T00:00:00+00:00</published>
        <updated>2020-05-28T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/castles-of-abstraction/"/>
        <id>https://jarsen.engineer/castles-of-abstraction/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/castles-of-abstraction/">&lt;p&gt;A few months ago I had a moment of existential crisis.&lt;/p&gt;
&lt;p&gt;We were remodeling our basement bathroom and wanted the toilet moved. The contractors came, jackhammered the cement, and laid new pipes. I got home from work and wanted to see the progress, so I poked my head in and saw… dirt.&lt;/p&gt;
&lt;p&gt;There was dirt under my house.&lt;/p&gt;
&lt;p&gt;I closed the door slowly and backed away.&lt;/p&gt;
&lt;p&gt;My house is just a fancy hut.&lt;/p&gt;
&lt;p&gt;Don’t get me wrong—I am so privileged to have a nice, safe home. But when I say it’s a fancy hut, I mean it’s not magic: it’s some cement in the ground with some brick, cinderblock, and wood on top.&lt;/p&gt;
&lt;p&gt;Sometimes we get extra fancy. We shove stuff in the walls for extra insulation. We pipe water in and out. We hide wires in the walls so we don’t have to see them (so unsightly). Indoor plumbing, which I accept daily as basic fact of life, was not commonplace even in the U.S. &lt;a rel=&quot;external&quot; href=&quot;https://www.aceee.org/files/proceedings/2004/data/papers/SS04_Panel1_Paper17.pdf&quot;&gt;as recent as 80 years ago&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;My first reaction at seeing the dirt was surprise—I had never really thought about it much. My second reaction was a wave of shame. Of course there was dirt under my house, what else could there be? I felt like a fool, blinded by a privileged life of playing with computers all day for money.&lt;/p&gt;
&lt;p&gt;I forgot there was dirt under my house.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;I think everyone is capable of understanding anything about computers, but no one is capable of understanding everything.&lt;/p&gt;
&lt;p&gt;Computers are complex. We can’t possibly hold all computerdom in our head at once—our brains would ’splode. So, we necessarily establish boundaries and dig foundations for castles of abstraction.&lt;/p&gt;
&lt;p&gt;Every day we work hard in our hyper-dimensional castles, and every day the castles expand in new, M.C. Escher-esque ways. Yet we walk their familiar halls with increasing confidence, because we too grow with the castle.&lt;/p&gt;
&lt;p&gt;The deeper and more comfortable we are within the walls of abstraction, the easier it is to lose touch with reality.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“The programmer, like the poet, works only slightly removed from pure thought-stuff. [They build] castles in the air, from air, creating by exertion of the imagination…”&lt;br /&gt;
&lt;br /&gt;
— Fred Brooks&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Code is a castle of abstraction in which we can live. It’s easy to get lost and forget code is not the only thing that builds software.&lt;/p&gt;
&lt;p&gt;Many of us frequently live in Kanban boards or other project management tools. Tools and processes are also abstractions we use to build software.&lt;/p&gt;
&lt;p&gt;Then there are even more abstract castles, like culture and teams. They’re sort of like abstract distributed meta-castles. They’re way harder to understand and build than code, but even more critical than code or tools to create good software.&lt;/p&gt;
&lt;p&gt;The Fred Brooks quote goes on:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“…Yet the program construct, unlike the poet’s words, is real in the sense that it moves and works, producing visible outputs separately from the construct itself. It prints results, draws pictures, produces sounds, moves arms. The magic of myth and legend has come true in our time. One types the correct incantation on a keyboard, and a display screen comes to life, showing things that never were nor could be.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Any sufficiently advanced technology is indistinguishable from magic… if you don’t look behind the curtain. When you open the bathroom door and look: it’s just a fancy hut. We forget there is dirt under the castle floor.&lt;/p&gt;
&lt;p&gt;Software is a story of humans. Software is built by humans, for humans. The magic of the display coming to life is not a miracle of science; it is a triumph of the human imagination. Code is code. Silicon is silicon. Electricity is electricity.&lt;/p&gt;
&lt;p&gt;On and off, ones and zeros, pixels on a display—these have no inherent meaning. It’s humans that craft meaning from nothing, hoping that other humans too will find their work meaningful.&lt;/p&gt;
&lt;p&gt;Our choices about what tech stack, processes, or project management software to use—all of it—are secondary to the humanity of software development.&lt;/p&gt;
&lt;p&gt;The Agile manifesto, a document which spawned countless software development methodologies, starts with this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:&lt;br /&gt;
&lt;br /&gt;
Individuals and interactions over processes and tools&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Software is built by humans, for humans. Let’s never get so lost in the constructs of our mind that we forget.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Software is Made by Humans. Part I.</title>
        <published>2020-02-22T00:00:00+00:00</published>
        <updated>2020-02-22T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/software-is-made-by-humans-part-i/"/>
        <id>https://jarsen.engineer/software-is-made-by-humans-part-i/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/software-is-made-by-humans-part-i/">&lt;p&gt;The reason I got into programming as a teenager was because of video games.&lt;/p&gt;
&lt;p&gt;I mean, I always liked computers generally–I was fortunate to grow up in the Cupertino area, and my dad was a software developer who would build random computers for my brother and I out of old hardware from work–but it was really video games that got me excited about computers.&lt;/p&gt;
&lt;p&gt;In particular I loved Blizzard games: I remember begging for the Warcraft II Battlechest at Costco, Starcraft, Diablo II (which I was not “allowed” to play so played at friends’ houses). These were all games that I spent many of my waking hours obsessing over. When I would hit my limit for hours I was allowed to spend on the computer, I would pull out the manuals and read them over and over, trying to understand the mechanics and analyzing the rules systems, copying the art in notebooks, and imagining playing and making my own games.&lt;/p&gt;
&lt;p&gt;In middle school a group of my friends made a website for their Diablo II clan, and it was &lt;em&gt;rad&lt;/em&gt;. It had all these cool dropdowns, little animations and dynamic widgets, persistence, authentication… I asked them how they made it and they were like “wouldn’t you like to know.” I had done some HTML, but didn’t know about Javascript or any backends or databases. This exclusion from some secret knowledge, in tandem with the announcement of Warcraft III¹, drove me to ask my dad for some help. My dad responded by printing out a stack of pages for a PHP tutorial from the PHP DevShed forums (I didn’t have internet access on my computer). He had a very throw you in deep end of the pool and let you drown for a bit style of teaching.² This was my introduction to “real” programming.&lt;/p&gt;
&lt;p&gt;Growing up in Silicon Valley I learned all about certain software legends, and slowly an image formed in my mind of what it meant to be a great developer: you were sort of an opinionated mad “genius” and you would do things like write your own operating system, programming language, version control system, etc., in a few days of caffeine driven rage.³ Then people would praise you for being so smart and you would get to tell people how to pronounce the name of the thing you made.⁴&lt;/p&gt;
&lt;p&gt;Almost 2 decades since I decided I wanted to make video games when I grew up… where are all the video games I wanted to make? 👀&lt;/p&gt;
&lt;p&gt;Turns out making games by yourself is hard. I didn’t know that I needed so many skills to make cool art, models, rigging… Not to mention the game design, the graphics programming, the music. There is a lot more to making the kind of game I want than one person can handle. That truth holds for more than just game development: it is the truth of most all software development.⁵&lt;/p&gt;
&lt;p&gt;My teenaged mental model–the lone wolf code hero unix hacker chugging Code Red and eating pizza by the light of their dark themed text editor and listening to some sweet beats uninterrupted in their audiophile headgear–was wrong.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;And that long winded intro brings me to my theme.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you believe that taking time to think before writing code is unproductive?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you believe that teaching, learning and elevating those around us is a waste of time?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you believe that you can make better software by routinely burning the midnight oil?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you believe that sacrificing a healthy life and balance will make your software better?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Do you think that if everyone just left you alone in “the zone” to hack that you would make a great product?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I see lots of conversations around these questions, and others like it. And it seems that the majority (at least in my circles) would answer with a resounding “no” to all of the above questions.&lt;/p&gt;
&lt;p&gt;I think most of us agree: software is a collaborative effort, and we can build better software together. We agree that &lt;em&gt;making a great product is not a sprint&lt;/em&gt;, and that as knowledge workers, our value is not in lines of code written, tickets completed, or widgets produced.&lt;/p&gt;
&lt;p&gt;High performing teams will out perform any single individual. This is why businesses build teams.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;Then why do we still use tired arguments like “X slows &lt;em&gt;ME&lt;/em&gt; down”?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For X we could subsitute Test-Driven Development, Pair Programming, Open Offices, Meetings, code reviews, design reviews, pretty much any part of any process ever… the list goes on.&lt;/p&gt;
&lt;p&gt;This is not an effort to sweep all critiques of the aforementioned under the rug. But, if you truly believe that software development is a &lt;em&gt;long term, continuous team effort&lt;/em&gt;, then you must be willing to sacrifice your perceived optimal personal productivity.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;You must optimize your processes around the values and goals of the team, not your individual “flow.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Too often, despite our agreements and platitudes on teamwork, we sometimes seem to still struggle to discard the last vestiges of my teenaged software development mental model.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;It turns out that my teenaged myth of the programmer god was not just wrong, but often toxic. Look at the damage in certain communities, e.g. Linus Torvalds’ notoriously abusive behavior. We have probably all seen or been on teams where the “smartest” person on the team was a person that maybe most needed to be fired.&lt;/p&gt;
&lt;p&gt;Many of us have felt unsafe or uncomfortable when we think about that critical piece of code that one person wrote and no one else understands (please don’t leave). Some of us may have been awoken in the middle of the night by Pager Duty and tried to figure out what was going on in some of that code after they have left.&lt;/p&gt;
&lt;p&gt;To be clear, I don’t believe you are toxic if you don’t agree with me about TDD or Pair Programming, or that you are a bad person if you have written that code (I would like to officially apologize to all my Instructure iOS colleagues for rewriting all our networking code in Reactive Cocoa).&lt;/p&gt;
&lt;p&gt;What I do believe, is that we need to stop framing criticism of practices in terms of personal productivity and the coveted state of “flow.” Instead we must focus on the practices that will help our teams achieve “flow.”⁶&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;There is an analogy I heard once about oxen and yokes. Now, don’t read too much into this (human workers are certainly not livestock), but the analogy goes something like this:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;A yoke slows down the fastest ox to the speed of the slowest ox, but allows them to collectively pull more than they could individually.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Reframing every practice and process in terms of the values of your team and organization, rather than your personal values, is key to the success of your team.&lt;/p&gt;
&lt;p&gt;Thank you for coming to my Ted Talk.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;This has been Part I of “Sofware is Made by Humans”, an introduction to a series in which I am improvising as I go along. I want to talk about a few things in later segments: at least Pair Programming and Test Driven Development. I also want to touch on themes around eliminating team silos, diversity, inclusion, open offices, and meetings (collaboration). To talk about these, this initial framing of the conversation is crucial. Practices must be aligned with your organizational values. If they are not, they will fail. Also, practices will require an understanding of the principles upon which they are built. I hope to discuss all of these in more focused blog posts assuming I don’t get burnt out on blogging. It’s been a long time though since I’ve blogged consistently and I am trying to rekindle my passion for writing, but I am having fun for now.&lt;/p&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li&gt;I sometimes forget in those days how pliable Blizzard release dates were. I would check almost daily on the development blog for any tidbits, screenshots, any update. And all it did was get delayed and delayed (who knew software was so hard!). By the time the game was released my original clan website I made had been done for years.&lt;/li&gt;
&lt;li&gt;I actually gave up for a while trying to learn PHP because I wrote all the code in a text file but it didn’t tell me I needed to run a CGI server (or how), so I kept trying to load my PHP files in a browser like I had done when learning HTML.&lt;/li&gt;
&lt;li&gt;I wrote this blog post in such a fit of rage. Forgive my lack of editing.&lt;/li&gt;
&lt;li&gt;My image of a great software developer at that point was always a white man, likely largely due to the fact that all the “legends” I was exposed to were also white men. I didn’t become aware of the problematic nature of this common image til later. Diversity and inclusion are an essential thing to remember as we discuss “Software is Made by Humans.” I hope to tackle it later.&lt;/li&gt;
&lt;li&gt;and probably all product development, every business, every community, society, and the world.&lt;/li&gt;
&lt;li&gt;I used to be a huge fan of the idea of flow, and now I use it in air quotes because I am mostly critical of many of the concepts and surrounding culture. I feel like it is one of the the snake oils of the productivity nerd community.&lt;/li&gt;
&lt;/ol&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Ship Faster with this One Weird Trick</title>
        <published>2020-02-16T00:00:00+00:00</published>
        <updated>2020-02-16T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/ship-faster-with-this-one-weird-trick/"/>
        <id>https://jarsen.engineer/ship-faster-with-this-one-weird-trick/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/ship-faster-with-this-one-weird-trick/">&lt;p&gt;Last year our team decided to start documenting a list of our pain points as developers. We created a spreadsheet with columns for the original reporter, a quick description, and a pain rating on scale of 1-10 of how bad it hurts. We started to review the the document weekly in our team Dev Discussion meeting, using it to decide if there were techincal problems we needed to prioritize and address.&lt;/p&gt;
&lt;p&gt;As some time passed we started to recognize a cluster of pains. They looked something like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;MERGE CONFLICTS :( - 10/10&lt;/li&gt;
&lt;li&gt;Code review sucks - and let’s be real ppl see a 1k+ line PR and only do a quick scan. - 10/10&lt;/li&gt;
&lt;li&gt;I don’t know what environment has what “Is this merged into staging?” - 9/10&lt;/li&gt;
&lt;li&gt;PRs are open too long - 8/10&lt;/li&gt;
&lt;li&gt;Too much WIP and context switching - 8/10&lt;/li&gt;
&lt;li&gt;We keep stepping on each others toes as we refactor the same code or introduce similar ideas similtaenously. - 8/10&lt;/li&gt;
&lt;li&gt;Between the time of a feature being “dev complete” and approved by QA and Product, someone else may have merged and then we need to merge, deal with conflicts, and if it was big enough ask for another code review and get QA to check it out again. - 8/10&lt;/li&gt;
&lt;li&gt;Time from start of feature dev to release is too long - 7/10&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;All these pain points were related in some way to our branching strategy–a fairly generic git flow inspired approach. We had a master, which on merge would run our test suite in Circle CI, build our image, and deploy to prod. We had feature branches that could contain the work for anything from a small ticket to a small epic. We also had long-lived branches for an ungoldy number of staging/test environments. We would often have to ask “hey does anyone know if X feature is merged into Y environment?”&lt;/p&gt;
&lt;p&gt;The merge conflicts were where we felt the pain most accutely: since all of the branches were long lived, at best the conflicts were just dealing with a few renames, new methods, etc., at worst we would have totally refactored code someone else modified, or similtaenously introduced related/competing concepts and structures.&lt;/p&gt;
&lt;p&gt;We knew what hurt. We had a list of the symptoms. We had tried a few things in the past to bandaid some of the ouchies, but they didn’t stick.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;One experiment we tried was making PRs really small. We called this experiment &lt;strong&gt;“smol PRs”&lt;/strong&gt;. The idea was that if we did small PRs, they would be easy to review and we could merge more frequently and have less painful merges.&lt;/p&gt;
&lt;p&gt;The wise among you may already be able to guess what happened next: the number of open PRs exploded, and they were all big nasty chains of dependent branches. Our WIP remained the same, except now it was distributed and harder to manage. We had to review and merge all PRs in the right order. A PR review that required changes led to all downstream branches to rebase. It was bad.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;Stepping back, we had to think more about what was really wrong: what was the core of these problems? We knew they shared the same root but couldn’t articulate the essence of the relationship.&lt;/p&gt;
&lt;p&gt;Eventually we started to frame our problems in another context: our branching strategy, deployments, and release cycles were all tightly coupled. More specifically, our release strategy was driving how we managed the other two–did these things really need to be interdependent?&lt;/p&gt;
&lt;p&gt;We had been doing a lot of reading over the months for company sponsored bookclubs. Two books seemed to contain some potential answers: &lt;a rel=&quot;external&quot; href=&quot;https://www.amazon.com/Accelerate-Software-Performing-Technology-Organizations-ebook/dp/B07B9F83WM&quot;&gt;Accelerate&lt;/a&gt;and &lt;a rel=&quot;external&quot; href=&quot;https://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0321278658&quot;&gt;XP Explained&lt;/a&gt;. From Accelerate we knew that our deployment frequency was really at the core of the pain we felt–all of these things were &lt;em&gt;deployment pains&lt;/em&gt;. We knew what we wanted to do was focus on things that allowed us to deploy frequently. Both books contained a lot principles focused on deploying more frequently. Some of them we were already doing. Some of them we were not. And some of them we &lt;em&gt;thought&lt;/em&gt; we were doing, but were not. A few practices that stuck out to us were Continuous Integration (introduced by Extreme Programming over two decades ago), Trunk-Based Development, Continuous Delivery, and Continuous Deployment.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;continuous-integration&quot;&gt;Continuous Integration&lt;/h2&gt;
&lt;p&gt;Accelerate says the following about Continuous Integration:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Many software development teams are used to developing features on branches for days or even weeks. Integrating all these branches requires significant time and rework. […] High-performing teams keep branches short-lived (less than one day’s work) and integrate them &lt;em&gt;into&lt;/em&gt; trunk/master frequently. Each change triggers a build process that includes running unit tests. If any part of this process fails, developers fix it immediately.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;I was shooketh. I had always thought I was doing CI–after all, I had a CI server running my tests in the cloud! But running an automated test suite on commit is not Continous Integration. I’d been using the word CI &lt;a rel=&quot;external&quot; href=&quot;https://trunkbaseddevelopment.com/continuous-integration/&quot;&gt;incorrectly&lt;/a&gt;for maybe a decade, without knowing where it came from and what it really meant.&lt;/p&gt;
&lt;p&gt;All of a sudden it was so obvious. I don’t know if you’ve had this experience: but sometimes you will learn a new word and all of a sudden you start to hear it &lt;em&gt;everywhere&lt;/em&gt;. And then you realize, people didn’t start using it just after you learned it, it was there the whole time and you just didn’t hear it.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#footnote-18KR&quot;&gt;¹&lt;/a&gt; It was a similar experience to read a 20+ year old book and see it right there in the words.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“The Extreme Programming practice of Continuous Integration encourages all members of a development team to integrate their work daily, instead of developing features in isolation for days or weeks.”&lt;br /&gt;
&lt;br /&gt;
– Martin Fowler&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There you have it. &lt;strong&gt;If you are not merging all your team’s work into the same place every day, you are not doing Continuous Integration.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;We had the automated tests part of CI down, what we were missing was trunk-based development.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Trunk-based development is a required practice for continuous integration. Continuous integration (CI) is the combination of practicing trunk-based development and maintaining a suite of fast automated tests that run after each commit to trunk to make sure the system is always working.”&lt;br /&gt;
&lt;br /&gt;
– &lt;a rel=&quot;external&quot; href=&quot;https://cloud.google.com/solutions/devops/devops-tech-trunk-based-development&quot;&gt;Google Solutions DevOps&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;There are a few styles of trunk-based development, but since we are a small team working in our own product we decided on the simplest route: everyone on the team began developing and pushing directly to &lt;code&gt;master&lt;/code&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;It sounded a bit crazy at first. What if someone broke the build? We need to be able to deploy at any point. There also would almost always be “unfinished” features in the code that we did not want enabled yet in our production environment.&lt;/p&gt;
&lt;p&gt;We knew there would be tradeoffs, even if we didn’t yet know what new problems and friction we’d experience, but in the words of &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/bliki/FrequencyReducesDifficulty.html&quot;&gt;Martin Fowler&lt;/a&gt;:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“If it hurts, do it more often.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2 id=&quot;goodbye-code-review&quot;&gt;Goodbye, Code Review&lt;/h2&gt;
&lt;p&gt;One of the first things to go was PR based code review. Given that we were commiting directly to &lt;code&gt;master&lt;/code&gt;, this really wasn’t going to work for us.&lt;/p&gt;
&lt;p&gt;Our &lt;a rel=&quot;external&quot; href=&quot;https://mavenlink.com/&quot;&gt;company&lt;/a&gt; practices Extreme Programming. As part of that we spend most of our coding time pairing and mobbing–this means that our code already has had multiple sets of eyes on it. We decided that this was enough, along with our practice of TDD, to feel confident that we could push commits directly to master.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#footnote-28KR&quot;&gt;²&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Without PR code review, we were never blocked on review or chaining up WIP. Our momentum skyrocketed. And like a snowball rolling down a mountain, it accelerated as the wins began to compound.&lt;/p&gt;
&lt;h2 id=&quot;gaming-the-system-with-small-commits&quot;&gt;Gaming the System with Small Commits&lt;/h2&gt;
&lt;p&gt;When we first got started, one thing we expected was to have more frequent merge conflicts. We thought, “We will see them more often, but they will be smaller and more manageable.”&lt;/p&gt;
&lt;p&gt;Then something funny happened: no one wanted to be the pair to deal with merge conflicts, so unspoken, pairs started to commit more frequently in an attempt to get all their changes in so the &lt;em&gt;other&lt;/em&gt; pair had to deal with the conflicts. Commits got smaller, and as soon as you finished a commit pairs would push so it wasn’t sitting queued up locally.&lt;/p&gt;
&lt;p&gt;The surprising result, however, was that we now almost never see merge conflicts at all. Since everyone is working in small commits and constantly pushing, we were forced to &lt;code&gt;git pull --rebase&lt;/code&gt; if you wanted to push your change, and thus had to deal with merge conflicts immediately. If we found we were working on similar abstractions, we were able to collaborate early. This meant less time in slack asking questions about other people’s architectural opinions, and we began to communicate through the changes in the code more and more. This led to other changes in our team like self organizing pairs–we used plan a pairing schedule in standup, but now we just sort of pair up however we feel.&lt;/p&gt;
&lt;p&gt;The natural shift in behavior by developers trying to avoid pain resulted in a superior process in almost every way. Our retros became a constant refrain of “God, this is fun.”&lt;/p&gt;
&lt;p&gt;It reminded me of reading Kent Back on Test-Commit-Revert (TCR). Basically, with TCR, you write some code and tests, and if your tests fail, your git repository automatically does a hard reset and all of your work is lost. Sounds whack? It is. At first…&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Every time we make a mistake, as expected–&lt;em&gt;poof&lt;/em&gt;–our changes disappear. At first, the disappearing code startles us. Then we notice our programming style changing.&lt;br /&gt;
&lt;br /&gt;
Initially, we just make the same change again, but the computer eventually out-stubborns us. Then, if we’ve been making changes and we aren’t sure if we’ve broken anything, we just run the command line. If we disagree with the computer about whether we’ve made a mistake, we figure out how to make the change in several smaller steps.&lt;br /&gt;
&lt;br /&gt;
We know that we’re on to something with this new workflow. Despite its simplicity and similarity to test-driven development, it creates intense incentives for making changes in small steps.&lt;br /&gt;
&lt;br /&gt;
With a couple days’ practice, we gain confidence in our shiny new TCR skills. TCR incentivizes us to create an endless stream of tiny changes, each of which results in working software.&lt;br /&gt;
&lt;br /&gt;
– Kent Beck, &lt;a rel=&quot;external&quot; href=&quot;https://increment.com/testing/testing-the-boundaries-of-collaboration/&quot;&gt;Testing the Boundaries of Collaboration&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Focusing on the smallest and simplest changes keep everyone adaptible and agile, armed with fast feedback loops. We moved away from the common tendency to tackle multiple problems at once (humans are bad at multitasking), and focused on doing one thing well at at time. It’s pretty common on our team now to realize we are falling into that trap and to stash/reset all our changes and start over with a more clear direction.&lt;/p&gt;
&lt;p&gt;Small changes also mean we are less likely to break the build.&lt;/p&gt;
&lt;h2 id=&quot;not-breaking-the-build&quot;&gt;Not Breaking the Build&lt;/h2&gt;
&lt;p&gt;This was one of the big unknowns and concerns when starting to practice trunk-based development. I think it is also likely a concern that keeps many people from wanting to practice it: “Sounds nice maybe for small teams. But won’t work at our scale.”&lt;/p&gt;
&lt;p&gt;We already were comfortable with our build system (Circle CI) and had no problem quickly setting up a workflow to build our docker image for deployment and run our tests. If both steps are successful, we configured it to deploy directly to our production environment. We set up a Circle integration with slack to notify us when the build failed.&lt;/p&gt;
&lt;p&gt;We did break the build a few times, and still do occasionaly (many of the cases seem to have been issues with intermittent failures in our browser tests 💀. The friction means we deal with these issues quickly).&lt;/p&gt;
&lt;p&gt;If the build breaks, the pair responsible stops immediately to fix it. This is easy to do since we were working in such small commits–there really isn’t much context switching. It also means we spend effort keeping our tests fast and clean.&lt;/p&gt;
&lt;h2 id=&quot;commiting-unfinished-features-to-prod&quot;&gt;Commiting Unfinished Features to Prod&lt;/h2&gt;
&lt;p&gt;Working in small commits on top of master means you are usually commiting an unfinished feature directly to the production environment. Yikes. This was another thing that really required us to shift the way we thought about development (for the better again).&lt;/p&gt;
&lt;p&gt;&lt;code&gt;git&lt;/code&gt; branches are not the only way to branch code.&lt;/p&gt;
&lt;p&gt;Firstly, you can commit dead code–code that can’t be called isn’t likely to cause problems. This is what we do most of the time. Since we practice TDD we get lots of feedback about the code without having to run it. We also can use tricks like commenting out routes, or only exposing routes when we are in developer mode to make sure our code is dead in prod.&lt;/p&gt;
&lt;p&gt;You can branch by &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/bliki/BranchByAbstraction.html&quot;&gt;abstraction&lt;/a&gt;. Instead of doing something to a function, class, etc., that would change current behavior, replace it with an interface and you can gradually make your changes while the overall system sees no difference.&lt;/p&gt;
&lt;p&gt;You can also branch by feature flagging. At first I thought we would be doing a decent amount of feature flagging. However we almost never feature flag (at least in the way I used to understand it), and we certainly have not installed a complex feature flagging library or &lt;a rel=&quot;external&quot; href=&quot;https://launchdarkly.com/&quot;&gt;service&lt;/a&gt;.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#footnote-38KR&quot;&gt;³&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Your feature flag doesn’t need to be fancy: it can be an &lt;code&gt;if(false)&lt;/code&gt; statement you comment out during dev, or a GET param depending on your needs. Martin Fowler has some great ideas in his &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/articles/feature-toggles.html&quot;&gt;Feature Toggles&lt;/a&gt; article. I love this one:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function reticulateSplines(){
    var useNewAlgorithm = false;
    // useNewAlgorithm = true; // UNCOMMENT TO WORK ON

    if( useNewAlgorithm ){
      return enhancedSplineReticulation();
    }else{
      return oldFashionedSplineReticulation();
    }
  }

  function oldFashionedSplineReticulation(){
    // current implementation lives here
  }

  function enhancedSplineReticulation(){
    // TODO: implement better SR algorithm
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;“Ahhh!!! But what if accidentaly forget to recomment it?” Don’t. And if your tests don’t fail when you forget you’ve got other problems. Or you’re actually done anyway.&lt;/p&gt;
&lt;p&gt;What about migrations? Migrations can’t really be feature flagged or commited as dead code. So, don’t commit migrations that break things. You’re going to have to think about order of operations a lot. Your brain may not be trained to tackle thinking about breaking problems up this way (mine certainly wasn’t, and still has a lot to learn). But the benefits are worth it.&lt;/p&gt;
&lt;h2 id=&quot;testing-in-prod&quot;&gt;Testing in Prod&lt;/h2&gt;
&lt;p&gt;We all love a good meme about testing in prod. The funny thing is though, testing in prod is actually awesome—we just need to talk about what it means.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Testing in production is a superpower. It’s our inability to acknowledge it that’s the trouble.”&lt;br /&gt;
&lt;br /&gt;
– &lt;a rel=&quot;external&quot; href=&quot;https://increment.com/testing/i-test-in-production/&quot;&gt;Charity Majors&lt;/a&gt; (a must read article)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Testing in Prod does not mean: just push up unvalidated code and see what happens. It means that we have another tool to understand our systems. It also means we don’t have so many environments to manage. And it puts us closer to the user.&lt;/p&gt;
&lt;p&gt;As you might guess from how often I quote Martin Fowler’s blog… there is something about it there too… &lt;a rel=&quot;external&quot; href=&quot;https://www.martinfowler.com/articles/qa-in-production.html&quot;&gt;QA in Production&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;One of the consequences of our decisions as a team, is that every green commit is deployed to prod. After something goes live, pairs get on and manually verify features as needed. And not test in a “looking for regressions” way–our tests should catch that. This is an &lt;em&gt;exploratory&lt;/em&gt; style of testing. Our QA team member and product are also doing their tests on the production environment.&lt;/p&gt;
&lt;p&gt;We don’t have a lot of overhead in this process. Frankly, a lot of that is because we are a tiny team and we are developing a new product with no daily users. When we get to the right scale, we will probably start experiencing some pains that cause us to explore new things. We already have some ideas of what the future may hold: canary deploys, blue green deployements, automated rollbacks, super rad dashboards, observability tools… but we look at these only when we start to feel the pains.&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;It’s certainly not perfect. We have some new pains that we are experiencing. For example, because our deployements are push based (build and deploy on commit), if we commit faster than Circle CI can build and deploy our image, we end up with error when one of the Circle Workflows tries to deploy an image for a commit that is no longer the head of master. We’re not sure how we’ll address this yet–the noise hasn’t hurt bad enough yet–but maybe we’ll look at decoupling our deploys from the CircleCI workflows and doing something more pull based. Who knows?&lt;/p&gt;
&lt;p&gt;Another tradeoff is that code review used to serve as a sort of visiblity function: reviewing code would help you see changes you might not see otherwise. We’ve been trying to tackle this by having more frequent pair rotations (we usually rotate daily, sometimes we rotate during the same day), and also by mobbing more. I think there are other things we could learn here still.&lt;/p&gt;
&lt;p&gt;But the benefits have been undeniable and drastic in impact:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We are deploying many times a day, and it’s super easy to track.&lt;/li&gt;
&lt;li&gt;We never deal with paintful merge conflicts.&lt;/li&gt;
&lt;li&gt;We have have a much better incremental problem solving style.&lt;/li&gt;
&lt;li&gt;Our code is better.&lt;/li&gt;
&lt;li&gt;Engineering is more integrated with QA, Product, &amp;amp; Design.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We are able to move so fast–too fast. My new challenge is working with product &amp;amp; design keeping to keep up with how fast our “full stack” team of 4.5 engineers moves.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#footnote-48KR&quot;&gt;⁴&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;It may sound like “high-performance team” snake oil, but I really do believe we can attribute so much of the great change on our team to our new favorite weird trick: trunk-based development.&lt;/p&gt;
&lt;p&gt;🛳&lt;/p&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li&gt;I’ve experienced this a lot–especially with Spanish, a second language to me.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#ref-18KR&quot;&gt;↩&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;We did add caveats that if someone was working solo, they needed to ask somebody near them to pass off and their name added as co-author with &lt;a rel=&quot;external&quot; href=&quot;https://github.com/git-duet/git-duet&quot;&gt;&lt;code&gt;git-duet&lt;/code&gt;&lt;/a&gt;, or they needed to open a PR. Since we don’t solo often, that amount of work has remained small and at a scale that is trivial to manage.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#ref-28KR&quot;&gt;↩&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Yet. We may very well need this one day but avoiding any unecessary overhead helps us move fast. If we do it will be to help decouple our &lt;em&gt;deployment&lt;/em&gt; from our &lt;em&gt;releases&lt;/em&gt;. It will because we want the ability for product to control the toggle, and/or control percentages of people getting new features so we can a/b test, do a gradual rollout while monitoring the system, etc.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#ref-38KR&quot;&gt;↩&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;I only count myself as half. Meetings, you know.&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/16/ship-faster-with-this-one-weird-trick#ref-48KR&quot;&gt;↩&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Truth About Microservices Will Shock You!</title>
        <published>2020-02-02T00:00:00+00:00</published>
        <updated>2020-02-02T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/the-truth-about-microservices-will-shock-you/"/>
        <id>https://jarsen.engineer/the-truth-about-microservices-will-shock-you/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/the-truth-about-microservices-will-shock-you/">&lt;p&gt;It’s that time again… monolith vs microservices architecture debate on twitter! What better time to throw my hat into the ring and scream my raw, non-peer-reviewed thoughts into the void?&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/i/web/status/1222966700913479681&quot;&gt;Referenced post on X&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Like all patterns, implementing a microservices architecture pattern is a transaction that exchanges one set of problems for a different set of problems. The cost and benefits together are known as “tradeoffs.” If anyone ever talks about a pattern without talking about its tradeoffs, slowly back away until you are at a safe distance. Then flee.&lt;/p&gt;
&lt;p&gt;Given that choosing a design pattern is about trading problem sets, &lt;em&gt;before you implement a solution you must know what problem you have&lt;/em&gt;. If you are starting with a solution looking for problems, you are in for a long dark journey ahead.&lt;/p&gt;
&lt;p&gt;One of the common problems people try to address with a microservices architecture is “shitty code.” More specifically, your monolith has become a tangled mess of connections between various “boundaries.” ¹ (I am rather fond of the german word kabelsalat, meaning literally “cable-salad,” refering to the hellscape of tangled cables behind your TV, etc. Wouldn’t it be fun refer to our spaghetti code as kōdsalat?)&lt;/p&gt;
&lt;p&gt;Here’s the thing, the microservices architecture is a pattern about &lt;em&gt;deployment&lt;/em&gt;, not code boundaries. The problems microservices seek to give away by changing deployment strategy are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;bad performance in critical bottlenecks where you may want to switch language, or scale the number of servers/pods etc.&lt;/li&gt;
&lt;li&gt;critical inefficiencies for teams in delivering software due to awkward mappings between large codebases and large org structures (see &lt;a rel=&quot;external&quot; href=&quot;https://en.wikipedia.org/wiki/Conway%27s_law&quot;&gt;Conway’s Law&lt;/a&gt; and the Inverse Conway Maneuver)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you think microservices are the solution to your kōdsalat problem, you will find yourself filled with regret on your dying bed, slain by your new &lt;strong&gt;distributed monolith&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;This quote from Kelsey Hightower’s &lt;a rel=&quot;external&quot; href=&quot;https://changelog.com/posts/monoliths-are-the-future&quot;&gt;interview called “Monoliths are the future”&lt;/a&gt; is priceless:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Now you went from writing bad code to building bad infrastructure that you deploy the bad code on top of.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The irony of the distributed monolith is that now you have all the problems of a microservices architecture, but with none of the benefits. You paid the price for none of the gain.&lt;/p&gt;
&lt;p&gt;If the problems you are trying to address are not focused on increasing the ability for a team to ship (an organizational and human challenge, not a code one), or critical performance bottlenecks affecting users (a user problem, not a code one), then you should pack up your microservice bags and leave—all you are going to do is trade problems you don’t have for new problems. If one or both of these are the problems you are trying to solve, microservices &lt;em&gt;may&lt;/em&gt; be the solution for you. You may now proceed to weigh the tradeoffs.&lt;/p&gt;
&lt;p&gt;The problems you receive as part of your trade when introducing a microservices architecture include:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;complexity of debugging/tracing events across a distributed system ²&lt;/li&gt;
&lt;li&gt;complexity of dealing with failure in a distributed system.&lt;/li&gt;
&lt;li&gt;complexity of more integration/system testing.&lt;/li&gt;
&lt;li&gt;complexity of creating and maintaining your new infrastructure (e.g. going from a single simple deploy to heroku vs rolling and managing your own k8s behemoth).&lt;/li&gt;
&lt;li&gt;complex new toolchains.&lt;/li&gt;
&lt;/ul&gt;
&lt;hr /&gt;
&lt;p&gt;The conversation about clean code is orthogonal to the deployment conversation. If your kōdsalat is causing you to lose sleep, instead of reading about microservices, pick up your dusty copy of &lt;a rel=&quot;external&quot; href=&quot;https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8&quot;&gt;Gang of Four&lt;/a&gt;, or your fresh, wonderful smelling new edition of &lt;a rel=&quot;external&quot; href=&quot;https://pragprog.com/book/tpp20/the-pragmatic-programmer-20th-anniversary-edition&quot;&gt;The Pragmatic Programmer&lt;/a&gt;. In them you can find decades old solutions to your decades old problems.&lt;/p&gt;
&lt;p&gt;To deal with the tangled mess of code, what you need are better boundaries in your code. What are boundaries? &lt;strong&gt;Boundaries are interfaces around an abstraction.&lt;/strong&gt; In other words, boundaries are an API. Often in the web world we use API exclusively to refer to endpoints on a server somewhere, but used more broadly, the interface of a boundary is its public API. You must interact with a boundary &lt;em&gt;only&lt;/em&gt; via its public interface—that’s what makes it a “boundary.” The opposite of a boundary is a spaghetti or a salad.&lt;/p&gt;
&lt;p&gt;A boundary also dictates a method of transport. &lt;strong&gt;Transport is the method by which you send data and receive data from a boundary.&lt;/strong&gt; ³ Sometimes communicating with a boundary is as simple as internal message passing to a class/module, or a function call. Sometimes it may look like sharing memory ⁴, or inter-process communication. Other times it may be a calling out across a network to a REST API, gRPC, web sockets, etc.&lt;/p&gt;
&lt;p&gt;When boundaries are well defined, the context in which they execute (same process, different process, different core, different machine) becomes irrelevant from the perspective of the caller.⁵ The only thing that matters to the caller is the contract established by the API, and the method of transport so that it knows by what method to actually speak to the boundary. This means, with proper boundaries in a monolith, microservices can be extracted as necessary by changing the location of execution, and having the caller send its data via a new transport.&lt;/p&gt;
&lt;p&gt;For a more concrete example, imagine a Billing module in my monolith. If it defines a good interface, then one day if extracting it to a microservice will help me solve a team problem or performance bottleneck and is worth the tradeoffs, I can pull the module’s logic into a new microservice, and then I change the Billing module to make calls to the microservice. Neato.&lt;/p&gt;
&lt;p&gt;Granted, this is potentially an oversimplification. Often there are implicit APIs relying on shared memory/data that we forget about when designing boundaries. A prime example is the database, especially when involving foreign key constraints.&lt;/p&gt;
&lt;p&gt;Considering execution an implementation detail of a boundary is a blade that cuts both ways. Practicing Domain Driven Design and developing strong &lt;a rel=&quot;external&quot; href=&quot;https://martinfowler.com/bliki/BoundedContext.html&quot;&gt;Bounded Contexts&lt;/a&gt; means that to truly get the benefits of strong boundaries, you must also accept the tradeoffs as well. These tradeoffs can start to look like some of the tradeoffs you might expect from microservices. In fact, when going full DDD and ending up with things like an event message bus, it starts to look an awful like a distributed system in spite of it perhaps executing in the same system process. But, unlike microservices, you will not need new complex infrastructure, and you will be focused on creating boundaries, so you should not be led to a distributed monolith.&lt;/p&gt;
&lt;p&gt;Anyway, now that we’ve come full circle and I have seemingly undermined my own arguments, I have two final points to make.&lt;/p&gt;
&lt;h2 id=&quot;1-there-is-no-single-right-answer-and-anyone-who-doesn-t-talk-about-decisions-in-terms-of-tradeoffs-is-either-a-dogmatist-and-or-is-selling-you-something&quot;&gt;1. There is no single “right” answer and anyone who doesn’t talk about decisions in terms of tradeoffs is either a dogmatist and/or is selling you something.&lt;/h2&gt;
&lt;p&gt;It’s easy to think we’re fancy and treading new ground with our “modern” monolith vs microservices debates. But really it’s just a variation of the same age-old debates that have been going on for decades: monolithic kernels vs microkernels, lots of small specialized tools vs one integrated one, etc. The benefits of boundaries comes with a cost; abstraction is not free. If we are still having the same fundamental debate after decades, it’s likely because there is no one size fits all solution, and ultimately you need to choose what problems you want to have. ⁶&lt;/p&gt;
&lt;h2 id=&quot;2-if-this-problem-is-not-a-pain-that-affects-your-users-it-s-not-a-problem-to-be-spending-time-on&quot;&gt;2. If this problem is not a pain that affects your users, it’s not a problem to be spending time on.&lt;/h2&gt;
&lt;p&gt;Yehuda Katz went on an interesting twitter rant the other day spurred by the recent resurgence in microservice debate.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/i/web/status/1223051812862861312&quot;&gt;Referenced post on X&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I find these thoughts off-putting because it illustrates a fundamental misalignment amongst many engineering organizations—a world in which not not everyone on the team (including design, product, qa, tech writing–not just engineering disciplines) feel they have a seat at the table. If you’re not sitting at the same table as a team&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2020/02/2/the-truth-about-microservices-will-shock-you#footnote-7133&quot;&gt;⁷&lt;/a&gt; what are you doing? It’s a dark world where employees are siloed and bickering and unhappy, and it will surely show in the product.&lt;/p&gt;
&lt;p&gt;Start with problems that affect your customers, not solutions. Learn to state your problems in terms of customer benefit.&lt;/p&gt;
&lt;p&gt;Fortunately, the problems microservices intend to address are easily measurable. Trouble shipping? Track deployment frequency. Stay focused on how frequent deployment benefits the user. Performance bottlenecks? Start measuring times from a user’s perspective. Now that you have a problem identified and a baseline you can begin to explore solutions, including microservices.&lt;/p&gt;
&lt;p&gt;Aligning on the problems to solve and tracking key metrics will help ensure the focus is driven by business priorities, not by siloed engineering street cred, hype, or fun with computers. Don’t let microservices become an intellectual flex that hurts people you care about.&lt;/p&gt;
&lt;hr /&gt;
&lt;ol&gt;
&lt;li&gt;I use air quotes here because in all likelihood if you are feeling this pain we should be using the term very loosely.&lt;/li&gt;
&lt;li&gt;See: &lt;a rel=&quot;external&quot; href=&quot;https://www.honeycomb.io/wp-content/uploads/2018/07/Honeycomb-Guide-Achieving-Observability-v1.pdf&quot;&gt;observability&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;In practice, the line between an API and it’s transport mechanism is pretty blurred. For example, the fact a service uses GraphQL both defines the API, and the transport mechanism.&lt;/li&gt;
&lt;li&gt;Sharing memory is usually a good example of a lack of boundaries—a sort of implicit API.&lt;/li&gt;
&lt;li&gt;Working a lot in Elixir has really helped me start to understand better the difference between code and its execution–a function is just a function, and module a module. Whether it executes in a new process or not is an implementation detail hidden behind my public interface.&lt;/li&gt;
&lt;li&gt;Choosing what problems you want to have is a great way to think about life, as well. Accepting that all decisions come with a price, and being intentional about those decisions can lead to much peace and understanding. 🧘🏻‍♂️&lt;/li&gt;
&lt;li&gt;metaphorically, although this could be taken literally and be very beneficial as well.&lt;/li&gt;
&lt;/ol&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>I Did Not Shoot the Marshal</title>
        <published>2017-06-06T00:00:00+00:00</published>
        <updated>2017-06-06T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/i-did-not-shoot-the-marshal/"/>
        <id>https://jarsen.engineer/i-did-not-shoot-the-marshal/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/i-did-not-shoot-the-marshal/">&lt;h2 id=&quot;json-in-swift-4-and-open-source-thoughts&quot;&gt;JSON in Swift 4 and Open Source Thoughts&lt;/h2&gt;
&lt;p&gt;Swift 4 brings a cornucopia of welcome (and a few unwelcome) updates. One of the ones I am excited about is the introduction of Codable. As the owner of a &lt;a rel=&quot;external&quot; href=&quot;https://github.com/utahiosmac/Marshal&quot;&gt;popular open source JSON mapping framework&lt;/a&gt;, I really look forward to Codable making my work obsolete. It’s the death of an era, but it is a necessary death.&lt;/p&gt;
&lt;p&gt;Here is what mapping JSON to an object looks like using Marshal.&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;struct User: Unmarshaling {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var id: Int&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var name: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var email: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;init(object: MarshaledObject) throws {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;id = try object.value(for: “id”)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;name = try object.value(for: “name”)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;email = try object.value(for: “email”)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let users: [User] = try json.value(for: “users”)&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/8f574d75ee86c5b8b56039bfe5eb432a/raw/59d8597e539a6613e9308bfa349bb88583c642fa/unmarshaling.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/8f574d75ee86c5b8b56039bfe5eb432a#file-unmarshaling-swift&quot;&gt;unmarshaling.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And here is the simplest possible implementation of a Codable student.&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;struct Student: Codable {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var name: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var age: Int&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var email: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let student = Student(name: “Jason”, age: 99, email: “jason@example.com”)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let encoder = JSONEncoder()&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let data = try encoder.encode(student)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let decoder = JSONDecoder()&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let newStudent = try decoder.decode(Student.self, from: data)&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/ec99f0b6059571f80ea52d2feed81228/raw/97734a205e1ef934b8a36197fc8e7afb2c2b36fa/implicit_codable.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/ec99f0b6059571f80ea52d2feed81228#file-implicit_codable-swift&quot;&gt;implicit_codable.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The JSON keys we’re looking for here are implicitly defined to be the same as our variable names. If we have keys that don’t match the names of our variables, say for example, the key for age was “student_age” instead of just “age”, we can explicitly provide our keys like this:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;struct Student: Codable {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var name: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var age: Int&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var email: String&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;enum CodingKeys: String, CodingKey {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;case name&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;case age = “student_age”&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;case email&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/70de1dc800cbd487da6b5827e7a50654/raw/435b5bdad5508fa74216998973afe6c41ddef391/explicit_codable.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/70de1dc800cbd487da6b5827e7a50654#file-explicit_codable-swift&quot;&gt;explicit_codable.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The nice thing about Codableis that we get implementations of both Encodableand Decodable for free. However, the keys can still be implicit, and I find this to be a lurking danger. Having had too many gotcha moments using Mantle long ago, I felt that it was important to have the mapping always be explicit. This is why Marshal never embraced reflection.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Explicit is better than implicit.
- The Zen of Python
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But, you don’t have to take my word for it. The Swift blog, in it’s final section in the &lt;a rel=&quot;external&quot; href=&quot;https://developer.apple.com/swift/blog/?id=37&quot;&gt;Working with JSON in Swift&lt;/a&gt; post had this to say:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Converting between representations of the same data in order to communicate between different systems is a tedious, albeit necessary, task for writing software. Because the structure of these representations can be quite similar, it may be tempting to create a higher-level abstraction to automatically map between these different representations. For instance, a type might define a mapping between snake_case JSON keys and camelCase property names in order to automatically initialize a model from JSON using the Swift reflection APIs, such as Mirror. However, we’ve found that these kinds of abstractions tend not to offer significant benefits over conventional usage of Swift language features, and instead make it more difficult to debug problems or handle edge cases. In the example above, the initializer not only extracts and maps values from JSON, but also initializes complex data types and performs domain-specific input validation. A reflection-based approach would have to go to great lengths in order to accomplish all of these tasks. Keep this in mind when evaluating the available strategies for your own app. The cost of small amounts of duplication may be significantly less than picking the incorrect abstraction.”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Now, as far as I understand, Codable is not actually using any reflection—the compiler is actually generating those functions for you—but I think that the sentiment remains for me. I personally am going to always explicitly define my CodingKeys, even if they all match my variable names.&lt;/p&gt;
&lt;h2 id=&quot;core-data&quot;&gt;Core Data?&lt;/h2&gt;
&lt;p&gt;One thing I have yet to completely understand is how Codeable works with CoreData. Marshal has a protocol that allows the user to update an existing model with a dictionary and some context. It appears, according to my cursory looks that the userInfo dictionary on the decoder is where you want to pass along any context. But, I haven’t looked very deep because I don’t personally use CoreData in any of my projects.&lt;/p&gt;
&lt;h2 id=&quot;beyond-json&quot;&gt;Beyond JSON&lt;/h2&gt;
&lt;p&gt;One of the “cool” things about Marshal is that it wasn’t just about JSON. It could handle anything that conformed to the simple MarshaledObject protocol. This means you could use the same initialization methods to create an object from JSON as you could from a plist, CloudKit, or some other data source. Codable also supports this sort of behavior through use of different decoders. Personally, I think the Codable approach is more elegant in this regard.&lt;/p&gt;
&lt;h2 id=&quot;open-source-thoughts&quot;&gt;Open Source Thoughts&lt;/h2&gt;
&lt;p&gt;I really enjoyed using and working on Marshal. But wow was it a lot of work. At the time of writing this article Marshal has 477 stars. Which, is a good amount, but trivial compared to many other projects. Even with this relatively low usage, it was very burdensome to maintain between having a job, family, and hobbies/other projects. I definitely have a completely new respect for big people in the open source scene, and a strong opinion that companies that use open source should contribute to open source, whether that contribution be opening up their own code, encouraging employees to do open source work on the clock (not on their own time), or financial donations.&lt;/p&gt;
&lt;p&gt;I’m happy that this Codable work was part of Swift’s development as an open source effort. Even though sometimes (like anything you love or work with all day) Swift drives me nuts with some of its quirks/decisions, I appreciate all the efforts of the Swift team and the community as a whole. Open source is hard. Communication is hard. Making everyone happy is hard. I’d say this is one of the hardest problems in Software Engineering. But I’m glad so many people are working together so that we can all enjoy making apps more.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Optimistic Networking with Reactor</title>
        <published>2016-09-08T00:00:00+00:00</published>
        <updated>2016-09-08T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/optimistic-networking-with-reactor/"/>
        <id>https://jarsen.engineer/optimistic-networking-with-reactor/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/optimistic-networking-with-reactor/">&lt;h2 id=&quot;a-love-story&quot;&gt;A Love Story&lt;/h2&gt;
&lt;p&gt;Last time we talked about some pretty cool stuff we can do to build a more reactive iOS application using the &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Reactor&quot;&gt;Reactor&lt;/a&gt; architecture. Today we’ll investigate how we can keep in sync with data from the network and &lt;em&gt;make our app faster with the power of optimism!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Let’s look at the Reactor architecture diagram for a quick refresher:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;┌──────────────────┐                                 ┌──────────────────┐
│                  │                                 │                  │
│                  │         ┌───────────┐           │                  │
│                  │◀────────┤   Event   ├───────────┤                  │
│                  │         └───────────┘           │                  │
│                  │                                 │                  │
│                  │                                 │                  │
│     Reactor      │                                 │    Subscriber    │
│                  │                                 │                  │
│                  │         ┌───────────┐           │                  │
│    ┌───────┐     ├─────────┤  update   ├──────────▶│                  │
│    │ State │     │         └───────────┘           │                  │
│    └───────┘     │                                 │                  │
│                  │                                 │                  │
└──────────────────┘                                 └──────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/356832f3d4410eeac76b118c52fb2310/raw/a201b5e4e2276df3738c8228c6d0ed78c43808da/reactor_diagram.md&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/356832f3d4410eeac76b118c52fb2310#file-reactor_diagram-md&quot;&gt;reactor_diagram.md &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We send events to make the Reactor update our application state. The reactor handles events, updates the state, and then notifies all the subscribers. But what about asynchronous events?&lt;/p&gt;
&lt;h2 id=&quot;commands&quot;&gt;Commands&lt;/h2&gt;
&lt;p&gt;Performing async events is likely going to be a common occurrence in your app. Reactor offers the Command API to help establish a consistent and safe way to perform asynchronous events&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;struct FetchPlayers: Command {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var session = URLSession.shared&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;func execute(state: State, reactor: Reactor) {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;session.dataTask(with: fetchPlayerURL) { data, response, error in&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;if error {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: DisplayError(message: “Error fetching players”))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;else {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var players: [Player] = // handle json…&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: Update(value: players))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}.resume()&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// Caller uses:&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(command: FetchPlayers())&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/aff991b011ec33314f34e6e66a9d437a/raw/ceea450a365bc1e6e1ad62f12aac8852a303d6ef/Command.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/aff991b011ec33314f34e6e66a9d437a#file-command-swift&quot;&gt;Command.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Hopefully the code inside execute looks similar to your usual networking functions. The difference here is we’ve wrapped it inside of a function which receives its own copy of the application state and reference to the Reactor. We don’t end up needing the state for anything here, but we use the Reactor reference to dispatch events upon network task completion.&lt;/p&gt;
&lt;h2 id=&quot;instant-optimistic-network-results&quot;&gt;Instant, Optimistic Network Results&lt;/h2&gt;
&lt;p&gt;Say we’re performing a different type of network request, perhaps adding a new player. Do we really want to wait for a response from the server before we can update our UI? Can you imagine liking a post on Facebook and waiting for the request to travel all the way to the Facebook and back to confirm our like was successfully recorded before seeing the thumb turn blue? &lt;em&gt;Ain’t nobody got time for that!&lt;/em&gt; We want our app to feel fast and responsive!&lt;/p&gt;
&lt;p&gt;What if we just assume the network request is successful and immediately update the UI? Then we can update with the real response later. Or, in the case of an error, we can reset to the original state. Let’s call this “optimistic networking.”&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;struct AddPlayer: Command {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var session = URLSession.shared&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var player: Player&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;func execute(state: State, reactor: Reactor) {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let originalPlayers = state.players&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;let task = session.dataTask(with: player.putRequest()) { data, response, error in&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;if error {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// 3. whoops. switch back and display error&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: Update(value: originalPlayers))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: DisplayError(message: “Error adding \player.name)”))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;else {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// handle json and …&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// 2. update with the real values from the server, hopefully the same&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: Update(value: players))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// 1. optimistically assume success and immediately update UI&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;var optimisticPlayers = originalPlayers&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;optimisticPlayers.append(player)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(event: Update(value: optimisticPlayers))&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;task.resume()&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;// Caller uses:&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;reactor.fire(command: AddPlayer(player: player))&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/8cabf133e6aa2311322a8c82922f9223/raw/49acd6b88390c5c9a4fbb03170b233f18adb6398/OptimisticCommand.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/8cabf133e6aa2311322a8c82922f9223#file-optimisticcommand-swift&quot;&gt;OptimisticCommand.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This code is similar to our FetchPlayers command, but we have added properties to our struct—this allows us to set up necessary data for our async Command. We also are firing events in a few more places:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We optimistically add the new player to our state, and fire an event telling the reactor to update its current list of players with our optimistic list.&lt;/li&gt;
&lt;li&gt;Upon a successful request, we parse the response and update (for a second time) with the result the server returns. If the data is the same (if our optimism was correct) then we should see no difference.&lt;/li&gt;
&lt;li&gt;If our request came back with an error, then we reset the list back to where it was when we started, and display an error message to the user.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;If you are using Reactor and doing any sort of of asynchronous operations then you want to use Commands!&lt;/p&gt;
&lt;p&gt;Commands will help you handle async tasks in a consistent manner while leveraging the power of Reactor to keep your UI always in sync. And with almost no work at all, you can have the power of optimism to make your app feel faster.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>React Native, Native</title>
        <published>2016-08-29T00:00:00+00:00</published>
        <updated>2016-08-29T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/react-native-native/"/>
        <id>https://jarsen.engineer/react-native-native/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/react-native-native/">&lt;h2 id=&quot;making-your-swift-app-more-react-nativey&quot;&gt;Making your Swift app more React Nativey&lt;/h2&gt;
&lt;h2 id=&quot;confessions&quot;&gt;Confessions&lt;/h2&gt;
&lt;p&gt;I’m going to let you in on a dirty little secret. Sometimes I think longingly about React Native.&lt;/p&gt;
&lt;p&gt;I know, I know. Feels so wrong. But some of it feels so right. *Reactive, declarative UI code? Hot reloading? Updates that can bypass the app store?*And even though Javascript isn’t as sweet in a lot of ways as Swift, it’s getting pretty good (new async/wait and gradual type checking with &lt;a rel=&quot;external&quot; href=&quot;https://flowtype.org/&quot;&gt;Flow&lt;/a&gt;). I keep trying it out from time to time, wanting it to be amazing and save me from all the things that drive me nuts in iOS development. &lt;a rel=&quot;external&quot; href=&quot;http://artsy.github.io/blog/2016/08/15/React-Native-at-Artsy/&quot;&gt;Of course it’s not without its share of cons&lt;/a&gt;, but certain features are awful fun and productive—and who doesn’t want to have fun and be productive?&lt;/p&gt;
&lt;p&gt;For those of us who decide React Native is not the way, what if we could get some of the features while still writing Swift? Today we’ll explore how we can have a reactive, declarative UI code and &lt;em&gt;hot reload app data&lt;/em&gt; so we can save tons of testing time. Also, maybe we can do something to bypass the app store for updates even just a little?&lt;/p&gt;
&lt;h2 id=&quot;reactive-declarative-ui&quot;&gt;Reactive, Declarative UI&lt;/h2&gt;
&lt;p&gt;React Native lets us write UI code that feels more like a description of what the UI should be, separated from the logic that configures and transforms all the data. We don’t have the fancy virtual DOM React does, but we can work around that.&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Reactor&quot;&gt;Reactor&lt;/a&gt; is a small Swift library I wrote inspired by Elm, Redux, and the work on the excellent &lt;a rel=&quot;external&quot; href=&quot;https://github.com/ReSwift/ReSwift&quot;&gt;ReSwift&lt;/a&gt; by Benjamin Encz and others. See the documentation for a more in depth understanding of Reactor, but the basic model we’re working with is this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;┌──────────────────┐                                 ┌──────────────────┐
│                  │                                 │                  │
│                  │         ┌───────────┐           │                  │
│                  │◀────────┤   Event   ├───────────┤                  │
│                  │         └───────────┘           │                  │
│                  │                                 │                  │
│                  │                                 │                  │
│     Reactor      │                                 │    Subscriber    │
│                  │                                 │                  │
│                  │         ┌───────────┐           │                  │
│    ┌───────┐     ├─────────┤  update   ├──────────▶│                  │
│    │ State │     │         └───────────┘           │                  │
│    └───────┘     │                                 │                  │
│                  │                                 │                  │
└──────────────────┘                                 └──────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/356832f3d4410eeac76b118c52fb2310/raw/a201b5e4e2276df3738c8228c6d0ed78c43808da/reactor_diagram.md&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/356832f3d4410eeac76b118c52fb2310#file-reactor_diagram-md&quot;&gt;reactor_diagram.md &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In a nutshell, we have one state object with all of the application data nested inside of it. Each of our view controllers has an update function that knows how to take the state object and update its view. The view controllers subscribe to the Reactor, which notifies them whenever the state changes.&lt;/p&gt;
&lt;p&gt;An example of this update function might look like:&lt;/p&gt;
&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td&gt;func update(with state: State) {&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;guard let user = state.user else { return }&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;firstNameLabel.text = user.firstName&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;lastNameLabel.text = user.lastName&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;ageLabel.text = String(user.age)&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;}&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/241de4df94dd4f110583b54f33294834/raw/f19fef495227edf9d162e8a977a78d1d64dcf620/UpdateExample.swift&quot;&gt;view raw&lt;/a&gt;&lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/241de4df94dd4f110583b54f33294834#file-updateexample-swift&quot;&gt;UpdateExample.swift &lt;/a&gt;hosted with ❤ by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;All UI updates go in this function. This gives us one easy place to declare exactly how our UI reflects the app data. It will always stay up to date, reacting to the any state updates.&lt;/p&gt;
&lt;p&gt;If this hasn’t all settled in yet, don’t worry. Going in depth here is beyond the scope of this article. Read the &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Reactor&quot;&gt;documentation&lt;/a&gt; and ping me on twitter with questions. And if you don’t like Reactor, ReSwift is terrific and the pattern is simple enough you can easily roll your own. The point is, if we store our application data in one data structure, we can have simple reactive, declarative UI code in Swift without React Native or a mind bending FRP library that may scare co-workers away (but make you sound super smart at dinner parties).&lt;/p&gt;
&lt;h2 id=&quot;hot-reloading&quot;&gt;Hot Reloading&lt;/h2&gt;
&lt;p&gt;We cannot, due to Swift limitations, hot reload recompiled code. Bummer.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;But&lt;/em&gt;, we did just talk about representing our application data as a struct. What if, hypothetically, we could serialize/deserialize our entire state into some format—say… JSON—save it to the file system, and then watch that file for updates? Then, hypothetically, we could edit that JSON file in our favorite text editor and our app would automatically update using our Reactor architecture.&lt;/p&gt;
&lt;p&gt;Hypothetically. &lt;em&gt;Right&lt;/em&gt;?&lt;/p&gt;
&lt;p&gt;Enter the amazing &lt;a rel=&quot;external&quot; href=&quot;https://github.com/krzysztofzablocki/KZFileWatchers&quot;&gt;KZFileWatchers&lt;/a&gt; by &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/merowing&quot;&gt;Krzysztof Zabłocki&lt;/a&gt;. Observe:&lt;/p&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2016/08/29/Check%20out%20the%20example%20project&quot;&gt;Check out the example project&lt;/a&gt; to see how it’s done. But it’s pretty much exactly like you might imagine: our state is designed to serialize/deserialize using &lt;a rel=&quot;external&quot; href=&quot;http://github.com/utahiosmac/Marshal&quot;&gt;Marshal&lt;/a&gt;, and then we use the hook it all together with our architecture and the file watcher.&lt;/p&gt;
&lt;p&gt;I think there’s a lot of potential here: recreate buggy states users report, testing UI without having to recompile, easy inspection of your apps current state… all kinds of fun stuff.&lt;/p&gt;
&lt;h2 id=&quot;bypassing-the-app-store&quot;&gt;Bypassing the App Store&lt;/h2&gt;
&lt;p&gt;We’re quickly approaching the end of the known iOS universe.&lt;/p&gt;
&lt;p&gt;Javascript, due to its interpreted nature, not only can hot reload code, but can hot reload code that has been received over the network. This leads to a whole realm of possibilities for A/B Testing, bypassing the app store for some updates, and security vulnerabilities. :P&lt;/p&gt;
&lt;p&gt;As we’ve dicussed before, we can’t hot reload Swift code. We do know we can hot reload application data, however. So, what if we represented more of our UI as application data? Maybe we could write a few reusable components, and the data itself would tell us which UI component it wants to use. &lt;a rel=&quot;external&quot; href=&quot;https://atscaleconference.com/videos/backend-driven-native-uis/&quot;&gt;This is something that Spotify is doing&lt;/a&gt;, as demonstrated by &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/johnsundell&quot;&gt;John Sundell&lt;/a&gt;. Watch that video. Cool, cool stuff.&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;React Native takes some heat from the iOS community; probably a lot is undeserved from developers who haven’t tried it, but like all tools it comes with its own pros and cons.&lt;/p&gt;
&lt;p&gt;Maybe those cons outweight the pros for you in your project. That doesn’t mean we shouldn’t covet the pros or try to figure out how we can apply the ideas amazing software developers in other areas to our own domain&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Refactoring: Replace Enum with Polymorphism</title>
        <published>2016-08-08T00:00:00+00:00</published>
        <updated>2016-08-08T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/refactoring-replace-enum-with-polymorphism/"/>
        <id>https://jarsen.engineer/refactoring-replace-enum-with-polymorphism/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/refactoring-replace-enum-with-polymorphism/">&lt;p&gt;Enums in Swift are great—love me some sweet, sweet enums. However, as with all great things, one can go too far.&lt;/p&gt;
&lt;p&gt;Let’s look at the following contrived example:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;swift&quot;&gt;enum Animal {

    enum Size {
        case small
        case medium
        case large
    }

    case dog
    case cat
    case cow

    var noise: String {
        switch self {
        case .dog:
            return &amp;quot;woof&amp;quot;
        case .cat:
            return &amp;quot;meow&amp;quot;
        case .cow:
            return &amp;quot;moo&amp;quot;
        }
    }

    var size: Size {
        switch self {
        case .dog:
            return .medium
        case .cat:
            return .small
        case .cow:
            return .large
        }
    }

}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I’ve seen a lot of enums like this. Well, not animals maybe. But you know what I mean.&lt;/p&gt;
&lt;p&gt;Let’s do a mental exercise: how do you add a fox to your list of animals? Pretty straightforward: add a new case, the compiler will tell you your cases are no longer exhaustive and you fill out those cases… and done.&lt;/p&gt;
&lt;p&gt;Unless you’re switching on it somewhere else in your code. Then you have to update those too.&lt;/p&gt;
&lt;p&gt;And if you have lots of vars/funcs… That’s a lot of work to add a case to to each.&lt;/p&gt;
&lt;p&gt;And now that you look at it, there’s a lot of duplicate code involved to setup the switches and define all the cases.&lt;/p&gt;
&lt;p&gt;And can you imagine what will happen if you have to throw logic and associated types into the mix?&lt;/p&gt;
&lt;p&gt;This could get unwieldy quickly.&lt;/p&gt;
&lt;h2 id=&quot;let-s-rewind&quot;&gt;Let’s Rewind&lt;/h2&gt;
&lt;p&gt;Why are we using an enum in the first place? Is it just because I want a way to group lots of the same type together that have the same properties?&lt;/p&gt;
&lt;p&gt;There is a way to do this that has existed since the dawn of time: &lt;em&gt;protocols&lt;/em&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;swift&quot;&gt;enum AnimalSize {
    case small
    case medium
    case large
}

protocol Animal {
    var noise: String { get }
    var size: AnimalSize { get }
}

struct Dog: Animal {
    var noise = &amp;quot;woof&amp;quot;
    var size = AnimalSize.medium
}

struct Cat: Animal {
    var noise = &amp;quot;meow&amp;quot;
    var size = AnimalSize.small
}

struct Cow: Animal {
    var noise = &amp;quot;moo&amp;quot;
    var size = AnimalSize.large
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This ancient refactoring technique is known as &lt;a rel=&quot;external&quot; href=&quot;https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism&quot;&gt;Replace Conditional with Polymorphism&lt;/a&gt;, and it can make your code cleaner, if you will let it in your heart. But I’ll call it Protocol Oriented Programming so we can get people to use it and increase traffic to this article.&lt;/p&gt;
&lt;p&gt;As you can see:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We remove lots of duplicate switch code.&lt;/li&gt;
&lt;li&gt;Adding a new case is as simple as adding a new type — no need to refactor other methods. This is the Open/Closed Principle.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code data-lang=&quot;swift&quot;&gt;struct Fox: Animal {
    var noise = &amp;quot;wa-pa-pa-pa-pa-pa-pow&amp;quot;
    var size = AnimalSize.medium
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;when-should-you-use-enums&quot;&gt;When Should You Use Enums?&lt;/h2&gt;
&lt;p&gt;As I said before, enums are great. You just need to use them appropriately. They are great for scenarios where you specifically do not want flexibility, or awesome things like ADTs.&lt;/p&gt;
&lt;p&gt;Notice that when we refactored we kept an AnimalSize enum lingering around; we only ever want those 3 types, so that’s a good use case for an enum.&lt;/p&gt;
&lt;p&gt;So, ask yourself first:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;“Do I know all cases and want to make sure every possibility is accounted for—but never more?”&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;If so, you very well might want to use an enum!&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Enums are an awesome, essential part of Swift, but it seems that this new shininess can sometimes lead to using enums where they aren’t the best fit.&lt;/p&gt;
&lt;p&gt;Let us go forth and use enums greatly, but also not forget the lessons of the past.&lt;/p&gt;
&lt;h2 id=&quot;further-reading&quot;&gt;Further Reading&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;http://www.jessesquires.com/enums-as-configs/&quot;&gt;Enums as configuration: the anti-pattern&lt;/a&gt; by &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/jesse_squires&quot;&gt;Jesse Squires&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Protocol-Oriented JSON in Swift</title>
        <published>2015-10-15T00:00:00+00:00</published>
        <updated>2015-10-15T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/protocol-oriented-json-in-swift/"/>
        <id>https://jarsen.engineer/protocol-oriented-json-in-swift/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/protocol-oriented-json-in-swift/">&lt;p&gt;Previously we &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/no-magic-json-parsing-with-swift-part-ii/&quot;&gt;explored&lt;/a&gt; how to use Swift’s amazing type system to simplify our JSON code. We came up with a solution that was concise, without building a complicated tree of JSON enums, using crazy operators, or getting deep into reflection. And we did it all in 100-some-odd lines of code.&lt;/p&gt;
&lt;p&gt;Today we’re going to use &lt;em&gt;protocol-oriented programming&lt;/em&gt; to take it even further.&lt;/p&gt;
&lt;p&gt;Last time we created our own class, &lt;code&gt;JSONObject&lt;/code&gt;, to encapsulate a JSON dictionary and to hold our &lt;code&gt;valueForKey&lt;/code&gt; family of helpers. This encapsulation had several benefits, however, it also came with the baggage of having to constantly wrap our basic &lt;code&gt;[String:AnyObject]&lt;/code&gt; JSON dictionaries. This can become especially tedious when we have nested JSON objects we want to extract.&lt;/p&gt;
&lt;p&gt;This time let’s use the power of protocols in Swift to extend &lt;code&gt;Dictionary&lt;/code&gt;. Of course, we don’t want to extend all instances of &lt;code&gt;Dictionary&lt;/code&gt;, just the instances that look like &lt;code&gt;[String:AnyObject]&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;json-keys&quot;&gt;JSON Keys&lt;/h2&gt;
&lt;p&gt;Although Swift allows us to restrict extensions on generic types, it only allows us to restrict the types based on protocols. Thus, we need a protocol to describe our &lt;code&gt;Key&lt;/code&gt; type.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public protocol JSONKeyType: Hashable {
    var stringValue: String { get }
}

extension String: JSONKeyType {
    public var stringValue: String {
        return self
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We’ll never make anything other than &lt;code&gt;String&lt;/code&gt; conform to &lt;code&gt;JSONKeyType&lt;/code&gt;. It’s a little bit of a work around, but it will allow us do this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension Dictionary where Key: JSONKeyType {
    // functions available only on instances where Key is a String
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;json-values&quot;&gt;JSON Values&lt;/h2&gt;
&lt;p&gt;We defined a protocol for our key type, so let’s define a protocol for our value type.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public protocol JSONValueType {
    typealias _JSONValue = Self

    static func JSONValue(object: Any) throws -&amp;gt; _JSONValue
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In order for a type to conform to &lt;code&gt;JSONValueType&lt;/code&gt;, it must implement a function that constructs itself given an &lt;code&gt;Any&lt;/code&gt;, or throw an error if it can’t. The &lt;code&gt;typealias&lt;/code&gt; is there to help the compiler out with some of the things we’ll do later.&lt;/p&gt;
&lt;p&gt;Many of the types we’ll be dealing with are directly bridgeable from their &lt;code&gt;Any&lt;/code&gt; counterpart. We can extend the &lt;code&gt;JSONValueType&lt;/code&gt; protocol to provide a default implementation for these cases, then simply add conformance to said types.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension JSONValueType {
    public static func JSONValue(object: Any) throws -&amp;gt; _JSONValue {
        guard let objectValue = object as? _JSONValue else {
            throw JSONError.TypeMismatch(expected: JSONValue.self,
                                         actual: object.dynamicType)
        }
        return objectValue
    }
}

extension String: JSONValueType {}
extension Int: JSONValueType {}
extension UInt: JSONValueType {}
extension Float: JSONValueType {}
extension Double: JSONValueType {}
extension Bool: JSONValueType {}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Et voila!&lt;/p&gt;
&lt;p&gt;If there are other types we wish to extract from our JSON, we can add conformance to &lt;code&gt;JSONValueType&lt;/code&gt; for them as well.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension NSURL: JSONValueType {
    public static func JSONValue(object: Any) throws -&amp;gt; NSURL {
        guard let urlString = object as? String,
              objectValue = NSURL(string: urlString) else {
            throw JSONError.TypeMismatch(expected: self,
                                         actual: object.dynamicType)
        }
        return objectValue
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This extension allows us to extract &lt;code&gt;NSURL&lt;/code&gt;s when the &lt;code&gt;Any&lt;/code&gt; is a valid URL string. We can write similar extension for &lt;code&gt;NSDate&lt;/code&gt;, and even &lt;code&gt;Array&lt;/code&gt; and &lt;code&gt;Dictionary&lt;/code&gt;. (You can find implementations for the last two in the &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/0f0919d3f43b2a2268e6&quot;&gt;gist&lt;/a&gt;. I have not included an &lt;code&gt;NSDate&lt;/code&gt; implementation because of the plethora of date-time representations, but writing your own for your specific should be straightforward.)&lt;/p&gt;
&lt;h2 id=&quot;extending-dictionary&quot;&gt;Extending Dictionary&lt;/h2&gt;
&lt;p&gt;Now to the heart of the matter: actually extending &lt;code&gt;Dictionary&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension Dictionary where Key: JSONKeyType {
    private func anyForKey(key: Key) throws -&amp;gt; Any {
        let pathComponents = key.stringValue.characters
                                .split(&amp;quot;.&amp;quot;).map(String.init)
        var accumulator: Any = self

        for component in pathComponents {
            if let componentData = accumulator as? [Key: Value],
                   value = componentData[component as! Key] {
                accumulator = value
                continue
            }

            throw JSONError.KeyNotFound(key: key)
        }

        return accumulator
    }

    public func JSONValueForKey&amp;lt;A: JSONValueType&amp;gt;(key: Key) throws -&amp;gt; A {
        let any = try anyForKey(key)
        guard let result = try A.JSONValue(any) as? A else {
            throw JSONError.TypeMismatchWithKey(key: key,
                                                expected: A.self,
                                                actual: any.dynamicType)
        }

        if let _ = result as? NSNull {
            throw JSONError.NullValue(key: key)
        }

        return result
    }

    public func JSONValueForKey&amp;lt;A: JSONValueType&amp;gt;(key: Key) throws -&amp;gt; [A] {
        let any = try anyForKey(key)
        return try Array&amp;lt;A&amp;gt;.JSONValue(any)
    }

    public func JSONValueForKey&amp;lt;A: JSONValueType&amp;gt;(key: Key) throws -&amp;gt; A? {
        do {
            return try self.JSONValueForKey(key) as A
        }
        catch JSONError.KeyNotFound {
            return nil
        }
        catch JSONError.NullValue {
            return nil
        }
        catch {
            throw error
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This should look mostly familiar if you followed along with &lt;a rel=&quot;external&quot; href=&quot;https://jasonlarsen.me/2015/06/23/no-magic-json-parsing-with-swift-part-2&quot;&gt;Part 2&lt;/a&gt;. What’s new is us restricting &lt;code&gt;A&lt;/code&gt; to conform to &lt;code&gt;JSONValueType&lt;/code&gt;. Now it is impossible for us to try and extract a value from our JSON and shove it into a non-JSONValueType conforming box. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// the old way let this compile
let firstName: UILabel = json.valueForKey(&amp;quot;first_name&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With our code in Part 2, this code would compile, even though we would likely figure it out down the road when we tried to use &lt;code&gt;firstName&lt;/code&gt;. The fact that &lt;code&gt;A&lt;/code&gt; must be a &lt;code&gt;JSONValueType&lt;/code&gt; gives us a little bit more safety here.&lt;/p&gt;
&lt;p&gt;Some more changes that have been made are to consolidate the public API to just one function signature: &lt;code&gt;JSONValueForKey&lt;/code&gt;. The compiler will figure out which version of the function to call based off of the type it is being assigned to—be it a plain ol’ &lt;code&gt;A&lt;/code&gt;, optional &lt;code&gt;A?&lt;/code&gt;, or even an array of &lt;code&gt;[A]&lt;/code&gt;! (The latter requires &lt;code&gt;Array&lt;/code&gt; to conform to &lt;code&gt;JSONValueType&lt;/code&gt;. You can find this in the &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/0f0919d3f43b2a2268e6&quot;&gt;gist&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Finally, use the power of &lt;code&gt;typealias&lt;/code&gt; to make it more clear what we’re talking about when dealing with our JSON dictionaries.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public typealias JSONObject = [String: AnyObject]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And now your JSON code can look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var json: JSONObject = [&amp;quot;url&amp;quot;: &amp;quot;http://apple.com&amp;quot;, &amp;quot;foo&amp;quot;: (2 as NSNumber), &amp;quot;str&amp;quot;: &amp;quot;Hello, World!&amp;quot;, &amp;quot;array&amp;quot;: [1,2,3,4,7], &amp;quot;object&amp;quot;: [&amp;quot;foo&amp;quot;: (3 as NSNumber), &amp;quot;str&amp;quot;: &amp;quot;Hello, World!&amp;quot;], &amp;quot;bool&amp;quot;: (true as NSNumber)]
do {
    var str: String = try json.JSONValueForKey(&amp;quot;str&amp;quot;)
    var foo2: Int = try json.JSONValueForKey(&amp;quot;foo&amp;quot;)
    var foo3: Int? = try json.JSONValueForKey(&amp;quot;foo&amp;quot;)
    var foo4: Int? = try json.JSONValueForKey(&amp;quot;bar&amp;quot;)
    var arr: [Int] = try json.JSONValueForKey(&amp;quot;array&amp;quot;)
    var obj: JSONObject? = try json.JSONValueForKey(&amp;quot;object&amp;quot;)
    let innerfoo: Int = try obj!.JSONValueForKey(&amp;quot;foo&amp;quot;)
    let innerfoo2: Int = try json.JSONValueForKey(&amp;quot;object.foo&amp;quot;)
    let bool: Bool = try json.JSONValueForKey(&amp;quot;bool&amp;quot;)
    let url: NSURL = try json.JSONValueForKey(&amp;quot;url&amp;quot;)
}
catch {
    // ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can find the full code in this &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/0f0919d3f43b2a2268e6&quot;&gt;gist&lt;/a&gt;, and most likely in a more permanent Github repo home soon.&lt;/p&gt;
&lt;p&gt;Please share this if you like it and leave me feedback below in the comments or on the twitters &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/jarsen&quot;&gt;@jarsen&lt;/a&gt;!&lt;/p&gt;
&lt;p&gt;I hope this makes Crusty proud.&lt;/p&gt;
&lt;p&gt;A special thanks to a bunch of local Utah iOS developers who have been working on this and giving lots of great ideas, especially: Bart Whiteley, Brian Mullen, BJ Homer, Derrick Hathaway, Dave DeLong, Mark Schultz and Tim Shadel.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>The Church of Xcode - Simple Emacs Keybindings</title>
        <published>2015-07-22T00:00:00+00:00</published>
        <updated>2015-07-22T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/the-church-of-xcode-simple-emacs-keybindings/"/>
        <id>https://jarsen.engineer/the-church-of-xcode-simple-emacs-keybindings/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/the-church-of-xcode-simple-emacs-keybindings/">&lt;p&gt;Long has the holy war between emacs and vi been waged. I’ve used both, and I don’t really care either way. However, OS X text fields everywhere come with secret support for limited (and sometimes modified) Emacs keybindings. So, regardless of your position in the great text editor wars you might as well learn a few keybindings because &lt;em&gt;you can use them anywhere you see a text field&lt;/em&gt;. Learning a few basic keybindings will empower you as an iOS/Mac developer and as an OS X user.&lt;/p&gt;
&lt;h2 id=&quot;emacs-modifier-keys&quot;&gt;Emacs Modifier Keys&lt;/h2&gt;
&lt;p&gt;Whenever you look at emacs shortcuts you’ll see something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;C-v
M-v
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A little translation is needed: C is the control key (⌃) and M is the “META” key, which in our case is the alt/option key (⌥). Since we’re not really a member of the church of emacs, from now on we’ll refer to our modifier keys using ⌃ and ⌥.&lt;/p&gt;
&lt;h2 id=&quot;remapping-caps-lock&quot;&gt;Remapping Caps Lock&lt;/h2&gt;
&lt;p&gt;The ⌃ key is not in the easiest position to stretch your fingers to, and it gets used a lot as a key modifier. So much so, you might want to consider remapping a less useful key that’s in a good position. A common choice for this is the Caps Lock key. If you’re like me you don’t do a lot of shouting when you type, and when you do you can hold down the shift key for a minute. So, it’s a prime choice.&lt;/p&gt;
&lt;p&gt;Simply go to your Keyboard preferences, hit the modifier keys button in the bottom right, and change the Caps Lock dropdown to “⌃ Control”.&lt;/p&gt;
&lt;p&gt;Remapping your keyboard is really easy, and your friends will think you’re hardcore.&lt;/p&gt;
&lt;h2 id=&quot;cursor-movement&quot;&gt;Cursor Movement&lt;/h2&gt;
&lt;p&gt;The point of keybindings is to keep your fingers on the keyboard where they belong; you want to avoid as much as possible moving your hand to mouse. Even using the arrow keys requires you to move your fingers away from their home row, and should be avoided where possible.&lt;/p&gt;
&lt;p&gt;⌃F | Move Cursor &lt;strong&gt;F&lt;/strong&gt;orward |&lt;br /&gt;
⌃B | Move Cursor &lt;strong&gt;B&lt;/strong&gt;ackward |&lt;br /&gt;
⌃P | Move Cursor U&lt;strong&gt;p&lt;/strong&gt; |&lt;br /&gt;
⌃N | Move Cursor Dow&lt;strong&gt;n&lt;/strong&gt; |&lt;br /&gt;
⌃E | Move to &lt;strong&gt;E&lt;/strong&gt;nd of Line (also ⌘→) |&lt;br /&gt;
⌃A | Move to Beginning of Line … (&lt;strong&gt;A&lt;/strong&gt; is the first letter of the alphabet?) (also ⌘←)&lt;/p&gt;
&lt;p&gt;If you hold down shift with any of these, you will move the selection as you move your cursor.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;You can also use ⌃P and ⌃N to move the selection in your autocomplete results up and down!&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Nobody likes to move the cursor one character at a time when you have a long ways to go. In Emacs, if you use the meta key instead of control, you can move forward and back by entire words. If you try to do this in Mac ⌥F and ⌥B instead insert the fancy characters ƒ and ∫, respectively. This is a little tricky because Mac also allows users to use the ⌥ key to insert special characters.&lt;/p&gt;
&lt;p&gt;We can add our own keybindings to override this behavior in Xcode by adding out own Key Bindings in Xcode preferences (which I do suggest), but part of our goal here is to learn key bindings that work across the system. These key bindings are available system wide, although in modified form—you must hold down both the control and meta modifier keys.&lt;/p&gt;
&lt;p&gt;⌥⌃F | Move Cursor &lt;strong&gt;F&lt;/strong&gt;orward a word (also ⌥→) |&lt;br /&gt;
⌥⌃B | Move Cursor &lt;strong&gt;B&lt;/strong&gt;ackward a word (also ⌥←) |&lt;/p&gt;
&lt;p&gt;Once again, holding shift while using either of these will move your selection. (Although it requires holding down 3 modifier keys! You’ll get lots of finger dexterity).&lt;/p&gt;
&lt;h2 id=&quot;text-deletion&quot;&gt;Text Deletion&lt;/h2&gt;
&lt;p&gt;Sometimes you want to delete text. These keybindings will help you delete efficiently.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Deleting by &lt;em&gt;word&lt;/em&gt; deletes whole words delimited by whitespace or other non-word characters.&lt;/li&gt;
&lt;li&gt;Deleting by &lt;em&gt;subword&lt;/em&gt; will delete individual words in camelCasedWords (camel, Cased, and Words are each in subwords)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;⌃⌫ | Backward delete a subword |&lt;br /&gt;
⌃⌦ | Forward delete a subword |&lt;br /&gt;
⌥⌫ | Backward delete a word |&lt;br /&gt;
⌥⌦ | Forward delete a word |&lt;br /&gt;
⌃k | Delete to end of line (&lt;strong&gt;k&lt;/strong&gt;ill) (also ⌘⌦) |&lt;br /&gt;
⌘⌫ | Delete to beginning of line (this is not really an Emacs binding, but a must-know nonetheless) |&lt;/p&gt;
&lt;p&gt;(⌫ is the backspace key, and ⌦ is the Delete key)&lt;/p&gt;
&lt;h2 id=&quot;exercise&quot;&gt;Exercise&lt;/h2&gt;
&lt;p&gt;You can look over these shortcuts till the cows come home, but unless you practice them you will never realize their utility.&lt;/p&gt;
&lt;p&gt;One exercise I like to do is to &lt;em&gt;try not to use the arrow keys at all&lt;/em&gt;. Now, sometimes I find using the arrow keys to be more efficient (like moving forward/back by word or in the cases of ⌘↑ and ⌘↓ to move to the top and bottom of the file), but forcing myself to not use them helps me practice my other keybindings and I realize which operations I can actually do more quickly without the arrow keys.&lt;/p&gt;
&lt;hr /&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Emacs of course has many, many more keybindings. With Xcode’s Key Binding preferences you can try to imitate more of them, but these are just some standard OS-wide key bindings that will help you text edit more efficiently.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>No-Magic JSON Parsing with Swift Part II</title>
        <published>2015-06-15T00:00:00+00:00</published>
        <updated>2015-06-15T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/no-magic-json-parsing-with-swift-part-ii/"/>
        <id>https://jarsen.engineer/no-magic-json-parsing-with-swift-part-ii/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/no-magic-json-parsing-with-swift-part-ii/">&lt;p&gt;Last time we talked about how we could &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/no-magic-json-parsing-with-swift/&quot;&gt;simplify our JSON parsing&lt;/a&gt; with Swift 2 error handling and get rid of all the magic. Today we’re going to use the power of type inference to take our old &lt;code&gt;JSONObject&lt;/code&gt; struct from having 12 methods (or more, if you want to add methods for values like CGFloat, etc.) to only 4!&lt;/p&gt;
&lt;p&gt;Let’s look at our &lt;code&gt;valueForKey&lt;/code&gt; function.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func valueForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; A {
    let pathComponents = key.componentsSeparatedByString(&amp;quot;.&amp;quot;)

    var accumulator: Any = dictionary

    for component in pathComponents {
        if let dict = accumulator as? [String:AnyObject] {
            if let value = dict[component] {
                accumulator = value
                continue
            }
        }
        throw JSONError.NoValueForKey(key)
    }

    if let value = accumulator as? A {
        return value
    }
    else {
        throw JSONError.TypeMismatch
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With this function we tell our struct what type we are looking to get out and and what key. But the Swift compiler is smart. Real smart. Given just the minimum amount of information, it can &lt;em&gt;infer&lt;/em&gt; what types we’re talking about.&lt;/p&gt;
&lt;p&gt;It turns out we can actually remove the &lt;code&gt;type&lt;/code&gt; argument completely, and as long as we give the compiler a little help at the function’s callsite by specifying the type that the return value will be assigned to, it can infer &lt;code&gt;A&lt;/code&gt; for us.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func valueForKey&amp;lt;A&amp;gt;(key: String) throws -&amp;gt; A {
    let pathComponents = key.componentsSeparatedByString(&amp;quot;.&amp;quot;)

    var accumulator: Any = dictionary

    for component in pathComponents {
        if let dict = accumulator as? [String:AnyObject] {
            if let value = dict[component] {
                accumulator = value
                continue
            }
        }
        throw JSONError.NoValueForKey(key)
    }

    if let value = accumulator as? A {
        return value
    }
    else {
        throw JSONError.TypeMismatch
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And we can use it like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let street: String = try json.valueForKey(&amp;quot;address.street&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Et voila.&lt;/p&gt;
&lt;p&gt;This means that we can remove all of our &lt;code&gt;intForKey&lt;/code&gt;, &lt;code&gt;stringForKey&lt;/code&gt;, etc. And, if we revamp our &lt;code&gt;optionalForKey&lt;/code&gt; in the same way by also removing the &lt;code&gt;type&lt;/code&gt;argument, we can do the same for all our calls to &lt;code&gt;optionalForKey&lt;/code&gt;. The only functions I didn’t remove in my implementation were &lt;code&gt;objectForKey&lt;/code&gt; and &lt;code&gt;optionalObjectForKey&lt;/code&gt; because since the values there are really &lt;code&gt;[String:AnyObject]&lt;/code&gt; you can’t get a &lt;code&gt;JSONObject&lt;/code&gt; out without the initializer.&lt;/p&gt;
&lt;p&gt;Here’s what our updated &lt;code&gt;Person&lt;/code&gt; model might look like:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Person {
    var name: String
    var age: Int
    var height: Double
    var street: String?

    static func fromJSON(json: JSONObject) throws -&amp;gt; Person {
        let name: String = try json.valueForKey(&amp;quot;name&amp;quot;)
        let age: Int = try json.valueForKey(&amp;quot;age&amp;quot;)
        let height: Double = try json.valueForKey(&amp;quot;height&amp;quot;)
        let street: String = try json.valueForKey(&amp;quot;address.street&amp;quot;)
        return Person(name: name, age: age, height: height, street: street)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, having to specify the type in two places is a little much, don’t you think? Surely we can do better. Since the items we’re assigning them to already have types, why not use those?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Person {
    var name = &amp;quot;&amp;quot;
    var age = 0
    var height = 0.0
    var street = String?.None

    static func fromJSON(json: JSONObject) throws -&amp;gt; Person {
        var person = Person()
        person.name = try json.valueForKey(&amp;quot;name&amp;quot;)
        person.age = try json.valueForKey(&amp;quot;age&amp;quot;)
        person.height = try json.valueForKey(&amp;quot;height&amp;quot;)
        person.street = try json.optionalForKey(&amp;quot;address.street&amp;quot;)
        return person
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So, to do that we had to assign default values… which is a little weird as well. What does it mean to have a “default height”? This also is a little unsafe because now the API allows for &lt;code&gt;Person&lt;/code&gt;s to be created without any arguments.&lt;/p&gt;
&lt;p&gt;Let’s try again, but let’s forget about &lt;code&gt;fromJSON&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Person {
    var name: String
    var age: Int
    var height: Double
    var street: String?

    init(json: JSONObject) throws {
        try name = json.valueForKey(&amp;quot;name&amp;quot;)
        try age = json.valueForKey(&amp;quot;age&amp;quot;)
        try height = json.valueForKey(&amp;quot;height&amp;quot;)
        try street = json.optionalForKey(&amp;quot;address.street&amp;quot;)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We got rid of &lt;code&gt;fromJSON&lt;/code&gt; in favor of &lt;code&gt;init&lt;/code&gt;. This gives us the opportunity to set all the values before the object is initialized—the only trick is that our initializer now throws.&lt;/p&gt;
&lt;p&gt;I like that. I hope you do too.&lt;/p&gt;
&lt;p&gt;As always, comments are welcome—either down below or on &lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;twitter&lt;/a&gt; (&lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;@jarsen&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;You can get the &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/b27de2ed9e84b84086ae&quot;&gt;full code here&lt;/a&gt;&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Result vs. Throws</title>
        <published>2015-06-14T00:00:00+00:00</published>
        <updated>2015-06-14T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/result-vs-throws/"/>
        <id>https://jarsen.engineer/result-vs-throws/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/result-vs-throws/">&lt;p&gt;Swift 2.0 is causing a lot of well deserved excitement. Chris and the folks over at apple have been doing an &lt;em&gt;amazing&lt;/em&gt; job. I have been loving Swift the past year and am really excited about all the new features—and, of course, the open source announcement.&lt;/p&gt;
&lt;p&gt;When the &lt;code&gt;do&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; model for error handling was announced, there was a bit of frustration that &lt;code&gt;Result&lt;/code&gt; was not the adopted model. Since then, several developers have come out with &lt;a rel=&quot;external&quot; href=&quot;http://www.sunsetlakesoftware.com/2015/06/12/swift-2-error-handling-practice&quot;&gt;articles&lt;/a&gt; detailing what they &lt;a rel=&quot;external&quot; href=&quot;http://owensd.io/2015/06/12/swift-throws-get-it.html&quot;&gt;like better&lt;/a&gt; about it that have got &lt;a rel=&quot;external&quot; href=&quot;https://twitter.com/clattner_llvm/status/610154161552756736&quot;&gt;quite a bit of attention&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;While I am excited about the prospect of standardized error handling, I still am not convinced that throwing errors is a better approach than &lt;code&gt;Result&lt;/code&gt;. I have a lot of mixed feelings. I’m sure there will be errors and counter-points I have yet to consider, in which case please leave a comment at the bottom or ping me on twitter (&lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;@jarsen&lt;/a&gt;), but here are my thoughts so far.&lt;/p&gt;
&lt;h2 id=&quot;what-is-result&quot;&gt;What is Result?&lt;/h2&gt;
&lt;p&gt;In case you aren’t familiar, &lt;code&gt;Result&lt;/code&gt; is an enum very similar to &lt;code&gt;Optional&lt;/code&gt;: both have cases that hold generic values, but where we have &lt;code&gt;Optional.None&lt;/code&gt; to represent &lt;code&gt;nil&lt;/code&gt; values, we have instead &lt;code&gt;Result.Failure&lt;/code&gt; with an associated &lt;code&gt;ErrorType&lt;/code&gt;. Basically, think of &lt;code&gt;Result&lt;/code&gt; as &lt;code&gt;Optional&lt;/code&gt; with that can carry an error instead of being nil.&lt;/p&gt;
&lt;h2 id=&quot;deal-with-it&quot;&gt;Deal With It&lt;/h2&gt;
&lt;p&gt;One of the purported advantages of &lt;code&gt;do&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; error handling is that it forces the programmer to handle errors.&lt;/p&gt;
&lt;p&gt;But &lt;code&gt;Result&lt;/code&gt; enforces error handling as well. Since &lt;code&gt;Result&lt;/code&gt; is an &lt;code&gt;enum&lt;/code&gt;, in order to get at your potentially successful value you must deconstruct it using pattern matching. If you do so using a switch statement, the switch statement will require you do be exhaustive in your case handling, meaning that you must necessarily handle the &lt;code&gt;Failure&lt;/code&gt; case.&lt;/p&gt;
&lt;p&gt;Now, the astute observer may say, “But Jason, in Swift 2.0 I can deconstruct enums with the new &lt;code&gt;if-case&lt;/code&gt; statements, and thus can avoid handling failures.”&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;if case let .Success(value) = result {
    doSomething(value)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;“Or, you might run something and never handle the result at all. Throwing an error forces you to write a catch”&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let _ = someResultFunction() // ignore result entirely
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both these arguments have good points. Although in the latter case, the only reason someone would do this is to run a function that performs side effects, in which case I would argue that the number of functions performing side effects and returning &lt;em&gt;synchronous&lt;/em&gt; errors where you don’t care about the successful value of the operation is pretty small. If you have a lot of these, I think you’re using &lt;code&gt;Result&lt;/code&gt;wrong.&lt;/p&gt;
&lt;p&gt;And finally, look what I can do:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;try! functionThatThrows() // forces execution without a catch
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both approaches can ignore errors. Sure, &lt;code&gt;try!&lt;/code&gt; will make your program crash if something throws, and you might not think that counts as ignoring errors, but I can see the lazy programmer putting this in because it works in dev every time, or because it rarely executes, or because for some reason &lt;code&gt;functionThatThrows()&lt;/code&gt; only throws a fraction of the time. It’s an open invitation to shoot yourself in the foot. It is a more dangerous way to ignore errors, but it ignores them nonetheless.&lt;/p&gt;
&lt;p&gt;Finally, the cynic in me says many will end up writing empty &lt;code&gt;catch&lt;/code&gt; statements, or else simply:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;do {
    try stuff()
}
catch {
    print(&amp;quot;Error while doing stuff&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I don’t know if this really qualifies as “handling” anything.&lt;/p&gt;
&lt;p&gt;And in many cases not doing anything with an error might be the right thing to do.&lt;/p&gt;
&lt;p&gt;Ultimately I don’t think that making it impossible to ignore errors is the goal here; I think the goal should be to make it difficult to ignore errors.&lt;/p&gt;
&lt;h2 id=&quot;exhaustive&quot;&gt;Exhaustive&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Handling errors appropriately is just as important as not ignoring errors; ignorance about their types is just ignoring them in a different way.&lt;/strong&gt; It is important to know what types of errors you deal with, and for the compiler to help you handle them exhaustively.&lt;/p&gt;
&lt;p&gt;I mentioned that the &lt;code&gt;switch&lt;/code&gt; statement would require you to be exhaustive in your error handling. In contrast, &lt;code&gt;throws&lt;/code&gt; doesn’t know anything about the error types at all. “Exhaustive” in Swift’s &lt;code&gt;try&lt;/code&gt;/&lt;code&gt;catch&lt;/code&gt; world simply means: no matter what, you must always have a catch-all statement because you have no idea what &lt;code&gt;ErrorType&lt;/code&gt;s to expect from a function contract.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;enum Fail : ErrorType {
    case Normal
    case Epic
}

func foo() throws {
    // some code here, may throw any `Fail` case
}

do {
    try foo()
}
catch Fail.Normal {
    print(&amp;quot;Normal fail&amp;quot;)
}
catch Fail.Epic {
    print(&amp;quot;Epic fail!&amp;quot;)
}
catch {
    print(&amp;quot;this statement will NEVER be executed&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Compare this to the same code using &lt;code&gt;Result&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;switch someResult {
case let .Success(value):
    print(value)
case .Failure(.Normal):
    print(&amp;quot;Normal fail&amp;quot;)
case .Failure(.Epic):
    print(&amp;quot;Epic fail!&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I’m unsure if Swift will gain the ability to &lt;code&gt;throw&lt;/code&gt; specific error types in the future. Several people I have talked to think it’s a for-sure enhancement. Others think lack of types is actually a feature, claiming that specifying error types makes the API &lt;em&gt;fragile&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;If that’s the case, why even have pattern matching in &lt;code&gt;catch&lt;/code&gt; statements? If your API could at any minute change what it throws, why bother handling specific errors at all?&lt;/p&gt;
&lt;h2 id=&quot;contracts&quot;&gt;Contracts&lt;/h2&gt;
&lt;p&gt;For practice, I started writing a little JSON parsing library using throwing instead of results. It was really frustrating to deal with Cocoa APIs because they don’t detail what errors might be thrown—I was left writing generic catch-all cases.&lt;/p&gt;
&lt;p&gt;I believe error types belong in the function contract. &lt;code&gt;Result&lt;/code&gt; forces the API to communicate to its caller what in can expect in both the successful case, and in the case of failure.&lt;/p&gt;
&lt;p&gt;**Failing to communicate about the error path in the function contract implies that for some reason the “happy path” is more important.**How can you expect to build robust error handling with a lackadaisical approach to error handling contracts?&lt;/p&gt;
&lt;h2 id=&quot;hijacking-control-flow&quot;&gt;Hijacking Control Flow&lt;/h2&gt;
&lt;p&gt;Consider the following code:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;do {
    try thing1()
    try thing2()
}
catch {
    print(error)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If &lt;code&gt;thing1()&lt;/code&gt; fails, &lt;code&gt;thing2()&lt;/code&gt; will never be executed. In many cases that might be the desired behavior. However, what if you actually want to do something different in the case that both fail, or in the case that only one fails? Using &lt;code&gt;throws&lt;/code&gt; makes this difficult to impossible, as&lt;code&gt;throws&lt;/code&gt; will hijack your code flow and immediately terminate the &lt;code&gt;do&lt;/code&gt; block.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let result1 = thing1()
let result2 = thing2()

switch (result1, result2) {
case (.Success, .Success):
    print(&amp;quot;Everything is awesome!&amp;quot;)
case (.Failure, .Failure):
    print(&amp;quot;Everything is not awesome&amp;quot;)
default:
    print(&amp;quot;Everything is half awesome&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since &lt;code&gt;Result&lt;/code&gt; does not hijack your control flow, you are able to handle errors in a more robust manner. This also makes &lt;code&gt;Result&lt;/code&gt; a great candidate for asynchronous code.&lt;/p&gt;
&lt;h2 id=&quot;async-error-handling&quot;&gt;Async Error Handling&lt;/h2&gt;
&lt;p&gt;One of the main arguments I’ve seen against &lt;code&gt;throws&lt;/code&gt; is that is has no way of handling asynchronous errors. Async error handling is a big deal—most of my error handling code revolves around async networking errors. That said, I actually think that this point has been a little over-exaggerated by those contending for &lt;code&gt;Result&lt;/code&gt;—async errors are just handled with a different pattern altogether. However, I still believe &lt;code&gt;Result&lt;/code&gt; is better than said solution. Take a look at this async networking function.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;func fetchJSON(endpoint: String, completionHandler: (JSONDictionary?, ErrorType?) -&amp;gt; Void) {
    //...
}

fetchJSON(&amp;quot;/api/v3/users&amp;quot;) { json, error in
    if let error = error {
        switch error {
        case ErrorType.Type1:
            // type 1
        case ErrorType.Type2:
            // type 2
        }
        return
    }

    guard let json = json else {
        return
    }

    // handle JSON
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This simple function takes an API endpoint, goes and does the networking and JSON parsing, and then returns the result or an error to the user. This code is not horrible. However, it does mean the developer needs to understand the conventions being used: namely that you need to check if the error is nil first.&lt;/p&gt;
&lt;p&gt;Notice I said it “returns the result or an error.” Gee, that sounds an awful like a &lt;code&gt;Result&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;func fetchJSON(endpoint: String, completionHandler: Result&amp;lt;JSONDictionary, ErrorType&amp;gt; -&amp;gt; Void) {
    //...
}

fetchJSON(&amp;quot;/api/v3/users&amp;quot;) { result in
    switch result {
    case let .Success(json):
        // handle JSON
    case let .Failure(.Type1):
        // handle error type 1
    case let .Failure(.Type2):
        // handle error type 2
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I think the equivalent code using &lt;code&gt;Result&lt;/code&gt; is much better: I have a single switch that handles &lt;em&gt;all&lt;/em&gt; cases.&lt;/p&gt;
&lt;h2 id=&quot;no-asserts&quot;&gt;No Asserts&lt;/h2&gt;
&lt;p&gt;Currently there are no functions available in the &lt;code&gt;XCTAssert&lt;/code&gt; family for asserting whether or not a function or closure throw an error.&lt;/p&gt;
&lt;p&gt;Please join me in filing a &lt;a rel=&quot;external&quot; href=&quot;http://bugreport.apple.com/&quot;&gt;radar&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Here’s how you might write one in the meantime:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;func XCTAssertThrows&amp;lt;A&amp;gt;(file: String = __FILE__, line: Int = __LINE__, test: () throws -&amp;gt; A) {
    do {
        try test()
        XCTFail(&amp;quot;Whoops&amp;quot;, file: file, line: UInt(line))
    }
    catch {

    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;throws-is-simpler&quot;&gt;throws is “simpler”&lt;/h2&gt;
&lt;p&gt;A lot of people seem to think that &lt;code&gt;throws&lt;/code&gt; is easier. I’m not sure if I agree, but even so I find it irrelevant. What does “simpler” mean? Does it mean more familiar for those who have never touched Haskell or Rust or the likes?&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Result&lt;/code&gt; is no less simple than &lt;code&gt;Optional&lt;/code&gt;, which in his great wisdom Papa Swift found fit to force upon everyone. It may be foreign at first, but if it’s a better way of doing things: learn it. Learning “hard” things can make you a better programmer, and can make your software better.&lt;/p&gt;
&lt;p&gt;Finally, the new error handling introduces 5 keywords: &lt;code&gt;throws&lt;/code&gt;, &lt;code&gt;rethrows&lt;/code&gt;, &lt;code&gt;do&lt;/code&gt;, &lt;code&gt;try&lt;/code&gt;, and &lt;code&gt;catch&lt;/code&gt;. I don’t know that I would say the introduction of 5 new keywords is “simple”.&lt;/p&gt;
&lt;h2 id=&quot;result-errortype&quot;&gt;Result&amp;lt;(), ErrorType&amp;gt;&lt;/h2&gt;
&lt;p&gt;One gripe with &lt;code&gt;Result&lt;/code&gt; I see is that sometimes people end up having to type something as &lt;code&gt;Result&amp;lt;(), ErrorType&amp;gt;&lt;/code&gt; because all they really want is a pure Failure. I agree, it can feel a little weird. However, it’s not that hard, it’s rare, and you really only do it when you’re going to &lt;code&gt;map&lt;/code&gt; it to something else later.&lt;/p&gt;
&lt;p&gt;If you find yourself doing this often, I would reexamine your code. Are you really using &lt;code&gt;Result&lt;/code&gt; in the correct places? If all you’re doing is returning whether an operation fails or not, and you don’t care what the error is, return a &lt;code&gt;Bool&lt;/code&gt; instead, or perhaps an &lt;code&gt;ErrorType?&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;advanced-operators&quot;&gt;Advanced Operators&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;Result&lt;/code&gt; brings with it a lot of powerful functional programming ideas and higher order functions. Talking about &lt;code&gt;apply&lt;/code&gt;, &lt;code&gt;map&lt;/code&gt;, and &lt;code&gt;flatMap&lt;/code&gt; is really beyond the scope of this post (plus I don’t want to say the words: Applicative, Functor, or Monad so you keep reading). Perhaps this is where some of the fear of complexity comes from. But they’re really not complex—just new ways of thinking.&lt;/p&gt;
&lt;p&gt;Such higher order functions enable powerful abstractions like JSON parsing a la &lt;a rel=&quot;external&quot; href=&quot;http://github.com/thoughtbot/argo&quot;&gt;Argo&lt;/a&gt;, or my &lt;a rel=&quot;external&quot; href=&quot;http://github.com/jarsen/pipes&quot;&gt;Pipes&lt;/a&gt; library I &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/blog/blob/master/2015/05/23/swift-data-pipelines&quot;&gt;blogged about the other week&lt;/a&gt;. The forward pipe operator makes working with &lt;code&gt;Result&lt;/code&gt; awesome. &lt;strong&gt;The forward pipe operator allows you to compose a data pipeline completely agnostic towards optionals or results.&lt;/strong&gt; And it reads so nice:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let processedText = inputFileName
                    |&amp;gt; escapeInput
                    |&amp;gt; readFile
                    |&amp;gt; processText
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But I’m biased there. :)&lt;/p&gt;
&lt;h2 id=&quot;but-standards&quot;&gt;But, Standards…&lt;/h2&gt;
&lt;p&gt;All this said, I think standards are important. And to me, that’s one of the biggest selling points &lt;code&gt;throws&lt;/code&gt; has. The Swift team has spoken, the Cocoa APIs have been rewritten, and let’s face it: they’re not going back.&lt;/p&gt;
&lt;p&gt;Fortunately, using functions like &lt;a rel=&quot;external&quot; href=&quot;http://github.com/antitypical/Result&quot;&gt;antitypical/Result&lt;/a&gt;’s &lt;code&gt;materialize&lt;/code&gt; and &lt;code&gt;dematerialize&lt;/code&gt; (once a few compiler bugs are worked out) it is possible to switch between thrown errors and and results. So, if you too like &lt;code&gt;Result&lt;/code&gt;, then you’re not up the river with no paddle when working with other APIs.&lt;/p&gt;
&lt;p&gt;That said, there are lots of advantages to sticking close to the herd. That is worth some weight in your judgements.&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I’m new to this, just like everyone else; I’m still playing with it, and seeing how it feels. Sometimes I find myself liking it, others I find myself frustrated. These are just my impressions after a week—I’m sure I have plenty of errors and there are better ways that I missed. Again, comments below or on &lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;twitter&lt;/a&gt; are appreciated.&lt;/p&gt;
&lt;p&gt;Papa Swift and everyone working on the Swift team are doing a &lt;em&gt;tremendous&lt;/em&gt; job. Just because I don’t happen to like the new error handling model as much as I like &lt;code&gt;Result&lt;/code&gt; yet doesn’t mean they made the wrong decision: there are lots of factors to consider, and I guarantee you they thought about it long and hard. I also hope that some more error handling features are on the horizon, like some sort of &lt;code&gt;await&lt;/code&gt; for handling async errors.&lt;/p&gt;
&lt;p&gt;I have yet to shake my greater love for &lt;code&gt;Result&lt;/code&gt;. As such, I think I will be sticking to it for most of my failable code. That said, I’m still playing with &lt;code&gt;throws&lt;/code&gt; and only time will tell.&lt;/p&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>Swift Data Pipelines</title>
        <published>2015-05-23T00:00:00+00:00</published>
        <updated>2015-05-23T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/swift-data-pipelines/"/>
        <id>https://jarsen.engineer/swift-data-pipelines/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/swift-data-pipelines/">&lt;p&gt;The forward pipe operator is an infix operator taken from languages like F# and Elixir. I’ve been working on a &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Swift implementation&lt;/a&gt; that will help clean up data processing pipelines.&lt;/p&gt;
&lt;p&gt;In order to understand the motivation for the forward pipe operator, let’s first look at some regular looking code.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let students = Database.allStudents()
let grades = Grades.forStudents(students)
let curvedGrades = curve(grades, average: 0.6)
let finalGrades = prepareGrades(curvedGrades)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code is simple and has clear variable naming. However, even with clear variable names, it may still be difficult for a reader to immediately realize that each variable declaration’s real purpose is only to hold a value to be used in the next line. These temporary variables introduce noise that may obfuscate the simple flow of data. So why all the temporary variables? Well, the alternative is this:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;prepareGrades(curve(Grades.forStudents(Database.allStudents()), average: 0.6))&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Clearly, the temporary variables are the lesser evil.&lt;/p&gt;
&lt;p&gt;The &lt;code&gt;.&lt;/code&gt; operator allows us to chain class and instance methods together in a clean an consistent manner, but it does not help when we want to chain together method calls between distinct entities or stand-alone functions.&lt;/p&gt;
&lt;h3 id=&quot;meet-the-forward-pipe-operator&quot;&gt;Meet the Forward Pipe Operator&lt;/h3&gt;
&lt;p&gt;The forward pipe simply takes the left hand side of the expression and applies it as the first argument of the function on the right.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;increment(1) // becomes
1 |&amp;gt; increment

divide(5, 10) // becomes
5 |&amp;gt; divide(10)

map(1...100, increment) // becomes
1...100 |&amp;gt; map(increment)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That’s nothing special in and of itself—all it has done is provide a new way to call methods and functions. But look at how it lets us rewrite our original example:&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let finalGrades = Database.allStudents()
                  |&amp;gt; Grades.forStudents
                  |&amp;gt; curve(average: 0.6)
                  |&amp;gt; prepareGrades
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is much cleaner. The forward pipe expresses the series of function calls as a clear data pipeline; it reads like a sequential list of operations to be performed.&lt;/p&gt;
&lt;p&gt;It does’t matter if you’re chaining instance methods, class methods, or functions—the forward pipe chains them all together.&lt;/p&gt;
&lt;h3 id=&quot;optional-pipelines&quot;&gt;Optional Pipelines&lt;/h3&gt;
&lt;p&gt;We’ve seen that the forward pipe can clean up our data pipelines, but one of the stumbling blocks in Swift is learning to deal with one of it’s best features: optionals.&lt;/p&gt;
&lt;p&gt;Optionals show up almost everywhere in your swift code. Want to use a &lt;code&gt;Dictionary&lt;/code&gt;? You’re going to have to deal with optionals.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let animalNoiseMap = [&amp;quot;cow&amp;quot;:&amp;quot;moo&amp;quot;, &amp;quot;dog&amp;quot;:&amp;quot;woof&amp;quot;, &amp;quot;cat&amp;quot;:&amp;quot;meow&amp;quot;]

animalNoiseMap[&amp;quot;dog&amp;quot;]?.uppercaseString // .Some(&amp;quot;WOOF&amp;quot;)
animalNoiseMap[&amp;quot;fox&amp;quot;]?.uppercaseString // .None
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;?&lt;/code&gt; operator is great for chaining together instance methods, but once again as programmers we work with more than just instance methods. Want to count the number of vowels in the animal sounds above?&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;let numberVowelsFox: Int?
if let noise = animalNoiseMap[&amp;quot;fox&amp;quot;] {
    numberVowelsFox = count(filter(noise, isVowel))
}
else {
    numberVowelsFox = nil
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Yikes. That if-let is a lot of work. We could eliminate the else if we wanted to use &lt;code&gt;var&lt;/code&gt; insted of &lt;code&gt;let&lt;/code&gt;, but then we’d lose some safety. If you understand &lt;code&gt;map&lt;/code&gt; you can clean up your code significantly:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;map(animalNoiseMap[&quot;fox&quot;]) { count(filter($0, isVowel)) }&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;But not everyone groks functors.&lt;/p&gt;
&lt;p&gt;Luckily, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes&lt;/a&gt; makes dealing with optionals in your pipelines easy. In fact, you don’t need to anything—just write the same code you would have written without &lt;code&gt;Optional&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;animalNoiseMap[&amp;quot;fox&amp;quot;]
|&amp;gt; filter(isVowel)
|&amp;gt; count // whole expression evaluates to Int?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I might be biased, but that’s pretty wizard.&lt;/p&gt;
&lt;h3 id=&quot;result-pipelines&quot;&gt;Result Pipelines&lt;/h3&gt;
&lt;p&gt;But the forward pipe operator doesn’t stop there, folks! Enjoy using &lt;code&gt;Result&lt;/code&gt;? Just like &lt;code&gt;Optional&lt;/code&gt;s, &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes&lt;/a&gt; supports &lt;code&gt;Result&lt;/code&gt;. (specifically &lt;a rel=&quot;external&quot; href=&quot;https://github.com/antitypical/Result&quot;&gt;antitypical/Result&lt;/a&gt;) Don’t care about &lt;code&gt;Result&lt;/code&gt;? That’s ok, you don’t have to link it in for &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes&lt;/a&gt; to work.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;func escapeInput(string: String) -&amp;gt; String { ... }

func readFile(fileName: String) -&amp;gt; Result&amp;lt;String&amp;gt; { ... }

func processText(string: String) -&amp;gt; String { ... }

let processedText = inputFileName
                    |&amp;gt; escapeInput
                    |&amp;gt; readFile
                    |&amp;gt; processText
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once again, you don’t even have to think about &lt;code&gt;Result&lt;/code&gt;s as you chain these functions together—if result shows up along the way, the whole epxression will evaluate to a result. And if something fails along the way, it will short circuit and you’ll get your &lt;code&gt;.Failure&lt;/code&gt; with the appropriate error message. Neato.&lt;/p&gt;
&lt;h3 id=&quot;keep-your-pipes-clean&quot;&gt;Keep Your Pipes Clean&lt;/h3&gt;
&lt;p&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes&lt;/a&gt; lends itself very well to functional programming ideas. Ideally, keep all the functions and methods in the data processing pipeline pure—i.e., without side effects. Pipes has a bunch of pure implementations and helper functions for &lt;code&gt;Array&lt;/code&gt; and &lt;code&gt;Dictionary&lt;/code&gt; so you can perform pure versions of &lt;code&gt;append&lt;/code&gt;, &lt;code&gt;extend&lt;/code&gt;, &lt;code&gt;remove&lt;/code&gt; and the the likes.&lt;/p&gt;
&lt;h3 id=&quot;ok-i-lied-a-little&quot;&gt;OK. I Lied a Little.&lt;/h3&gt;
&lt;p&gt;I’m actually using some currying to add a little readability to my examples. Au naturel, Pipes expects functions that take more than one argument to provide a tuple on the right hand side where the first item is the function, and the rest are the ordered arguments.&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;// with the trick
5 |&amp;gt; divide(10)
// without the trick
5 |&amp;gt; (divide, 10)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When you use your own functions with more than one argument you’ll need to either use a tuple on the right hand side, or create a function signature where the first argument is curried on the end of the function signature&lt;/p&gt;
&lt;pre&gt;&lt;code data-lang=&quot;Swift&quot;&gt;func divide(numerator: Double, denominator: Double) -&amp;gt; Double {
    return numerator / denominator
}

// the trick
func divide(denominator: Double)(numerator: Double) -&amp;gt; Double {
    return numerator / denominator
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Essentially currying like this turns our functions into functions that take only one argument, so they don’t need to be put inside a tuple on the right hand side.&lt;/p&gt;
&lt;p&gt;Pipes has such curried versions of many standard functions bundled in the framework for your convenience.&lt;/p&gt;
&lt;h3 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;The forward pipe operator is one of the operators offered by &lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes&lt;/a&gt;. It will help clarify data processing pipelines, and automagically deal with &lt;code&gt;Optional&lt;/code&gt;s and &lt;code&gt;Result&lt;/code&gt;s for you. Please feel free to ask questions, and make issues or send me pull requests!&lt;/p&gt;
&lt;h3 id=&quot;resources&quot;&gt;Resources&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a rel=&quot;external&quot; href=&quot;https://github.com/jarsen/Pipes&quot;&gt;Pipes on Github&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;My &lt;a rel=&quot;external&quot; href=&quot;http://www.slideshare.net/jarsen7/pipes-48485417&quot;&gt;Utah Valley Cocoaheads Lighting Talk&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</content>
        
    </entry>
    <entry xml:lang="en">
        <title>No-Magic JSON Parsing with Swift</title>
        <published>2015-05-14T00:00:00+00:00</published>
        <updated>2015-05-14T00:00:00+00:00</updated>
        
        <author>
          <name>Unknown</name>
        </author>
        
        <link rel="alternate" type="text/html" href="https://jarsen.engineer/no-magic-json-parsing-with-swift/"/>
        <id>https://jarsen.engineer/no-magic-json-parsing-with-swift/</id>
        
        <content type="html" xml:base="https://jarsen.engineer/no-magic-json-parsing-with-swift/">&lt;p&gt;Since the beginning, JSON parsing has been a common pain point for many Swift developers. This is largely due to difficulties in dealing with a strict type system (which JSON does not have) and optionals, as well as a lack of a consistent error handling approach.&lt;/p&gt;
&lt;p&gt;Several great JSON parsing libraries have surfaced which avoid the mess of tangled if-lets (a.k.a. the infamous “pyramid of doom”). I really like the approach taken by thoughtbot in their &lt;a rel=&quot;external&quot; href=&quot;https://robots.thoughtbot.com/efficient-json-in-swift-with-functional-concepts-and-generics&quot;&gt;JSON&lt;/a&gt; &lt;a rel=&quot;external&quot; href=&quot;https://robots.thoughtbot.com/real-world-json-parsing-with-swift&quot;&gt;parsing&lt;/a&gt; articles, which ultimately led to their &lt;a rel=&quot;external&quot; href=&quot;https://github.com/thoughtbot/Argo&quot;&gt;Argo&lt;/a&gt; library on github (although I don’t like everything about Argo).&lt;/p&gt;
&lt;p&gt;However, most solutions tend to rely on a lot of magic: the magic of applicatives, functors, and monads; the magic of unfamiliar custom operators; the magic of a complex nested enum structure; the magic of multiple external dependencies.&lt;/p&gt;
&lt;p&gt;Now that swift 2.0 has brought error handling to us, we can implement much less magical JSON parsing. Here is an example of what your JSON parsing code might look like with just a thin error-throwing layer over &lt;code&gt;[String:AnyObject]&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;let-s-get-started&quot;&gt;Let’s Get Started&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;enum JSONError : ErrorType {
    case NoValueForKey(String)
    case TypeMismatch
}

class JSONObject {
    private let dictionary: [String:AnyObject]

    init(dictionary: [String:AnyObject]) {
        self.dictionary = dictionary
    }

    func valueForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; A {
        if let value = self[key] {
            if let _ = value as? NSNull {
                throw JSONError.NoValueForKey(key)
            }
            if let value = value as? A {
                return value
            }
            throw JSONError.TypeMismatch
        }
        throw JSONError.NoValueForKey(key)
    }

    func stringForKey(key: String) throws -&amp;gt; String {
        return try valueForKey(key, type: String.self)
    }

    func intForKey(key: String) throws -&amp;gt; Int {
        return try valueForKey(key, type: Int.self)
    }

    func doubleForKey(key: String) throws -&amp;gt; Double {
        return try valueForKey(key, type: Double.self)
    }

    func arrayForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; [A] {
        return try valueForKey(key, type: [A].self)
    }

    func objectForKey(key: String) throws -&amp;gt; JSONObject {
        let dict = try valueForKey(key, type: [String:AnyObject].self)
        return JSONObject(dictionary: dict)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here we’ve added a bunch of functions that let us get basic things like &lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Int&lt;/code&gt;, and &lt;code&gt;Double&lt;/code&gt; out of our &lt;code&gt;[String:AnyObject]&lt;/code&gt; Pandora’s Box. If we either find a nil or NSNull value, we know the key is bad. And if we find an unexpected type hidden behind the &lt;code&gt;AnyObject&lt;/code&gt; we throw a &lt;code&gt;TypeMismatch&lt;/code&gt; error.&lt;/p&gt;
&lt;p&gt;How does this look in practice? Let’s try it on a simple &lt;code&gt;Person&lt;/code&gt; model.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;struct Person {
    var name: String
    var age: Int
    var height: Double

    static func fromJSON(json: JSONObject) throws -&amp;gt; Person {
        let name = try json.stringForKey(&amp;quot;name&amp;quot;)
        let age = try json.intForKey(&amp;quot;age&amp;quot;)
        let height = try json.doubleForKey(&amp;quot;height&amp;quot;)
        return Person(name: name, age: age, height: height)
    }
}

do {
    let jsonObject: JSONObject = [&amp;quot;name&amp;quot;: &amp;quot;Bob&amp;quot;, &amp;quot;age&amp;quot;: 26, &amp;quot;height&amp;quot;: 5.75]
    let person = try Person.fromJSON(jsonObject)
}
catch let JSONError.NoValueForKey(key) {
    print(&amp;quot;Didn&amp;#39;t find value for key: \(key)&amp;quot;)
}
catch {
    print(&amp;quot;Wrong type&amp;quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Not bad! &lt;em&gt;No pyramid of doom, no external dependencies, you didn’t have to learn a single new operator, and no worrying about the scary words like functor or monad!&lt;/em&gt;&lt;/p&gt;
&lt;h2 id=&quot;optional-json-keys&quot;&gt;Optional JSON Keys&lt;/h2&gt;
&lt;p&gt;Of course, we also want to be able to handle optional values in some cases.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;extension JSONObject {
    private func optionalForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; A? {
        do {
            let value = try valueForKey(key, type: type)
            return value
        }
        catch JSONError.NoValueForKey {
            return nil
        }
        catch {
            throw JSONError.TypeMismatch
        }
    }

    func stringOptionalForKey(key: String) throws -&amp;gt; String? {
        return try optionalForKey(key, type: String.self)
    }

    func intOptionalForKey(key: String) throws -&amp;gt; Int? {
        return try optionalForKey(key, type: Int.self)
    }

    func doubleOptionalForKey(key: String) throws -&amp;gt; Double? {
        return try optionalForKey(key, type: Double.self)
    }

    func arrayOptionalForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; [A]? {
        return try optionalForKey(key, type: [A].self)
    }

    func objectOptionalForKey(key: String) throws -&amp;gt; JSONObject? {
        let dict = try optionalForKey(key, type: [String:AnyObject].self)
        return dict.map(JSONObject.init)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Awesome. Now we have some pretty basic JSON handling in place, but honestly it’s probably most of what you will ever need.&lt;/p&gt;
&lt;h2 id=&quot;key-paths&quot;&gt;Key Paths&lt;/h2&gt;
&lt;p&gt;There’s one more thing that might be nice though: handling key paths. So, let’s rewrite our &lt;code&gt;valueForKey&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;func valueForKey&amp;lt;A&amp;gt;(key: String, type: A.Type) throws -&amp;gt; A {
    let pathComponents = key.componentsSeparatedByString(&amp;quot;.&amp;quot;)

    var accumulator: Any = dictionary

    for component in pathComponents {
        if let dict = accumulator as? [String:AnyObject] {
            if let value = dict[component] {
                accumulator = value
                continue
            }
        }
        throw JSONError.NoValueForKey(key)
    }

    if let value = accumulator as? A {
        return value
    }
    else {
        throw JSONError.TypeMismatch
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can do this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;let street = try json.stringForKey(&amp;quot;address.street&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And, because we implemented our &lt;code&gt;optionalForKey&lt;/code&gt; on top of &lt;code&gt;valueForKey&lt;/code&gt;, everything else will just keep working.&lt;/p&gt;
&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I think this JSON code is quite nice, and easy for anyone to understand without having their mind blown. Even though &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/result-vs-throws/&quot;&gt;I went a little caremad the other week about Result&lt;/a&gt;, I like how this code turned out better than my old &lt;code&gt;Result&lt;/code&gt; based JSON parsing: it’s easier to explain to others, and it’s much easier on the compiler, which saves you time when trying to figure out what is wrong. It is also more idiomatic.&lt;/p&gt;
&lt;p&gt;I’m sure there are some cool ways to improve this code, I’d love to hear your thoughts! Please leave a comment or give me a shout on &lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;twitter&lt;/a&gt;(&lt;a rel=&quot;external&quot; href=&quot;http://twitter.com/jarsen&quot;&gt;@jarsen&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;The Swift 2.0 beta2 brings &lt;em&gt;extensions to generic types&lt;/em&gt;. Generic types extensions allow us to add functionality to things like &lt;code&gt;Array&lt;/code&gt; and &lt;code&gt;Dictionary&lt;/code&gt;in specific cases. Unfortunately for the moment it seems that you can’t give it specific types for Key/Value, only protocol conformance. If we could specify specific types, we could extend &lt;code&gt;[String:AnyObject]&lt;/code&gt; and typealias it to &lt;code&gt;JSONObject&lt;/code&gt; instead of having a wrapper class.&lt;/p&gt;
&lt;p&gt;And here’s &lt;a rel=&quot;external&quot; href=&quot;https://gist.github.com/jarsen/2b0913111c0427642c41&quot;&gt;the final code&lt;/a&gt; all in one gist.&lt;/p&gt;
&lt;p&gt;Update: Be sure to check out &lt;a rel=&quot;external&quot; href=&quot;https://jarsen.engineer/no-magic-json-parsing-with-swift-part-ii/&quot;&gt;Part 2&lt;/a&gt;, in which we make the code even better by relying more heavily on type inference.&lt;/p&gt;
</content>
        
    </entry>
</feed>
