Every Skill is a Liability

I think the hardest skill to learn in programming is recognizing when you’re not communicating enough.

We’re often the first people to spot change, to feel the rumble of trouble over the horizon, but we’re also inclined to reflect on approaching danger internally, as a puzzle to solve without assistance, rather than externally by sharing the burden with our team.

Every skill is also a liability. Programming is anticipating the future and solving problems before anyone else has to know that a problem would have occurred. Every day we practice that skill and get better at it, but sometimes the right call is to resist the urge to problem solve, to instead simply report on what I’ve seen, to let my team know that a problem is coming, and then wait for the team to collaboratively decide who’ll solve the problem, and how, and when.

I wish I knew a secret that unlocks this ability without effort, but I don’t. The only way I know of is to dedicate some utility thread of my mind that periodically checks in to see if there’s anything that pattern-matches against mistakes I’ve made in the past, and quickly course correct by communicating with the right people.

|  21 Oct 2020




Dagmar Chili Pitas: The Official Unofficial Mirror

“…and with the microscopic diligence of a Leuwenhoeck submits to the inspection of a shivering world ninety-six facsimiles of magnified Arctic snow crystals.”

{}oe|e|ep[]

Have you ever heard of Dagmar Chili Pitas? It’s twenty years old. It, sadly, went offline a few years back. It is, I can say without hesitation or reservation, the greatest website ever made, at least in my own flawed estimation.

I have no idea who made it. Or why. Or what substances they were under the influence of. It doesn’t matter, I enjoy the mystery. If I had to pick a back story, it would be: Thomas Pynchon got bored and spent two years working on an anonymous website whenever he was drunk.

Although the site is available at the Internet Wayback Machine, I have been anxious, whenever I think about it, that the site will eventually get lost or purged from there. Thanks to this very, very helpful tool, I was able to easily download the entire site and make it available as the Official Unofficial Mirror on my site. Enjoy your symptom!

{}oe|e|ep[]

|  28 May 2020




When Should I Use @State, @Binding, @ObservedObject, @EnvironmentObject, or @Environment?

SwiftUI introduced a laundry list of new property wrappers that your code can use to bridge the gap between program state and your views:

 @State
 @Binding
 @ObservedObject
 @EnvironmentObject
 @Environment

That’s only a partial list. There are other property wrappers for Core Data fetch requests and gesture recognizers. But this post isn’t about these other wrappers. Unlike the wrappers above, the use cases for @FetchRequest and @GestureState are unambiguous, whereas it can be very confusing how to decide when to use a @State versus @Binding, or @ObservedObject versus @EnvironmentObject, etc.

This post is an attempt to define in simple, repeatable terms when each wrapper is an appropriate choice. There’s a risk I’m being overly prescriptive here, but I’ve gotten some decent mileage from these rules already. Besides, being overly prescriptive is a time-honored programmer blog tradition, so I’m in good albeit occasionally obnoxious company.

All of the code samples that follow are available in this GitHub repo. Note for posterity: this post was written using Swift 5 and iOS 13.

Cheat Sheet

  1. Use @State when your view needs to mutate one of its own properties.

  2. Use @Binding when your view needs to mutate a property owned by an ancestor view, or owned by an observable object that an ancestor has a reference to.

  3. Use @ObservedObject when your view is dependent on an observable object that it can create itself, or that can be passed into that view’s initializer.

  4. Use @EnvironmentObject when it would be too cumbersome to pass an observable object through all the initializers of all your view’s ancestors.

  5. Use @Environment when your view is dependent on a type that cannot conform to ObservableObject.

  6. Also use @Environment when your views are dependent upon more than one instance of the same type, as long as that type does not need to be used as an observable object.

  7. If your view needs more than one instance of the same observable object class, you are out of luck. You cannot use @EnvironmentObject nor @Environment to resolve this issue. (There is a hacky workaround, though, at the bottom of this post).

Your view needs a @State property if…

…it needs read/write access to one of its own properties for private use.

A helpful metaphor is the isHighlighted property on UIButton. Other objects don’t need to know when a button is highlighted, nor do they need write access to that property. If you were implementing a from-scratch button in SwiftUI, your isHighlighted property would be a good candidate for an @State wrapper.

struct CustomButton<Label>: View where Label : View {
    let action: () -> Void
    let label: () -> Label

    /// it needs read/write access to one of 
    /// its own properties for private use
    @State private var isHighlighted = false
}


…it needs to provide read/write access of one of its properties to a descendant view.

Your view does this by passing the projectedValue of the @State-wrapped property, which is a Binding to that value1. A good example of this is SwiftUI.Alert. Your view is responsible for showing the alert by changing the value of some @State, like an isPresentingAlert boolean property. But your view can’t dismiss that alert itself, nor does the alert have any knowledge of the view that presented it. This dilemma is resolved by a Binding. Your view passes the Alert a Binding to its isPresentingAlert property by using the compiler-generated property self.$isPresentingAlert, which is syntax sugar for the @State wrapper’s projected value. The .alert(isPresented:content:) modifier takes in that binding, which is later used by the alert to set isPresentingAlert back to false, in effect allowing the alert to dismiss itself.

struct MyView: View {

    /// it needs to provide read/write access of 
    /// one of its properties to a descendant view
    @State var isPresentingAlert = false

    var body: some View {
        Button(action: {
            self.isPresentingAlert = true
        }, label: {
            Text("Present an Alert")
        })
        .alert(isPresented: $isPresentingAlert) {
            Alert(title: Text("Alert!"))
        }
    }
}


Your view needs a @Binding property if…

…it needs read/write access to a State-wrapped property of an ancestor view

This is the reverse perspective of the alert problem described above. If your view is like an Alert, where it’s dependent upon a value owned by an ancestor and, crucially, needs mutable access to that value, then your view needs a @Binding to that value.

struct MyView: View {
    @State var isPresentingAlert = false

    var body: some View {
        Button(action: {
            self.isPresentingAlert = true
        }, label: {
            Text("Present an Alert")
        })
        .customAlert(isPresented: $isPresentingAlert) {
            CustomAlertView(title: Text("Alert!"))
        }
    }
}

struct CustomAlertView: View {
    let title: Text
    
    /// it needs read/write access to a State-
    /// wrapped property of an ancestor view
    @Binding var isBeingPresented: Bool
}


…it needs read/write access to a property of an object conforming to ObservableObject but the reference to that object is owned by an ancestor.

Boy that’s a mouthful. In this situation, there are three things:

  1. an observable object
  2. some ancestor view that has an @-Something wrapper referencing that object
  3. your view, which is a descendant of #2.

Your view needs to have read/write access to some member of that observable object, but your view does not (and should not) have access to that observable object. Your view will then define a @Binding property for that value, which the ancestor view will provide when your view is initialized. A good example of this is any reusable input view, like a picker or a text field. A text field needs to be able to have read/write access to some String property on another object, but the text field should not have a tight coupling to that particular object. Instead, the text field’s @Binding property will provide read/write access to the String property without exposing that property directly to the text field.

struct MyView: View {
    @ObservedObject var person = Person()

    var body: some View {
        NamePicker(name: $person.name)
    }
}

struct NamePicker: View {

    /// it needs read/write access to a property 
    /// of an observable object owned by an ancestor
    @Binding var name: String

    var body: some View {
        CustomButton(action: {
            self.name = names.randomElement()!
        }, label: {
            Text(self.name)
        })
    }
}


Your view needs an @ObservedObject property if…

…it is dependent on an observable object that it can instantiate itself.

Imagine you have a view that displays a list of items pulled down from a web service. SwiftUI views are transient, discardable value types. They’re good for displaying content, but not appropriate for doing the work of making web service requests. Besides, you shouldn’t be mixing user interface code with other tasks as that would violate the Single Responsibility Principle. Instead your view might offload those responsibilities to an object that can coordinate the tasks needed to make a request, parse the response, and map the response to user interface model values. Your view would own a reference to that object by way of an @ObservedObject wrapper.

struct MyView: View {

    /// it is dependent on an object that it 
    /// can instantiate itself
    @ObservedObject var veggieFetcher = VegetableFetcher()

    var body: some View {
        List(veggieFetcher.veggies) {
            Text($0.name)
        }.onAppear {
            self.veggieFetcher.fetch()
        }
    }
}


…it is dependent on a reference type object that can easily be passed to that view’s initializer.

This scenario is nearly identical to the previous scenario, except that some other object besides your view is responsible for initializing and configuring the observable object. This might be the case if some UIKit code is responsible for presenting your SwiftUI view, especially if the observable object can’t be constructed without references to other dependencies that your SwiftUI view cannot (or should not) have access to.

struct MyView: View {

    /// it is dependent on an object that can
    /// easily be passed to its initializer
    @ObservedObject var dessertFetcher: DessertFetcher

    var body: some View {
        List(dessertFetcher.desserts) {
            Text($0.name)
        }.onAppear {
            self.dessertFetcher.fetch()
        }
    }
}

extension UIViewController {

    func observedObjectExampleTwo() -> UIViewController {
        let fetcher = DessertFetcher(preferences: .init(toleratesMint: false))
        let view = ObservedObjectExampleTwo(dessertFetcher: fetcher)
        let host = UIHostingController(rootView: view)
        return host
    }

}


Your view needs an @EnvironmentObject property if…

…it would be too cumbersome to pass that observed object through all the initializers of all your view’s ancestors.

Let’s return to the second example from the @ObservedObject section above, where an observable object is needed to carry out some tasks on behalf of your view, but your view is unable to initialize that object by itself. But let’s now imagine that your view is not a root view, but a descendant view that is deeply nested within many ancestor views. If none of the ancestors need the observed object, it would be painfully awkward to require every view in that chain of views to include the observed object in their initializer arguments, just so the one descendant view has access to it. Instead, you can provide that value indirectly by tucking it into the SwiftUI environment around your view. Your view can access that environment instance via the @EnvironmentObject wrapper. Note that once the @EnvironmentObject’s value is resolved, this use case is functionally identical to using an object wrapped in @ObservedObject.

struct SomeChildView: View {

    /// it would be too cumbersome to pass that 
    /// observed object through all the initializers 
    /// of all your view's ancestors
    @EnvironmentObject var veggieFetcher: VegetableFetcher

    var body: some View {
        List(veggieFetcher.veggies) {
            Text($0.name)
        }.onAppear {
            self.veggieFetcher.fetch()
        }
    }
}

struct SomeParentView: View {
    var body: some View {
        SomeChildView()
    }
}

struct SomeGrandparentView: View {
    var body: some View {
        SomeParentView()
    }
}


Your view needs an @Environment property if…

…it is dependent on a type that cannot conform to ObservableObject.

Sometimes your view will have a dependency on something that cannot conform to ObservableObject, but you wish it could because it’s too cumbersome to pass it as a initializer argument. There are a number of reasons why a dependency might not be able to conform to ObservableObject:

In cases like these, your view would instead use the @Environment wrapper to obtain the required dependency. This requires some boilerplate to accomplish correctly.

struct MyView: View {

    /// it is dependent on a type that cannot 
    /// conform to ObservableObject
    @Environment(\.theme) var theme: Theme

    var body: some View {
        Text("Me and my dad make models of clipper ships.")
            .foregroundColor(theme.foregroundColor)
            .background(theme.backgroundColor)
    }
}

// MARK: - Dependencies

protocol Theme {
    var foregroundColor: Color { get }
    var backgroundColor: Color { get }
}

struct PinkTheme: Theme {
    var foregroundColor: Color { .white }
    var backgroundColor: Color { .pink }
}

// MARK: - Environment Boilerplate

struct ThemeKey: EnvironmentKey {
    static var defaultValue: Theme {
        return PinkTheme()
    }
}

extension EnvironmentValues {
    var theme: Theme {
        get { return self[ThemeKey.self]  }
        set { self[ThemeKey.self] = newValue }
    }
}


…your views are dependent upon more than one instance of the same type, as long as that type does not need to be used as an observable object.

Since @EnvironmentObject only supports one instance per type, that idea is a non-starter. Instead if you need to register multiple instances of a given type using per-instance key paths, then you will need to use @Environment so that your views’ properties can specify their desired keypath.

struct MyView: View {
    @Environment(\.positiveTheme) var positiveTheme: Theme
    @Environment(\.negativeTheme) var negativeTheme: Theme

    var body: some View {
        VStack {
            Text("Positive")
                .foregroundColor(positiveTheme.foregroundColor)
                .background(positiveTheme.backgroundColor)
            Text("Negative")
                .foregroundColor(negativeTheme.foregroundColor)
                .background(negativeTheme.backgroundColor)
        }
    }
}

// MARK: - Dependencies

struct PositiveTheme: Theme {
    var foregroundColor: Color { .white }
    var backgroundColor: Color { .green }
}

struct NegativeTheme: Theme {
    var foregroundColor: Color { .white }
    var backgroundColor: Color { .red }
}

// MARK: - Environment Boilerplate

struct PositiveThemeKey: EnvironmentKey {
    static var defaultValue: Theme {
        return PositiveTheme()
    }
}

struct NegativeThemeKey: EnvironmentKey {
    static var defaultValue: Theme {
        return NegativeTheme()
    }
}

extension EnvironmentValues {
    var positiveTheme: Theme {
        get { return self[PositiveThemeKey.self]  }
        set { self[PositiveThemeKey.self] = newValue }
    }

    var negativeTheme: Theme {
        get { return self[NegativeThemeKey.self]  }
        set { self[NegativeThemeKey.self] = newValue }
    }
}


Workaround for Multiple Instances of an EnvironmentObject

While it is technically possible to register an observable object using the .environment() modifier, changes to that object’s @Published properties will not trigger an invalidation or update of your view. Only @EnvironmentObject and @ObservedObject provide that. Unless something changes in the upcoming iOS 14 APIs, there is only one recourse I have found: a hacky but effective workaround using a custom property wrapper.

With this set up in place, your view can observe multiple objects of the same class:

struct MyView: View {

    @DistinctEnvironmentObject(\.posts) var postsService: Microservice
    @DistinctEnvironmentObject(\.users) var usersService: Microservice
    @DistinctEnvironmentObject(\.channels) var channelsService: Microservice

    var body: some View {
        Form {
            Section(header: Text("Posts")) {
                List(postsService.content, id: \.self) {
                    Text($0)
                }
            }
            Section(header: Text("Users")) {
                List(usersService.content, id: \.self) {
                    Text($0)
                }
            }
            Section(header: Text("Channels")) {
                List(channelsService.content, id: \.self) {
                    Text($0)
                }
            }
        }.onAppear(perform: fetchContent)
    }
}

// MARK: - Property Wrapper To Make This All Work

@propertyWrapper
struct DistinctEnvironmentObject<Wrapped>: DynamicProperty where Wrapped : ObservableObject {
    var wrappedValue: Wrapped { _wrapped }
    @ObservedObject private var _wrapped: Wrapped

    init(_ keypath: KeyPath<EnvironmentValues, Wrapped>) {
        _wrapped = Environment<Wrapped>(keypath).wrappedValue
    }
}

// MARK: - Wherever You Create Your View Hierarchy

MyView()
    .environment(\.posts, Microservice.posts)
    .environment(\.users, Microservice.users)
    .environment(\.channels, Microservice.channels)
    // each of these has a dedicated EnvironmentKey


Sample Code

All of the code above is available in an executable form here.

  1. Every @propertyWrapper-conforming type has the option of providing a projectedValue property. It is up to each implementation to decide the type of the value. In the case of the State<T> struct, the projected value is a Binding<T>. It behoves you, any time you’re using a new property wrapper, to jump to its generated interface to discover in detail what it’s projected value is. 

|  7 May 2020




Addicted to Jesus

I was pushing forty before I was able to articulate this:

Religion and philosophy are bad for me.

Not “are bad”, but “are bad for me”, specifically me, in the way the same liquor that drags one person down passes quietly over the next. I don’t drink. I’ve another poison. I’m fatally attracted to unanswerable questions. I’m always slouching toward a downward spiral of obsessive philosophical and religious thought, trying to resolve irresolvable thought problems, torturing myself over that failure by trying ever harder, until I develop old-fashioned clinical depression. From my teenage years onward, throughout all of my twenties, I was transfixed by big, vexing questions. The usual suspects: the problem of evil, the existence of god, blah blah blahd nauseam. But not in a casual way. Never in a pot-fueled like, what if we’re all in a simulation, man reverie. This pain cut deep, pervaded every moment of my life. I tore apart books, filled journals with angsty blather, changed jobs and majors like clothes, looking for answers to questions that have none. I was addicted.


"The Upper Zoom" by @MythAddict.

That notion — those words even: religion and philosophy are bad for me — is not a thing I’ve ever heard before. It’s not a part of any tradition I know of. There are no shortage of true unbelievers who’ll blame the human condition on religion1. This ain’t that. I’m saying that they’re bad for me, and it doesn’t matter whether they’re a cause of or the cure for society’s ills. I can’t safely be around them. I was raised in an evangelical subculture that was profoundly committed to a certain view of right living, often harmful, sometimes heart-breakingly beautiful, spotlit by a few passages of truly moving literature. One thing evangelicals and atheists and whateverists of all stripes have in common is the assumption that the nuts n’ bolts of religio-philosophical thought are value-neutral. Abstracted from any conclusions drawn, the practical mechanics of the thing aren’t considered a threat. “Assumption” is too strong a word. It’s simply not under consideration.

When I finally figured out that I am not like other people, that sustained religious and philosophical thinking poses a perpetual threat to my mental health, it was liberating. In practical terms, I was able to spot the warning signs and put myself out of harm’s way. Put down that book, jackass, go do something grounded.

I can’t say for sure, but I attribute at least some of my predicament to my evangelical roots. That contradictory tension of “you must believe this but you had better not actually live this,” the impossible sacrifice we were all expected to recite but never required to follow, — so many contradictions — it’s inevitable that it’s going to churn out some kids like me, kids who go into adulthood feeling like they have no home, can’t go back to the bullshittery of the past, but are still addicted to Jesus.

  1. Faith traditions are powerful motivators both for good and for evil. Don’t @-me with your religion-is-the-cause-of-evil bullshit. 

|  1 Apr 2020




Dr. Jekyll and Mr. Tumblr

Yesterday morning this tweet from Mark Sands showed up in my mentions:

@jaredsinclair Looks like Tumblr deleted your blog. Any hope for reviving it?

Up until yesterday, my blog was hosted via Tumblr with a CNAME redirect from blog.jaredsinclair.com to the appropriate Tumblr domain. I set everything up seven or eight years ago, and it had worked fine all that time. I tried visiting the site and, like Mark said, the blog was gone. I got the Tumblr equivalent of a 404 instead of my blog. Next I tried logging into my Tumblr account to figure out what was wrong. Here’s what I saw:

W. T. Fuck.

I thought perhaps I’d missed a warning from Tumblr, but I had no recollection of receiving anything. I double and triple checked all my email accounts. Nada. There wasn’t anything from Tumblr since one day in March when I used a magic link to sign into my account rather than username and password. Nothing archived, nothing in spam. Without warning Tumblr had terminated my account for no discernable reason. I tried logging in from a desktop browser to be sure there wasn’t some mobile-rendering goof. Same thing. Your account has been terminated in classic Tumblr chunky white.

Wait, back up.

Ever since I slung screwdrivers around repairing Macs at a third-party Mac store, I’ve lived in mortal fear of losing data. Practically every day we had to tell somebody your baby pictures, your wedding pictures, your dissertation: all gone. There’s only so many times you can watch folks sob over the consequences of a spilled cup of coffee before you’re sobbing with them. For the most part, my backup strategy has been comfortably paranoid:

Yet my blog was the one corner of my digital life where I had gotten lazy. I didn’t have a backup of my posts anywhere, only scattered draft versions in a Dropbox folder. The canonical versions of all my blog posts were whatever Tumblr had saved for my account. The Tumblr versions had lots of small edits and corrections that weren’t saved anywhere, even if there was a draft copy in Dropbox. Now suddenly, everything that Tumblr had was gone.

Moving to Jekyll

I used the spartan contact form to ask Tumblr why my account was terminated. But rather than wait for a response that might never come, I decided it was past time to bring my blogging setup in line with the rest of my backup paranoia.

I decided to move everything over to Jekyll, backed by a comprehensive GitHub repository. I’ve had a Media Temple account for years and have been really happy with them. I knew once I figured out how to actually use Jekyll in a comfortable way, my Media Temple Grid Service would be able to host the static files easily. Why Jekyll? The short answer is that it’s used by GitHub Pages. In a sea of alternatives, I’m content to follow the smart folks at GitHub wherever they go.

If you’re reasonably comfortable with basic web programming, and know enough about the shell to get yourself in trouble, using Jekyll isn’t so bad. I got a proof-of-concept site up and running pretty quickly. Since Media Temple is also the domain registrar for jaredsinclair.com, it was easy to replace the Tumblr CNAME record for blog.jaredsinclair.com with an A record pointing to the same IP address as jaredsinclair.com (this was a necessary part of ensuring that old blog post links resolved to their new Jekyll permalink). Within hours, anyone that wanted to visit this blog was able to see something here. The real problem was recovering all my old posts.

Recovering all my old posts

Felix Lapalme recommended a command-line tool that downloads an entire site’s content from the Internet Wayback Machine. Before anything else could go wrong, I immediately ran that tool, which worked as advertised (isn’t it great when things work like they say on the tin?). This archive was missing a lot of posts, particularly my more recent stuff, but something was better than nothing. I was pretty worn out from getting Jekyll set up so I went to bed, putting off figuring out how to transform this backup into something formatted for Jekyll.

When I woke up this morning, I had a pleasant email in my inbox. It wasn’t from Tumblr, natch. It was from Ben Ubois, the founder of Feedbin, the RSS aggregator:

Hey Jared,

I saw on Twitter about Tumblr closing your account. That sounds lame!

Feedbin has posts from your blog going back to 2012. I’ve attached all 234 of them as JSON.

The structure looks like:

{ title: “Title”, url: …

Hope it helps!

Thanks to Ben, I now had everything I needed. Unlike the Internet Archive backup, in which each post would need to be heavily transformed to unsleeve the post content from all the page chrome that got captured with each crawl, the RSS backup was already free of such chrome. Better still, the JSON data structure would make it possible to automate the capture of the critical metadata for each page, namely the title and published date.

Using the Swift Package Manager, I made a quick n’ dirty utility that transforms a JSON-encoded file of Feedbin posts into a directory of HTML files formatted for Jekyll. After running this utility, all I had to do to republish all my old content (in correct chronological order, too) was to copy those HTML files into the _posts directory in my Jekyll project, run jekyll build, and upload them to the right directory on my Media Temple server.

The one truly unfortunate downside of moving to Jekyll is that all existing links to my Tumblr-hosted blog are now defunct. Tumblr blog post URL paths take one of the following forms:

/post/123456789
/post/123456789/title-slug-for-post
/post/123456789/title-slug-for-post/index.html

Whereas Jekyll links use a date-based path:

/2019/04/07/title-slug-for-post.html

At least that’s the Jekyll default. I like this default and have decided to keep it and fix broken Tumblr links on a case-by-case basis. For the posts that I care about most (the ones that at one time or another got a lot of traffic, like this one or this one), I’ve updated the .htaccess file on my Media Temple server with redirects like this:

RedirectMatch 301 /post/97655887470.${html`*`}$ /2014/09/16/good-design-is-about-process-not.html

I don’t know if I’ll do it this way forever (there might be a better way that Jekyll supports), but this was effective and took only a few minutes.

For all the posts that I haven’t redirected, I’ve updated the 404 with a blurb about what happened to my blog this weekend, with a link to my archive page.

Looking ahead

To make day-to-day life easier going forward, I added a script to my Jekyll project that uses rsync to upload the _sites directory to my Media Temple server, authenticated with ssh. From the root directory of my Jekyll repo, I can just run publish.sh to rebuild and upload everything. I’m continually impressed by how efficient rsync is. Small changes to the site, like correcting a typo in some markup, are published in seconds.

Update: Tumblr replies

By the time I finished writing this post, I received a reply from Tumblr:

Hello,

We’ve restored your account.

Thank you for bringing this problem to our attention. We’re sorry that it occurred, and we’ll do our best to make sure that it doesn’t happen again.

You should now be able to log in just fine with your email address and password.

Please let me know if there’s anything else I can help you with!

Drew

Community Manager

Too little, too late, Drew. I hope Tumblr understands that I simply cannot trust them anymore. I’m grateful that they responded to my contact request and that my account has been reopened, but it’s unacceptable that a years-old account still in good standing can be terminated without any advance warning or preventative recourse. This weekend’s debacle is a textbook case for why folks should own their own data. It’s also a good reminder that no single service provider can be wholly trusted.

If something isn’t backed up in more than one place, it’s not backed up at all.

|  7 Apr 2019




Please Pardon Our Mess

Since Tumblr decided to terminate my account without warning or explanation, I’ve decided it’s past time to move my blog to something under my control. Unfortunately I don’t have a backup of my old posts ready to go. In lieu of anything better, I’ll fill my Jekyll queue with my favorite lorem ipsum alternative, the “Clipper Ships” poem from Little Man Tate.

|  6 Apr 2019




Clipper Ships

Me and my dad make models of clipper ships. Clipper ships sail on the ocean. Clipper ships never sail on rivers or lakes. I like clipper ships because they are fast. Clipper ships have lots of sails and are made of wood.

(Matt Montini)

|  6 Apr 2019




Unit Testing is Easier Than You Think

I am ashamed to admit how many years I avoided incorporating unit tests into my iOS projects. The simple truth is that I was afraid of what I didn’t know. I don’t have a CS degree. I never studied programming formally. The terminology itself is intimidating. What is a unit? How do I know if my app has units in it? What does it mean to test them? Not understanding what they are or even what good unit tests look like, my anxiety filled the gaps in my knowledge with frightening mental imagery.

After struggling with them for a few years, and after finding the occasional inspiring tech talk, I have come to understand that not only is unit testing not scary, but in fact good unit testing is surprisingly easy. The simplest and best unit test looks exactly like this:

XCTAssertEqual(actual, expected)

That’s it. A straightforward comparison of some unknown value against what you expect that value to be. The goal with unit testing is to write simple, direct assertions like that one. Every other choice you make is just a means to that end. To see how, first let’s widen our field of vision to the code surrounding that assertion:

let input = ... // hard-coded inputs
let actual = SomeWidget().doSomething(with: input)
let expected = ... // hard-coded output
XCTAssertEqual(actual, expected)

A good unit test answers the question, “When I pass something into this other thing, what value do I get out?” Answering that question is easier if your input and expected output are written using simple, hard-coded constants. Unlike writing regular code, when you’re writing a unit test, using hard-coded data is mandatory. Swift literals are your friends. You jot down some hard-coded input values, and also a hard-coded expected output value. Sandwiched in the middle is the behavior you’re testing. Imagine if you wanted to test String.lowercased():

let input = "unIT TesTING Is NoT SO BAD"
let actual = input.lowercased()
let expected = "unit testing is not so bad"
XCTAssertEqual(actual, expected)

‘m calling a method called lowercased(). I’m passing a string into it (input) and I’m getting another string out of it (actual). I hope that the returned value is the same as another string (expected). By using string literals (instead of, say, dynamic values obtained from a networked resource), you’ve eliminated unpredictability from the test. There’s now only a single variable (in the algebraic sense) at play, the behavior of lowercased(). This is a good unit test.

This may strike you as overly simplistic, but I assure you it isn’t. Even the most complex behaviors in your app can be tested in this manner. If you have some dark corner of your app that you wish had unit tests, start by building a mental model of the problem that’s oriented towards that XCTAssert assertion you’re going to write. Say you want to add unit tests to some code that interacts with a web service. You have a class that looks like this:

class APIManagerHamburgerHelper {
    func getUser(withId id: String, completion: @escaping (Result<user apierror>) -> Void) {...}
}

Right now there’s no way to unit test that getUser method, not in the way that I’m advocating. There are several things hindering you. The method has no return value. It requires making a roundtrip request to an actual server. There are many jobs hiding inside the implementation of that method: building a URL request, evaluating a URLSession response envelope (response, data, and error), decoding JSON-encoded data, mapping any error along the way to your APIError type. Each of these hidden jobs is itself something that needs unit test coverage. To test them, you’ll need to expose those jobs in a form that is “shaped” like the .lowercased() example above. There’s no one single way to do this, but here’s a rough example. You can break out these jobs into a single-purpose utilities:

struct URLRequestBuilder {
    func getUserRequest(userId: String) -> URLRequest
}

struct URLResponseEnvelopeEvaluator {
    struct Success: Equatable {
        let response: HTTPURLResponse
        let data: Data
    }

    struct Failure: Swift.Error, Equatable {
        let response: URLResponse?
        let error: APIError?
    }

    typealias Result = Result<Success, Failure>

    func evaluate(data: Data?, response: URLResponse?, error: Error?) -> Result {...}
}

struct User: Decodable {
    let id: String
    let name: String
    let displayName: String
}

The knowledge of how to implement each of these jobs (building requests, evaluating responses, parsing data) has been extracted out of the untestable getUser method and into discrete types that lend themselves to straightforward unit tests. Testing the request builder might look something like this:

let id = "abc"
let actual = URLRequestBuilder().buildGetUserProfileRequest(userId: id)
let expected: URLRequest = {
    let url = URL(string: "https://baseurl.com/user/\(id)")!
    var request = URLRequest(url: url)
    request.addValue("foo", forHTTPHeaderField: "Bar")
    return request
}()
XCTAssertEqual(actual, expected)

Note how the input value and expected output value are all written using hard-coded constants as possible. As with all good unit tests, we pass hard-coded input into the member being tested, and compare the actual output against a hard-coded expected output value. Because inputs and expected outputs are hard-coded, we can write unit tests to cover any imaginable scenario. Perhaps you want to test a specific error pathway, what happens when the web service replies with a 401 status code. We set up the input values to closely reflect what a URLSession would actually present to the developer in a completion block:

let data: Data? = nil
let response = HTTPURLResponse(
    url: URL(string: "https://baseurl.com/user/abc")!,
    statusCode: 401,
    httpVersion: "1.0",
    headerFields: nil
)
let error = NSError(
    domain: NSURLErrorDomain,
    code: 401,
    userInfo: ["foo": "bar"]
)

Then we use those values as inputs to the method being unit tested, as well as to the expected result (where applicable):

let actual = URLResponseEnvelopeEvaluator().evaluate(
    data: data,
    response: response,
    error: error
)
let expected: URLResponseEnvelopeEvaluator.Result = .failure(Failure(
    response: response,
    error: .authenticationError401(error)
))
XCTAssertEqual(actual, expected)

n all the foregoing examples, no matter how hairy the subject matter, all the unit tests take the same shape:

This simple, repeatable pattern is what makes good unit tests “easy”. The hardest part isn’t writing the tests themselves, but rather structuring your code so that the behaviors are unit-testable in the first place. Doing that takes experience and much trial-and-error. That effort will come more easily to you once you have internalized the essential simplicity of a good unit test.

If you would like to learn more about refactoring your code for unit testing, I have a screencast on Big Nerd Ranch’s The Frontier with some live coding examples that you may find helpful.

|  1 Apr 2019




PSA: Please Don’t Double Space Between Sentences

In the nineteenth century, which was a dark and inflationary age in typography and type design, many compositors were encouraged to stuff extra space between sentences. Generations of twentieth-century typists were then taught to do the same, by hitting the spacebar twice after every period. Your typing as well as your typesetting will benefit from unlearning this quaint Victorian habit. As a general rule, no more than a single space is required after a period, a colon, or any other mark of punctuation.

~ Robert Bringhurst, The Elements of Typographic Style

|  27 Mar 2019




Think Twice Before Downgrading to a Free GitHub Account

Today I learned that if you downgrade from a paid to a free GitHub account, you’ll lose any branch protection rules you’ve added to your private repositories. It’s my fault for not reading the fine print more carefully, but still – it would have been helpful for them to toss up an alert or something that makes it obvious that by downgrading to the free tier there will be destructive side effects on features you probably set-and-forgot years ago and have taken for granted. I live in mortal fear of making a dumb mistake and losing irreplaceable source code. Downgrading to free account is, in my estimation, Step One on the path to me making such a mistake.

Please note also that when upgrading back to a Pro account, any branch protection rules you had before were permanently deleted when you downgraded to the free tier. They will all have to be recreated from scratch. So if you were considering downgrading to a free GitHub account, I don’t recommend doing so if you use private repositories for code that you care about. And if you have already downgraded to a free account, double check that you can live with the consequences of accidentally force pushing or deleting an important branch.

Update: I received a friendly reply from GitHub CEO Nat Friedman. :)

|  24 Mar 2019