Why I am Not Moving

“Janie, why are you still in Madison?”

This is a question I was asked recently. I actually get asked this question a lot.

For the record, I don’t live in Madison. I live in Deerfield. Deerfield is a village with less than two thousand people, no grocery store, and no traffic lights.

I had a lot of frustrating conversations with people over the winter when I was freaking out about taking care of myself where I was told to order delivery or sublet my house to move closer to work. There is no delivery in a village of two thousand people, one restaurant, and six bars (this is Wisconsin, there is a five bar minimum per incorporated town).

There is no public transportation. I drive sixty miles round trip every day to go to my job. This can easily eat up two hours of my day. The closest actual grocery store is twenty minutes away, so it is rather difficult to run errands because just going to the store kills almost an hour of my increasingly limited free time.

Additionally, I have my pugs who spend way too much time alone in my house and it’s hard for me to go home, feed them, shovel food down my throat, then go back out again after working a ten hour day.

Part of me thinks it would be nice to be able to go out at 9:00 on a week night on the spur of the moment without having to drive a hundred miles round trip in one day. It would be nice to take advantage of my gym membership without feeling guilty thinking about my pugs being stuck in my house alone all day. It would be nice to join the maker space that inconveniently exists equally far away from both my job and my house.

So why don’t I move?

First off, I can’t afford it. Conservatively, it would quadruple the cost of my housing to move downtown, or even closer to my job. After my divorce I effectively have a blank slate. I don’t have any debt (besides my house and my car), but I don’t have anything saved either.

I would have to sell my house. Did I mention the whole living in the middle of nowhere, no public transportation thing? There are a half dozen houses around me that have been on the market for a while. My house is just about the right size for one person or maybe a couple, but not for a family. It’s within walking distance of the school, but in our era of helicopter parenting, that doesn’t mean what it used to.

I feel like I am in a really weird stage of my life right now. I never did the whole partying and dating thing in my twenties. I had some health and social issues and so I didn’t go out to bars and date. I married my ex-husband because we knew one another our whole lives and the dating scene terrified me because the only attention I got was from married creeps who wanted to have affairs (which isn’t that much different right now, to be honest).

Even though I didn’t have kids, I have a lot of the same issues that parents have. I have to go home to take care of my pugs. If I want to stay out after work, I have to make arrangements for someone to come take care of them. I find it incredibly selfish that people tell me that they only want to hang out with me if they can call me on a whim and ask to meet at the bar twenty miles away in ten minutes rather late on a week night. When I tell them I need to schedule something or meet earlier, they get pissy with me and tell me to move. This makes me less inclined to hang out with them because they want me to contort myself like a pretzel and they are unwilling to do one thing to accommodate me.

Last week I did an interview with the Ray Wenderlich podcast. One of the themes of the interview was them asking about all the projects I have been doing. I spoke at, I think, at least ten conferences last year. I coauthored a book. I work a full time job. I am the cohost of NSBrief. I have a lot of projects that I do. I never really thought about it because they slowly added incrementally and the deadlines for each one would come and go then another would take it’s place like Hydra.

I started to really think about what I am doing with my life and how things would be different if I lived in a city like a normal person.

If I lived downtown and I could order takeout and go out drinking at 9:00 on a week night, I would probably do it. I would develop a circle of friends who all do those things. I would probably be more social, have different hobbies and activities, and have something that resembles a normal life.

I don’t think I would find that fulfilling.

When I started programming a few years ago, I was driven by my fears of inadequacy. I was competing with people who had been programming since they were twelve. I was in my thirties and I hadn’t established a career yet. Just yesterday I was talking to a high school student who is on Ray’s tutorial team and I felt a deep sense of shame for squandering my twenties doing stupid crap.

I don’t remember where I read this, but there was a piece of writing Anthony Bourdain did where he talked about his chef career. He said that when he was a young chef, he had two options. He could either take some time really honing his skills by working for better chefs, or he could chase the money by being an okay head chef at a couple of different places. He had a heroin habit to feed, so he chose to chase the money. He talked about Grant Achatz, the chef at Alinea. He was talented enough that he could have been a head chef right away, but he wanted to be a great chef, so he paid his dues for several years by being a sous chef for great chefs so that he could learn to be a great chef. His restaurant is the only consistent 3-star Michelin restaurant in Chicago and he is considered to be one of the greatest chefs of his generation.

I consider my current job to be more than a job. I feel like it’s my do-it-yourself graduate school. I am a much better programmer now than I was when I started here almost a year ago. I have the freedom to ask stupid, esoteric questions without worrying that I am going to be fired for not knowing what a bubble sort algorithm is. I am a sous chef working under a great chef to learn how to be a better programmer (mixed metaphors are pretty).

Right now I have two options for making up for lost time. I can either spend a lot more money to engage in a lifestyle that will be fun for a few years but will do little to enhance my career, or I can accept that living in the suburbs sucks, but that I can spend all of my time stuck at home doing things that will enhance my career and help me make up for lost time by fast tracking my programming skills.

I know most people after a divorce would throw themselves back out into the dating pool and get new hobbies and do a bunch of things to feel free and alive again. It’s a tempting thing. However, I made a lot of sacrifices over the last three years to get to the point I am at now. My fire is burning, but it will go out if I don’t keep tending it. I worked my ass off to get it going after having two previous attempts not get past the kindling stage. As cool as it would be to be a “normal” person and go enjoy my youth, I think that I have a chance to do something important right now and I want to see where I can take it.

Meaningful Relationships and the Art of Networking

Family

My father and I have had arguments about family for most of my life. My father keeps insisting that now that I am an adult I should make a pilgrimage twice a year to go to his family reunions. I don’t see the point in going to these because I had many of these events from my childhood where I felt kind of like we were the Anne of Cleeves juice glass in the collection of wives of Henry VIII. We needed to be there so that there would be a complete set of my father’s siblings and family, but once we were accounted for we were kind of ignored and forgotten.

I came to terms with this at some point in my early adulthood because, honestly, what do you say to people you only see twice a year? Most of my relatives were much older than I was. My cousins were in college and getting married when I was in Jr. High. We were at different points in our lives.

The advent of Facebook and the Internet has made it much easier to connect with my relatives and keep up with what they are doing. We’re also now all adults and it’s a little easier to connect with people when you’re at the same point in your life.

Yet still I fight with my father over the necessity to go there and see people in person. We would have incredibly heated arguments over this and I could never articulate why this bothered me so much until recently, and yes, it does has something to do with networking.

Meaningful Relationships

I guess the things that bothers me about going to various family reunions is that they are perfunctory and superficial. You go, you say hi to the host, you eat your sandwich, you go home.

I observed over many years that most people’s relationships with their families were much different than my own.

I grew up in a very small town where most people had a huge network of cousins and other relatives who were all around the same age. They were thick as thieves in school and continue to voluntarily spend time together as adults. People weren’t just cousins, they were friends as well.

My cousins were not my friends. I really think that they could have been.

I remember as a kid being hauled to the family Christmas brunch where I would usually find a nice corner to sit in and read my Babysitter’s Club books while I waited for presents to be opened so that we could go back to the hotel and go swimming. One thing that happened every year was that my cousins would all go out to a movie and I was always invited to go. My dad would tell them no, I wasn’t allowed to go with them.

After a few years they stopped asking and whatever relationship I had with them withered until I became an adult and reconnected with them on social media.

My mother’s family was closer in both age and geographically and I barely saw them either. I will now go on Facebook and see every cousin of my mother’s, except her, go on a week-long camping trip and other various adventures that we are never included in because we’re not really a member of the family.

I keep fighting with my dad because I think we have different ideas of what “family” is.

My dad thinks that family is people you are related to by blood who are obligated to take you in if you are in trouble. He sees them like Social Security. You show up once a year to let them know you are alive so that if you are at a point where you might not be you can show up with your hand out and expect to be taken care of.

To me, what I observed, is that family are your social circle and your safety net. Family is people you want to spend time with and who you want to help if they’re in trouble. My dad has no interest in a meaningful relationship with any member of his or my mother’s extended family and he assumes that the blood tie is enough to fulfill this goal.

So What Does this Have to do with Networking?

I’ve noticed that some people are taking the wrong approach to networking.

Many people think that having several hundred LinkedIn connections is a network. It isn’t.

Jeremy Sherman was talking at the mini-360iDev in Greenville last year about how he networked with a journalist he hoped would feature him in a piece for his magazine. The only reason this tactic worked was because Jeremy actually made friends with this person. They liked one another and it was a real, meaningful relationship. He made it clear it wasn’t a mercenary tactic, he just really wanted to befriend the guy and that it worked out because he treated the journalist as a human being and not an opportunity.

All of the opportunities I have had have come from having meaningful relationships with people in this community.

It means a lot to me that the Kleins, the Remsiks, and the Wilkers have given me the opportunity to speak at their conferences. I like all of them as people very much. If I didn’t get to speak at 360iDev in two weeks (buy your tickets!), I would still like the Wilkers very much and would have found a way to go (but I am glad I didn’t have to).

I made friends with Chris Adamson because I liked the work that he did. We hung out at Anime Central the last two years because we were friends and we both had a mutual enjoyment of anime.

If I had gone into my friendship with him with the agenda that I was going to get something out of him, our friendship would never have materialized. People can sense users a mile away. Don’t be a user.

I am at a point right now where if I lost my job this afternoon, I have a large number of people I would go to for help, not just to find another job, but just because they’re friends who I think can give me advice and comfort about what to do. I have a lot of people in this community that I consider to be close friends and confidants and it makes my life and career richer for having a meaningful relationship with them.

Networking is about building meaningful relationships with people. It’s about seeing them as people and spending time with them even if it doesn’t immediately get you anything. It’s about finding people you genuinely like and who genuinely like you. If you go to one conference and meet someone once and never follow up with them, then I am sorry, they are not a connection in your network.

If you’re going to go to the expense and time of attending a conference, make the most of it. Meet as many people as you can. Find people who like the same things you do and keep in touch with them. You can’t pick your family, but you can pick the people you choose to be connected to.

Property Lists And User Defaults in Swift

I have written a bit about some of the work I am doing right now. Sadly, for most of this calendar year I have worked with Swift very little. I spent a lot of time working with some old open-source C libraries. Trying to yank my brain from the C precipice and trying to force it back into thinking in Swift.

My boss Brad Larson has been diving into the deep end of the Swift pool and bringing a bunch of treasures up from the bottom that I never would have considered. I am taking one of these treasures and examining how it works and what issues in our code it solves. I am hoping that by taking an elegant solution that many of us might not have thought of that we can all start thinking outside the OOP box.

The first part of this blog post is talking about some Cocoa concepts you probably are familiar with if you are not a new developer. Since I am a new developer, this stuff was new to me and interesting, so if you’ve been programming a while, you can probably skim this first section.

NSCoding, Property Lists, and Objective-C

The main piece of software we utilize at my company is SonoGuide. This is a piece of software that controls our robotics systems. Our systems print very minute amounts of liquid on a very small scale. Our positioner systems must be very precise. Our systems are rated to be accurate down to five microns. For those who haven’t worked with measurements for a while, that is 0.005 millimeters. You know, those super tiny increments on the ruler that are smaller than the tip of your pencil. So we are dealing with things that are incredibly small.

One of the pieces of functionality that we want our users to have is to be able to save coordinates. Since our systems are so precise and measure such small distances, it would be rather annoying for them to have to remember where their solution wells are in relation to the substrate they are printing on. We would like these positions to persist even if the user turns off the computer for the day and comes back next week.

It makes the most sense to keep these locations in the NSUserDefaults, which is a Property List. Property Lists, or plists, are NSDictionaries that contain different types of data. They can include arrays, strings, numbers, and even other NSDictionaries.

So we need an array of coordinate objects that we want to store in the NSUserDefaults that we are able to store and retrieve when necessary.

The way we, and everyone else, accomplished this back in the before time was as follows:

Serialization and NSCoder

While we’re still in the Way Back machine, do you remember that there was a period of time where if you looked at crash logs, you got weird hexadecimal values for where your app crashed rather than a nice, neat, human readable line of code?

The process of turning that value into a line of code is called “serialization.” The best mental explanation I have for serialization is the explanation that Mike Teevee uses to explain what television is in Willy Wonka and the Chocolate Factory:

You photograph something, and then the photograph is split up into millions of tiny pieces, and they go whizzing through the air down to your TV set where they’re all put together again in the right order.

Except instead of a photograph, you are using data and instead of it whizzing through the air, it’s whizzing through your hard drive in an area where it can be persisted and reproduced accurately.

We used the archiving functionality built into Cocoa to do our data serialization. Our persistence needs were not large enough to justify using Core Data and I think it’s possible that Core Data didn’t exist when the project was created. For a good background on choosing how to persist data, read Mattt Thompson’s post on the topic.

Archiving functionality has a few pieces. It has NSKeyedArchiver and NSKeyedUnarchiver for pushing and pulling the data. It also has NSCoder, which is where we, as the programmer, specify how to encode and decode our data.

NSCoding is a protocol that requires two methods to be written to conform to the protocol: encodeWithCoder and initWithCoder.

We implement the initialization protocol in our Coordinate class:

#pragma mark -
#pragma mark NSCoding protocol methods

- (void)encodeWithCoder:(NSCoder *)coder;
{
    if (name != nil) {
        [coder encodeObject:name forKey:@"name"];
        [coder encodeInteger:x forKey:@"x"];
        [coder encodeInteger:y forKey:@"y"];
        [coder encodeInteger:z forKey:@"z"];
    }
}

- (id)initWithCoder:(NSCoder *)coder;
{
    self = [self initWithX:[coder decodeIntForKey:@"x"] 
                      andY:[coder decodeIntForKey:@"y"] 
                      andZ:[coder decodeIntForKey:@"z"]];
    if (self != nil)
    {
        self.name = [coder decodeObjectForKey:@"name"];
    }

    return self;
}

With this code we are simply encoding the name of our coordinate object as a key and then adding the x, y, and z locations as values.

This takes care of our issues with serializing our coordinates. The coordinates are converted into NSData, making it nice and easy for us to move it from one place to another.

So cool, we have encoded our coordinate and we can extract it by decoding it. Huzzah.

So how do we decode our coordinate?

Our coordinate is stored as NSData. We have to reach out to our NSUserDefaults, look for anything encoded with the key “savedPositions”, decode it, and bring it back here.

NSData *dataRepresentingSavedPositions = [[NSUserDefaults standardUserDefaults]
                                           objectForKey:@"savedPositions"];
if (dataRepresentingSavedPositions != nil)
{
    NSArray *oldSavedPositions = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedPositions];
}

If you are interested in learning more about the NSCoding process, read this amazing blog post by Mike Ash.

Problems With This Approach

If you have learned anything about archiving data, this is the method you were probably taught. I did this myself while I was working through the Big Nerd Ranch guide to iOS programming. This is the standard. What is wrong with it.

Quite a bit, actually.

NSData isn’t inherently safe.

NSData is basically grey goo. It is a large clump of bits and bytes that have things fed into it and pulled out of it.

In our dataRepresentingSavedPositions we are simply pulling out any values associated with the key savedPositions. We are trusting that the data we are pulling is the kind that we want. It’s possible that our users have gone into the defaults property list and changed something. It’s possible that a hacker has gone and replaced one of our coordinates with a malicious executable file. We don’t know. There are no safety checks to ensure that none of these situations occur because when we serialized our data, we lost its type information. We’re living on a prayer here.

NSCoder can only be applied to an object inheriting from NSObject.

The way we structured our Swift code, we take advantage of the enhanced features of structs and enums. Our structs cannot comply to the NSCoder protocol because the only things that can are objects that inherit from NSObject.

In Mike’s article about implementing NSCoding, he mentions that if you want to encode a struct, you can’t encode it directly because it breaks. You need to break a struct down into its base components if you want to store and serialize them.

Since Apple has made it rather clear at this most recent WWDC that they would like us to start moving away from making everything an object, it doesn’t make a lot of sense for us to completely rewrite our code to start making our coordinates objects rather than structs.

Basically, NSCoder is build around the idea that you will only work with and encode objects, which is not how many of us program anymore.

A Swift Approach

Since we can’t really do our serialization and archiving the way we did them in the previous version of the code, how did we approach and solve this issue?

I will go over the various components of this code.

Structs

Right off the bat, we are creating our coordinate as a struct and not an object:

struct Coordinate {
    let x:Double
    let y:Double
    let z:Double

    init(_ x: Double, _ y: Double, _ z: Double) {
        self.x = x
        self.y = y
        self.z = z
    }
}

Since we know from earlier that we can’t associate NSCoder with our Coordinate struct, we need to figure out another way to deal with it. We used a protocol.

Protocols

protocol PropertyListReadable {
    func propertyListRepresentation() -> NSDictionary
    init?(propertyListRepresentation:NSDictionary?)
}

Since property lists are just NSDictionary objects, we need to make sure that anything that conforms to PropertyListReadable is able to create and take in NSDictionary objects.

Since we can now extend structs with protocols, we are able to take the PropertyListReadable protocol and extend the Coordinate struct:

extension Coordinate: PropertyListReadable {
    func propertyListRepresentation() -> NSDictionary {
        let representation:[String:AnyObject] = ["x":self.x, "y":self.y, "z":self.z]
        return representation
    }

    init?(propertyListRepresentation:NSDictionary?) {
        guard let values = propertyListRepresentation else {return nil}
        if let xCoordinate = values["x"] as? Double,
               yCoordinate = values["y"] as? Double,
               zCoordinate = values["z"] as? Double {
                   self.x = xCoordinate
                   self.y = yCoordinate
                   self.z = zCoordinate
        } else {
            return nil
        }
    }
}

The propertyListRepresentation function works under the assumption that a Coordinate instance was already able to be initialized with the correct number and types of parameters. This function goes through the Coordinate instance and sets key-value pairs for each of the axis and returns an NSDictionary. This function allows you to take any and all Coordinate instances and format them in such a way that they can be saved to the NSUserDefaults.

There are some situations where you want to go the other way. You have extracted an NSDictionary from the NSUserDefaults and you want to break it back down into a Coordinate instance. Since you can’t be certain that the data you are pulling from the defaults is in fact a completed coordinate, you need to use a failable initializer. You also need to make sure your return value is optional because if you were pulling data associated with a string you don’t want to crash your app by trying to process nonsense.

In our first line of code, we are implementing the shiny new guard statement. Since many of you may not have had time to dabble with guard, let me walk you through how we are using it and why.

Our goal with this initializer is to create a Coordinate with values we have extracted from the user defaults. Before we try to set each of our axis to a value, we want to make sure a value even exists. That is where guard comes in.

We are checking to see if our optional parameter was passed in or if we have nil. If we have nil, we don’t want to have to go through a bunch of conditional logic to verify that yes, we are doing nothing with our value. A guard statement only executes a line of code if the condition is not met. We want to return nil if we know that no parameters were passed in, so we can cut to the chase and do that immediately at the beginning of our block of code.

Once we have established that our NSDictionary was not nil, we now go through each value in the dictionary to make sure it correlates to a specific key. If at any point we encounter a key that does not have a value, we kick out of the whole thing and return nil.

By using a protocol to implement this functionality, we are able to specialize and reuse these concepts for other value types in our software. Before, we would have had to make a superclass or a delegate with methods that were required to be overridden by the subclass. By allowing structs to conform to protocols, we are able to specify functionality that we need in multiple places but with different implementation.

Map, Filter, and FlatMap

It would not be a shiny Swift blog post without the obligatory section on the functional features of Swift.

Just to clarify where we are at at this point in the code. NSUserDefaults is an NSDictionary where the key is the name you assign to label what you want to store. In our case, we want to store saved coordinates, so our key is “savedPositions”. The value is an array. The array can contain any object. Our Coordinate is not an object because it’s a struct, which is why we convert it to an NSDictionary. So, in theory, our NSUserDefaults should have a key-value pair where the key is “savedPositions” and the value is an array of NSDictionary objects that represent Coordinates. Simple, right?

Wouldn’t it be really cool to be able to filter through the array we pull from the NSUserDefaults to make sure we have an array of only the objects of the type we want? Sadly, there isn’t.

Of course there is. If there wasn’t then either that sentence wouldn’t be there, and or I would be a sadist. The jury is still out on that last conditional.

func extractValuesFromPropertyListArray(propertyListArray:[AnyObject]?) -> [T] {
    guard let encodedArray = propertyListArray as? [NSDictionary] else {return []}
    return encodedArray.map{T(propertyListRepresentation:$0)}
                       .filter{ $0 != nil }
                       .map{ $0! }
}

In the extractValuesFromPropertyListArray function, we are accepting an optional argument of an array of any object and returning an array of our generic return value. We also are specifying our generic return value must conform to the PropertyListReadable protocol.

The first thing we need to do is make sure we actually received a value. If we didn’t, there is no point in filtering an array that doesn’t exist. Our first line of code checks to see if we have a value and if that value can be cast to an array of NSDictionaries. If we don’t or we can’t, we return an empty array.

If that passes, we go ahead and filter the array. We use the .map function (which iterates through an array, applies a function to it, then creates a new array from the results) to run each value through our propertyListRepresentation initializer we created in our Coordinate extension. The propertyListRepresentation either returns an optional Coordinate or a nil.

We then apply a .filter to our results. We check to see if each item in the array is not nil. If it is nil, we throw it away. We then create a new array of just optional Coordinates.

Finally, now that we have ensured that we don’t have any possible nil values, we use another .map to unwrap each value and return and array of Coordinates (or any other structs we extend with the PropertyListProtocol).

This is really inefficient.

The function extractValuesFromPropertyListArray was refactored to the following:

func extractValuesFromPropertyListArray(propertyListArray:[AnyObject]?) -> [T] {
    guard let encodedArray = propertyListArray else {return []}
    return encodedArray.map{$0 as? NSDictionary}
                       .flatMap{T(propertyListRepresentation:$0)}
}

It was a real shame in our previous version of the code that if we had an array of mostly NSDictionaries, but if some stupid NSData object (which could be a malicious program) somehow snuck into our array, we had to throw away all of our other valid values. Since we’re going to filter through our results later anyway, we just want to verify we have an array of anything.

Since we don’t filter for NSDictionaries in our first line of code, we need to move the filter to our second line. Now our first .map statement is checking to see if each item can be cast the an optional NSDictionary. If it can, it gets added to the new array. If it can’t, it gets kicked to the curb.

Our previous code had a convoluted setup to be able to apply a function, filter out the nils, then unwrap the coordinates. This is a common enough thing that there should be a more concise way to do this. There is, and that is using .flatMap. Flat Map does exactly the same thing as our previous three chained functions in one handy dandy function call. Huzzah!

Saving to Defaults

We have one last part left to our property list loading and unloading. We’ve verified that everything we are extracting to the defaults is safe. We now have to verify that everything we are sending out to the defaults is safe.

One last little block of code:

func saveValuesToDefaults(newValues:[T], key:String) {
    let encodedValues = newValues.map{$0.propertyListRepresentation()}
    NSUserDefaults.standardUserDefaults().setObject(encodedValues, forKey:key)
}

For our parameters, we are taking an array of values that conform to T:PropertyListReadable and a string value to use for our key.

We’re creating an array of encoded values by taking the array parameter and mapping each one using the propertyListRepresentation function to turn it into an array of NSDictionaries. We then run the result through the setObject:forKey function associated with the NSUserDefaults.

Conclusion

I created a playground that contains all of the code I spoke about in the second half of this post.

When Brad showed me the extractValuesFromPropertyListArray function, it made my head explode. I saw the .flatMap() function and the guard statement, I felt stupid and inadequate. I felt despair that I would ever be able to come up with this stuff on my own. I can look at code and kind of grok what it means, but reading and understanding something are different than actually coming up with it.

After a while of struggling with the code, I realized I was asking the wrong questions about it. Rather than asking “how” it worked, I should have been asking “why” it was written that way. I talked to Brad about how we were dealing with the user defaults in the original code. He told me about the issue he had with it that I detailed in the first half of the post.

That is when a lot of this stuff began to click into place for me.

We don’t have this complicated code because we’re trying to be clever and use all the new toys in Swift. We are doing the code this way because it solves a problem that we had that could not be solved with Objective-C.

We could have used a “for-in” loop instead of the .map() function. We didn’t have to use .flatMap(), we had a longer implementation of it.

I have been approaching learning Swift all wrong. I was trying to take concepts like currying and trying to find ways of cramming them into my code so that I could understand how they worked. Our code is elegant because it had a specific set of problems it needed to solve that either were not solvable any other way, or would have resulted in more lines of code that would have taken more time to run because it wasn’t optimized.

For me, I took two lessons from this:

  1. Instead of spending more time thinking about clever ways to use shiny new features, I should spend some time thinking about what problems I had to solve.
  2. Just because my code “works” doesn’t mean it can’t be better. There might be “easy” ways to get something running, but there might be better, more elegant ways to write your code.

Yes, it’s overwhelming keeping up with all the new language changes and feature out there, but there can be great features that can make your code better that you never discover if you just decide your code is done once it compiles.

Soul Searching

January, 2014

I began my programming career in late December 2013. It started something out of necessity. Sometime around October I suffered from a nervous collapse that made it impossible for me to focus on my school work. I had dropped out. I was lying to my husband about dropping out of school because I was gambling on my ability to find a job around the time I was supposed to graduate. I was very lucky and something came through.

My only hope for my first job was that I would find something in iOS. In the Madison area, that was a pretty stiff order. Madison is a lot of enterprise Java, government, and health care.

I managed to find a job at a start-up where I was the oldest person by a decade. I was partially hired because my bosses were not old enough to drink and didn’t know any better about hiring people who have actual experience.

By January, I knew this wasn’t working. I didn’t get along with my programming partner and I knew I was going to be let go. I was okay with that. I knew it was a bad fit.

I did some soul searching at that point. I knew it was bad to lose your first job after two months and I did have some concerns with my long-term ability to be hired. I had a few choices. I could kind of fake it and find another, similar job where I would be equally uncomfortable, but possibly be able to fake it better. Or, I could acknowledge that I was in the weeds and I didn’t know what I was doing.

The people around me didn’t know what they were doing either, but I had enough training and visceral awareness to know that my programming sucked. I knew it could be better and I knew it would never be better if I continued to pretend like I knew what I was doing.

I sat down and started thinking about what I wanted from my career. There was only one thing I absolutely knew I wanted. I wanted to be Brad Larson.

Brad, for those who have not heard my enthusiastic ramblings about him, is the creator of GPUImage. Brad taught the Advanced iOS class at MATC the first year it was offered. The classes were, and are still, available to watch on iTunesU. While I was a student I heard a lot of stories about him. I heard about how Apple engineers told him that something he wanted to do with his Molecules app was physically impossible to do on the current hardware. He figured out a way around the limitation and he made it happen. He was the guy who did impossible things.

I didn’t know if it was possible or how long it would take, but I wanted that. I wanted to understand the language well enough that I could figure out a way around the limitations. I wanted to be a great programmer.

I reached out to Brad and told him that I wanted to do what he does and asked him for advice about how to get started. He was very kind and wrote a nice email back. A few weeks later, a contract opportunity became available to work with him on an extension of his Molecules app. I knew I was on my way out at my current job, so I reached out to him. I told him that I didn’t know anything but that I wanted to. I really wanted to make sure I didn’t misrepresent myself because I wanted to learn and I couldn’t do that if I pretended to know things I didn’t.

After this contract job, I spent time working on a book with Chris Adamson and doing a lot of conference talks. I was trying to get my name out there so that I could find a job. I talked about GPU programming and Metal because they were new things. I didn’t really explain them as well as they should be explained because I didn’t have enough experience with them to fully understand them. I gambled on talking about difficult and obscure technology to try and differentiate myself from all the other new programmers out there.

To my shock and surprise, Brad reached out to me about working for him as my speaking obligations were winding down. I did it. I accomplished the short term goal I made at the beginning of the year to find a programming job with a great programmer so that I could get better and be a great programmer too.

January 2015

Let’s jump ahead a year.

At the beginning of this year I initiated a divorce with my husband. Things had been difficult for a long time. My goal for a few years had been to find stable employment that would allow me to end the marriage.

I do not want to badmouth my ex-husband. Our divorce was amicable. He was a friend before we were married and he continues to be a friend. We had a lot of trouble and I honestly wish him no ill will.

I am bringing this up simply to establish that the last six months have been very difficult.

I have never taken care of myself.

I lived with my parents until I was 27 years old. I was essentially a perpetual student because I didn’t really understand how to find a job or support myself. I moved from my parent’s house to my husband’s house. The first few years I was working I had my husband manage our money because I was earning minimum wage and I did not want to know what my weekly paycheck was because I was afraid if I knew how little it was, it would be easier for me to mentally justify calling in sick when I didn’t feel like going. I was unemployed from 2012 for most of the rest of our marriage. I have never budgeted my money. I have never paid my own bills. I never lived on my own. I don’t think I filed a tax return until I got married because I earned no income.

The last six months have been difficult. It’s been hard trying to learn things that most people knew when they were 16. It’s been hard being away from my pugs so much every day. My house is still a mess because I am simply too tired and demoralized to clean it. I don’t think I’ve put my laundry away since February. My ex-husband was actually so appalled by my inability to care for myself that he cleaned my kitchen one day when he was here picking up some of this things.

The last six months have been physically and emotionally exhausting. I have had bouts of depression that I have spoken about on this blog before. It’s been rough.

Because things have been rough, I have been letting a lot of things go. One of those things has been my focus on my long-term goal of being a great programmer.

I have barely been getting by.

I have had weeks where I have barely gotten anything done. I have felt a great deal of self-hatred and fear about losing my job and independence.

At a certain point it became easy to rest on my credentials. I wrote a book. I was invited by Saul Mora to interview people for NSBrief. I had lots of people who knew who I was. I was given some cache for being a great developer because I had credentials. I didn’t want to think about how little I actually knew because it was too fucking demoralizing to deal with. So I pretended. I even convinced myself that I was as good as I needed to be. I got careless. I stopped trying because it was just too hard to deal with.

Now

I am not doing this any more.

I am tired of what I have been doing for the last year.

The reason I told my long, rambling story at the beginning of this post is because I feel like I am back there now. I feel like I have two choices about how I can proceed from here.

I can either decide that I learned enough and keep hiding behind my credentials. I can learn fast enough to keep up with things, but I won’t ever become the developer I wanted to be. I will have to keep pretending like I know more than I do.

I don’t want to do this anymore.

I want to be very clear about a few things.

Chris wrote most of the book. My name is on the book and I wrote three chapters from the book. I wrote the Debugging, Testing, and Photos chapters. Two of those chapters didn’t really require me to add much to the code base. When I had to tackle the Photos chapter I had to fly out to CocoaConf Boston to work directly with Chris on that chapter because I was not familiar enough with the code base to write the chapter by myself. I needed help with the Core Image code.

Chris worked on the book for two years before I was brought on. I think my presence played an important role in getting the book done. I contributed to the book. But, I feel that I have received more credit for the book than I am due. I haven’t read the book all the way through. I am not comfortable with most of the concepts in that book.

I am tired of waiting around for someone to figure out that cut to the front of the line. I am going to be proactive and admit that I don’t really know that much. I have never written an app of my own. I have focused on some very obscure and esoteric low level programming. For a developer who has only been working for a year and a half, I am fairly advanced. However, I have a long way to go.

I have realized that I have been squandering my opportunity of working with Brad by being too proud and afraid to ask him for help. I have been ignoring things that I don’t understand. Yesterday I asked Brad about what provisioning was. He could have explained it in a sentence. Instead, he took an hour to show me Instruments and how it could be used to analyze one of his projects. I felt like my world went from 2D to 3D. I realized that there was a whole dimension of being a programmer that I used to be aware of and wanted to explore that I had abandoned because I was tired and demoralized and didn’t want acknowledge how little I know. I felt exhilarated and deeply, deeply ashamed.

I do not want to be afraid anymore.

I am working on my own personal application. I am going to do my best to write about that process on this blog. I will be talking about concepts that are probably covered in the book that has my name on it. I will talk about things that most people who have been programming for five years already understand.

I want to go back to the spirit this blog was created in. I created it to document my progress as a student to a professional. True to my roots, I am a perpetual student.

I am going to ask more questions. I am going to delve deeper and try to understand better. I made time for what was important for the first half of this year. Now I need to get back on the track I decided a year and a half ago. I need to stop worrying so much about my exposure or my reputation and worry more about my skills. If my reputation suffers because I want to shore up my weak points, then I probably deserve it. It’s painful to admit that you don’t measure up, but if you won’t accept reality then you can’t change it.

I hope that Brad will continue to be patient with my questions and continue to go the extra mile to expose me to things I wouldn’t have thought of otherwise. His commitment to excellence pushes me to be better and even though it is painful sometimes, it is something I asked for that is rare in this day and age.

We Didn’t Start the Fire(Wire)

I have written about this before, but at my current job my boss and I are rewriting our robotics control software in Swift. This is an excellent blog post here that explains why we are doing this.

This is the camera setup we have on our robotics systems. Cameras help with dispenser positioning and we support both video and image capture for our users.

This is the camera setup we have on our robotics systems. Cameras help with dispenser positioning and we support both video and image capture for our users.

There have been a few projects we have open sourced after implementing them in this project. This blog post details the most recent project we have completed and open sourced, which was to write a wrapper class allowing us to connect to an external camera that conforms to the IIDC standard. This project can be found here.

Cameras are an important feature in our robotics systems. Users use the camera to help position their dispensers and to capture media. Videos and images of the dispensing process have been used in papers and documentation of scientific research, so continuing to support this functionality is vitally important.

What is the Goal?

Back when the code was initially written in 2007, AV Foundation and GPUImage did not exist. There was not really an easy way to hook up an external camera to an application. Additionally, the standard for rapid data transfer at the time was Firewire.

The fact that there were no easy solutions meant that our code was overly complex. There were much easier ways to connect to a camera and run the video through a filter that we simply couldn’t implement because our code touched too many other things. We set out to simply the code in our rewrite.

One major goal of this project was to make it easier to add additional cameras while still supporting the legacy cameras out in the field.

Since this company has been around for over a decade, we do have legacy hardware out in the field that we still need to support. Currently we have three different kinds of cameras out in the field associated with our robotics systems: Unibrain, Point Grey Flea2, and Point Grey BlackFly. At some point in the next year or so we will need to support a fourth camera because our current camera, the BlackyFly, has been discontinued.

What is IIDC 1394?

IEEE 1394 is a serial bus standard for high speed, real time data transfer. USB is another serial bus standard that is more widely adopted because IEEE 1394, aka FireWire, was proprietary to Apple.

Our first camera type, the Unibrain camera

Our first camera type, the Unibrain camera

Even though FireWire ports are no longer available on Macs being sold today, there are still many cameras that conform to the IEEE 1394 standard. Our current Point Grey BlackFly cameras have a USB 3 plug but they conform to the IEEE 1394 standard.

IIDC is the FireWire data format for live video. In order to be able to interface with an IIDC compliant camera, we have to conform to their standard.

There is a library to interface with IEEE cameras, libdc 1394. We have integrated that library into our project and adapted it in order to be able to communicate with our cameras. This library’s functionality is what we are wrapping in our GPUImageIIDCCamera class.

We did not integrate the GPUImageIIDCCamera class into the primary GPUImage framework. The libdc 1394 library has less permissive public licensing than GPUImage has, so for legal reasons, the class could not be merged into GPUImage proper and must remain a separate entity.

Objective-C? Why Not Swift

Taking a legacy piece of software that integrates with hardware is something of a challenge. Since Objective-C is a superset of C, there was a lot of low level C programming that could easily be integrated into the previous iteration of the control software that now presents some challenges when we attempt to implement them in Swift.

One such challenge was figuring out how to interact with our hardware. Prior to attempting to connect and control our camera, we had to determine how to talk to our micro controller. We were able to do this within the current constraints of Swift, but there is one feature of the C language that Swift does not yet support, which is mutable function pointers.

Since this was an integral part of our process, it was necessary to write this class in Objective-C. This, for the record, is the first time in our six-month process where we encountered a problem that we could not code in Swift. This didn’t prevent us from being able to implement this feature, it simply meant that we had to finagle a few things to fully integrate the Objective-C class into our control software code.

What do we Need the Code to do?

These are several things we needed this class to accomplish:

  • Connect to the camera
  • Capture frames
  • Set up the proper video format for the camera type
  • Remap the YUV colorspace to RGB colorspace
  • Get and set camera settings for things like brightness and saturation
  • Handle camera disconnection

Challenges

One of my personal challenges was simply understanding the code. Since much of our functionality would be done differently in the new code, I couldn’t just port it over from the old version of the software. It was important to get a sense of how to wrap the IIDC functionality in such a way that it would be easy to implement new cameras into our process. It was also important to figure out what lifting would be done by GPUImage and what would be done by the IIDC camera class.

Our current camera, the Point Grey BlackFly

Our current camera, the Point Grey BlackFly

Additionally, Brad did some extra work on our version of libdc1394 and his changes had not been documented. I couldn’t use the general documentation, what little of it there was, for the code.

Initially we thought that we would not need to use any OpenGL to process the video frames. It was later determined that a shader would be necessary for finding the frame size. This was beyond my present OpenGL experience, so Brad needed to write the necessary shader to accomplish this.

We also had to deal with different video modes. There are about thirty types of video modes we have access to, but all of these boil down to one of two types: Format 7 or anything else.

Format 7 allows you to set the frame size and the colorspace. All of the other video modes specify those things in their mode name.

Point Grey Flea2 camera mounted on our Desktop system

Point Grey Flea2 camera mounted on our Desktop system

Not all cameras support Format 7. Our first camera, the Unibrain, does not support Format 7. So we needed to make sure we were able to connect and use both Format 7 and non-Format 7 cameras.

We also had to deal with the fact that we were talking to a piece of hardware. Those settings, along with brightness, saturation, and others are all set on the physical piece of hardware. We can communicate with the hardware using C functions, but the point of wrapping this class is to avoid having to touch the messy underlying C library.

Each property associated with the camera that we can set has overridden getters and setters. We override them in order to make sure the camera and the application are on the same page about what each expects the settings to be. When you drop this class into another application, it appears to work the same way for the programmer with all the nasty bits tucked away in accessor methods.

Final Thoughts

When I worked on figuring out libxml2 at the beginning of the year I thought that was the hardest thing I would work on. That was just a warm-up for this project.

This was a huge challenge for me personally. I think trying to figure this out has been the hardest thing I have done in my career so far. In addition to how difficult this has been, not working with Cocoa since 2014 has made trying to get back in the swing of Cocoa development has been a bit of a challenge.

I hope that as I progress in my career it gets easier for me to pivot from low to high level development more easily. I wish I could have done this entire thing by myself, but I understand that we have deadlines that need to be met. I am proud of the amount I was able to do here and the growth I have experienced as a programmer by pushing myself to work on something this difficult.

The Trick to Forgetting the Big Picture is to Look at Everything Close-Up

Any sufficiently advanced technology is indistinguishable from magic.
– Arthur C. Clarke

Back when I was a programming student, my teacher Eric told me that over the years he has learned and forgotten a dozen programming languages.

At the time, it was inconceivable to me that anyone could learn and forget so much. Two years later, I am shocked to discover that he was right.

Two years ago when I really doubled down on learning iOS programming, I worked on it eighty hours a week. I was working through the Big Nerd Ranch iOS book. They had a series of about five chapters putting together a table view that would display a detail view populated by a singleton.

Every day I would wake up and code this over and over again. The first time I coded the examples, they made no sense. I typed a bunch of words that didn’t set off the compiler warnings, ran them, and magic happened. The second time was not much better. But by the third for fourth time, I began to realize, “Oh, I am creating this object because later when I load this detail view, I will be showing all the stuff I am keeping in this object. This is where it comes from.”

At the time Storyboards Interface Builder wasn’t particularly good for things. If you listen to many people online, their assessment of this situation has not changed. I used .xib files for each of my view and my custom cells and did all of my transitions programmatically. It took me weeks to wrap my head around all of these moving parts to figure out how they worked together. It wasn’t enough for me to just have something work, I really wanted to understand it.

Over the last year and a half, I haven’t really worked with user interfaces much. I had a contract job where there was no UI in Interface Builder because it was a legacy project from 2008. Then I spent a bunch of time running around like a chicken with my head cut off trying to figure out shaders, which are a tiny subset of a program. Then for the last eight months I have been working on porting another legacy project to Swift. We are just now getting to the point where I am working with interfaces again. It’s been over a year since I dealt with interfaces.

I am working on my first application. It is going to be rather limited to start off with, but I have plans to add additional functionality over time, so whenever I finally get it out, no, that is not the final product, more will come later, so don’t give me crap about it.

I am working with HealthKit. In HealthKit, there is a HKHealthStore that you are only supposed to have one instance of in your entire application.

I have been trying to figure out where to make that instance. I know that it needs to be accessible through the entire application and that you’re not supposed to make a bunch of instances of the same thing. I also know you have to pass it along to a lot of different places. I know many people don’t like singletons and I don’t want to create one of those, even though I am pretty sure HKHealthStore is a singleton. I was trying to figure out how all of the controllers can know about something while minimizing global state.

I talked to Brad about this a bit and he was talking about how it should be created in the root view controller for the application because that is responsible for the views that are controlled by it. As he was talking about all this stuff, it dawned on me that he was talking about the same things I was bashing my head against two years ago.

It wasn’t like I had spent a week mucking around with this stuff. I spent eighty hours a week for MONTHS trying to piece together how all this crap worked. I can’t believe that after spending all that time and pain on these concepts that they were buried in some far corner of my brain.

It also made me wonder about all the people who are learning programming now who use storyboards because, honestly, they are easier to get things done quickly. If you just push a couple of buttons and things happen like magic, how do you get a full understanding of what is actually going on? It makes me wonder about what else I don’t know about because I came into programming relatively recently. I know that my knowledge of memory management is bad because it was never something I had to deal with. I came in around iOS5/iOS6, so we had ARC and GCD and a lot of other things that abstract out a lot of the lower level programming stuff from you. Will understanding how root view controllers own detail views go the same way? I know talking to a guy at my first job he didn’t seem to understand this concept and it drove me crazy. I guess I have gotten to the point where I don’t understand it either.

It frightens me about how vast the knowledge is of everything that happens within the iOS ecosystem and how incredibly difficult it is to remember everything because really delving into the low level stuff means that you don’t know how to get things done quickly in the abstracted level. Sticking to the abstracted level limits your ability to do anything really customizable because you don’t see how the pieces fit together.

I am hoping that over the course of the next few years I can figure out a balance that works for me. I hope I can remember enough about how things work that I can deal with the abstracted layer without fundamentally forgetting everything.

The Demonization of Food

I had two incidents happen in the last 24 hours that have affected me on a deep, profound level that I would really like to talk about.

Last night I went to a friend’s house. We are beta testing a board game. Each of us is is going through some extreme life changes and we’re all trying to find ways of actually interacting with other human beings.

When I walked into his house, the heavenly aroma of fresh brownies hung in the air. His wife, who is also a friend, offered me a warm brownie and a glass of cold milk.

I honestly can’t remember the last time I was offered a warm brownie. I have had warm brownies at home, but there is always this cloud of shame attached to them. They get made because someone is really in the mood for chocolate and they are furtively consumed alone.

Having another person offer me a brownie with no associated guilt or feeling of failure associated with it was an incredibly moving experience.

The second incident was on the dead, forgotten social networking platform App.net. I commented about trying to figure out how to cook. I am living on my own for the first time in my life and I never really learned how to cook. I wish I had a cooking tutorial book for people like me starting off with some simple stuff that you then build into more complex stuff like you do when you learn programming.

Most people were very encouraging and enthusiastic about this goal. Except one person, who said: “Like you eat out every day prior to this? Unhealthy.”

That sound you hear in the background is the land mine this guy just stepped on blowing him to smithereens.

You have no fucking clue how pissed off I am about this comment.

I do not know why people in the country feel like they have the right to judge other people about what they eat.

My ex-husband and my father were both on extreme diets, but their diets were in direct opposition to one another. My father followed a mostly vegetarian diet with a lot of beans, rice, and bread. My ex husband followed a low-carb Paleo-style diet. Trying to coordinate a meal between the two of them was like the most bloody Holy War imaginable. Both were incredibly passionate that their way of eating was the right one, that the other person was an irresponsible fool, and that the other one would drop dead of a heart attack at a young age due to extreme obesity.

I don’t want to live like that. I have been living like this for the last thirty-three god damned years and I am fucking tired of it.

I like potatoes. I like pie. I like cheeseburgers. I like beans.

When I was a kid one of the highlights of my year was when my mom would bring home a French Silk pie from Baker’s Square. I told myself as a child that when I was an adult I would keep one of those suckers in my refrigerator and eat it directly out of the pie plate and share it with no one. Last month after my husband moved out of the house I brought a pie home and ate it directly from the plate. It was one of the most glorious, liberating moments I have had in my life of being able to eat like a savage and absolutely giving no shits about it.

I am incredibly disturbed by the amount of judgement we have about what other people eat. I am angry that we are making overweight people feel bad for being moral failures for being fat.

My Life as a Fat Girl

I have been on both sides of the coin. I have been fat and I have been painfully thin. I am a recovering anorexic. I starved myself in high school because I hated myself and I wanted to disappear but I was too afraid to actually follow through with taking my own life. I have hated my body for being fat even though I was incredibly thin, to the point of being unhealthy and unable to retain any body heat.

I was placed on a bunch of creepy medications when I was 16 that made me gain over sixty pounds in less than two years. As I watched myself going from a skinny to a chubby to borderline obese teenaged girl, I cried from despair and self loathing. I hated all of my skinny classmates and I was pissed at myself for not realizing I was skinny when I was anorexic.

I didn’t have a boyfriend for ten years and my parents and my doctors thought I was a lesbian. I tried to talk to my doctors about what was happening, but I got a sanctimonious “Eat less and exercise more” rather than an honest disclosure that weight gain was a common side effect of the drugs they were forcing me on. Right now there is a class action lawsuit against one of the drug manufacturers for causing Type-2 diabetes in people who were on the same medication I was because it caused so much weight gain.

The second I went off of these medications I lost most of the weight. I didn’t exercise more or eat less. I just stopped taking medicine I didn’t need to begin with.

One of the worst parts about being fat was basically being invisible. I have always spent way more time with men than women and I developed crushes on a lot of my classmates. I didn’t really like any of them, I just kind of thought I was supposed to have a boyfriend and I was sad that no one was attracted to me.

I would sit next to my crushes and listen to them bitch about how the hot girls in their classes didn’t notice they existed while they were completely oblivious to the fact that I had a crush on them. I think if they had known I liked them it wouldn’t have made any difference. They would have been dismayed that the only girl who liked them was the socially awkward chubby girl with the bad personality. I don’t think they liked any of the girls they crushed on any more than I actually liked them, we all just wanted some external validation that we were okay.

When I lost all of the weight and went back down to my anorexic high school weight in 2008, I thought it would be this life changing experience. It wasn’t. I still felt bad about myself, except now I couldn’t go longer than two hours without having to take a nap, half of my hair fell out, and my face broke out and wouldn’t heal. What did make a difference to me was finally finding something I was good at and learning not to worry about the other stuff. When I started focusing inward on what I thought and felt rather than what I looked like I found peace.

We’re Not Being Effective

In spite of the billions of dollars we have sunk into research about weight, we seem no closer to understanding how weight works. Don’t give me any of that crap about “calories in, calories out.” Yes, on some level it is calories in, calories out, but there are a lot of factors that affect how the calories out gets determined. Women retain more fat than men do because we need to to grow and make babies.

Guess what? No one wants to be fat. No one chooses to be fat.

Being fat is one of the last acceptable things for people to be discriminatory about. You can’t say racist things in public anymore, but it’s perfectly okay to shame someone for being fat. People are being cut open and having perfectly good organs butchered by doctors to avoid being fat. We have created a narrative in our culture where anyone who is fat is fat because they lack the willpower to stop shoveling donuts into their gaping maws. We can feel superior to them because we have enough restraint to be thin even if we aren’t actively doing anything about it. This Calvinistic belief is preventing any meaningful research from being done into how to effectively fight the obesity epidemic.

This isn’t helped by the mass media messages that we receive telling both men and women that we are not “enough” to con us into buying gym memberships to “fix” ourselves to some Photoshopped ideal.

If you are a “stereotypical” fat person who spends all day eating, you are probably depressed or have some other issue that is the actual root of your issues. The weight is just a symptom. We aren’t treating weight like a symptom. We’re treating it like a moral failing making it more difficult for people who are struggling to actually get help. That really sucks.

I am sick and tired of everyone I know feeling shame about food. I am sick of everyone I know judging other people for what they choose to eat.

I want to see more people like my friend offering warm brownies to people with no underlying shame. I like to feed people. I used to bake a lot and it gave me a lot of pleasure giving people food I made and seeing them enjoy it. Something I used to love is now a source of tremendous angst for most of the people I know. I want everyone to feel loved and accepted for who they are rather than wasting their lives feeling ashamed because they keep gaining and losing the same twenty pounds over and over again.

When I got married back in 2009 I was skinny and sick and miserable. I have gained back more of the weight than I would really have liked to. I don’t really care. I feel better than I did then. I know now that I will never look the way I think I am supposed to. I am curvy. I hate skinny jeans. They are an abomination. I can’t force my body to fit into a mold it doesn’t fit into, so fuck it.

I am going to wear shorts that show my thigh fat. I find them comfortable and I would rather be comfortable than worry about showing people that I am chubby. My mom tells me not to wear things that make me look chubby. Hey! Guess what? I AM chubby. I don’t give a fuck. I feel okay in my own skin and I am fine with who I am. I am trying to go running more because I enjoy it and it makes me feel better. If I lose weight cool. If not, then whatever.

I am drawing a line in the sand here. I am going to eat whatever I feel like eating. I will eat my food mindfully. I will think about each thing I put in my body and if I want to eat pie, I am going to eat pie. Life is too short to feel hungry all the time and to eat unsatisfying salads and to feel empty inside.

If you have enough leisure time to make your food from scratch every day, great for you. I don’t. I am out of my house close to twelve hours a day. I spend that time bashing my head against a lot of really difficult stuff that drains all of my energy. I come home and find anything I shove into my mouth before taking a bottle of wine with me to the bathtub to try and drink myself to sleep, which usually doesn’t work and I wind up waking up at 4:30 in the morning.

I want to learn how to cook. I find it rather intimidating. I lived with a guy who spent thousands of dollars on various kitchen gadgets and wanted to work his way through the Julia Child cookbook. I just want to make meatloaf and curry. I want to have a few things that I can throw together when I am brain dead and I need to feed myself. Eventually I would like to make food for other people who will enjoy eating it rather than giving me a lame excuse about how they’re on a diet and they can’t eat my food because it has butter and sugar in it.

I had tutorials to learn how to program, I don’t know why they don’t have a similar thing for adults to learn how to cook. Start simple and build various skills that can be used together to make increasingly complex foods. I don’t want some asshole online implying that I am a slovenly person because I lived off of grilled cheese sandwiches and tomato soup after my ex moved out of the house because I was trying to keep my head above water.

I hope that this post inspires people who feel ashamed about food to go out and eat something they want to eat without feeling guilty about it. Don’t be ashamed. Don’t feel like you are immoral because you ate a brownie. Life is meant to be lived. Eat the brownie. Enjoy the brownie.

A friend of mine said something that I thought was great. He said, “I don’t know when I will die, but I do know that when I die I won’t die hungry. I will die knowing the last thing I ate was tasty and delicious.”

Words to live by.

What’s an Object?

I was editing my interview with Orta Therox yesterday when I realized I mentioned asking my boss Brad Larson what an object was.

I realized when listening to this that I hadn’t given any context because I wasn’t anticipating talking about that during the interview and I come off being rather ignorant in the course of this question. So, to avoid having to turn in my nerd card, I am going to give some context and give a more nuanced explanation behind that question.

My Personal Background with Object-Oriented Programming

I started going to school in 2010 for computer programming. I was 28 and I had almost no experience whatsoever with computer programming. My background was writing HTML when I was in high school and learning how to compile “Hello, world!” in Perl. At the time I enrolled I was working at Target because I failed to find a journalism job after I graduated and I really didn’t want to work at Target for the rest of my life. Programming seemed like it would be a good fit and it didn’t seem like it was going anywhere for a while.

I got through my first semester of introductory programming okay. Starting in your second semester, you had to pick a language to study for the next three semesters. At the time I was making this decision, there were three languages to pick from: Java, PHP, and VB.Net. I decided I would pick whichever one fit into my work schedule. The one that fit was VB.Net.

Our introductory class kept getting further and further behind. By the time we got to the end of the semester, we had never spoking about object-oriented programming. It was something we were supposed to do, but we just never got around to it.

The following fall, I took the advanced class. It was a night class, which I don’t really do well with anyway. The first class period, my teacher showed me object-oriented programming for the first time. I had no idea what the fuck he was talking about.

A bunch of code was in other files! How did it work together? How does the computer know to look in these other files?? Wait, what the hell is polymorphism? Am I having a bad acid trip??

After three hours of this, the teacher said since this was all review he was never going to go over any of this ever again. That was when I realized I was kind of screwed.

I decided to drop out after I asked what a constructor was and the teacher asked me if I learned anything the previous semester. At this point I had a decent job with people that I liked. I figured I was too stupid to learn programming because I wasn’t born with an intuitive sense for it and I was tired of feeling stupid all the time.

Six months after this, I took a new job that was the most miserable job I have ever had. The plus side to this job was that I taught myself programming while I was there. I realized I hadn’t put enough effort into it and if I just programmed forty hours a week I could learn it. So I went back to school.

I finally grokked OOP when I took the Intro to Java class. They introduced objects immediately and forced you to use them throughout the whole semester so you could get used to them. I started to understand about file paths and how the program knew how to find your other classes and how you imported them and how you constructed them. I felt like after I understood this for the first time that I was a “real” programmer. I hadn’t felt that way before grasping object orientation.

OOP is Not the Only Paradigm

I went from Java to iOS/Cocoa/Objective-C programming. I had a few vague issues when I was learning Objective-C with trying to pass around things that weren’t objects. Rather than really think about it at the time, I just got annoyed and turned all of my ints and floats into NSNumber objects to shut up the compiler.

Here is a sample header file you might commonly make if you were creating an Objective-C project:

@interface MyViewController ()

@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIImageView *blurredImageView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) CGFloat screenHeight;

@end

In my experience with Objective-C, everything was an object. You created classes, which were objects, and you populated them with instances of other objects and in turn instantiated your new object in instances of UIViewController objects.

You had header and implementation files. The name of your class was the same as the name of your implementation file. Every file has a class. This is what programming is. It’s objects all the way down.

My first experience with understanding that this wasn’t the only way of doing things came several months ago. I was working on translating a plug-in we were using to a piece of code we kept internally. I had a weird method I was dealing with that wouldn’t compile.

After fighting with it for a while, I took it to Brad and asked him what I was doing wrong. He told me I was treating the function like a method. This statement kind of blew my mind because I thought that methods and functions were the same thing. I thought we called functions methods in Objective-C the same way that Java interfaces were the same thing as Objective-C protocols. (Yes, I am aware I am probably wrong about this as well. I am still learning.)

I didn’t know that there was a difference in Objective-C between functions and methods. Functions exist outside of classes and methods are functions that are embedded in a class. I hadn’t really thought about this or why anyone would want to do that. I simply assumed that all functions were methods and everything had to be encapsulated in a class.

This was only the tip of the iceberg.

Becoming Functional

Back in November, Brad went away for a week for a trade show. We were planning to rewrite all of our control software in Swift and he wanted me to take a look at the code he had written so far to make sure that I understood it.

What I saw completely broke my reality.

He has posted a sample project on GitHub including some of the code I looked at initially. Here is a small sample of what I saw that changed the way I think about programming:


import Foundation

// MARK: -
// MARK: Error protocols

public protocol ErrorType {}

protocol PresentableError {
    var errorTitle: String { get }
    var errorInfo: String { get }
}

// MARK: -
// MARK: Error types

enum CommunicationsError: ErrorType, Printable, Equatable {
    case ReadWriteTimeout
    case WrongByteCount(expectedByteCount:UInt, receivedByteCount:UInt)
    case CorruptedResponse(expectedResponse:[UInt8], receivedResponse:[UInt8])
    
    var description : String {
        get {
            switch (self) {
                case .ReadWriteTimeout: return ".ReadWriteTimeout"
                case let .WrongByteCount(expectedByteCount, receivedByteCount): return ".WrongByteCount(expectedByteCount:(expectedByteCount), receivedByteCount:(receivedByteCount)"
                case let .CorruptedResponse(expectedResponse, receivedResponse): return ".CorruptedResponse(expectedResponse:(expectedResponse), receivedResponse:(receivedResponse)"
            }
        }
    }
}

enum ElectronicsError: ErrorType, Printable, Equatable {
    case ElectronicsDisconnected
    case UnrecoverableCommunicationNoise
    
    var description : String {
        get {
            switch (self) {
                case .ElectronicsDisconnected: return ".ElectronicsDisconnected"
                case .UnrecoverableCommunicationNoise: return ".UnrecoverableCommunicationNoise"
            }
        }
    }
}

// MARK: -
// MARK: Equatable protocol compliance for these errors

func == (lhs: CommunicationsError, rhs: CommunicationsError) -> Bool {
    switch (lhs, rhs) {
        case let (.ReadWriteTimeout, .ReadWriteTimeout): return true
        case let (.ReadWriteTimeout, _): return false
        case let (.WrongByteCount(expectedByteCount, receivedByteCount), .WrongByteCount(expectedByteCount2, receivedByteCount2)):  return ((expectedByteCount == expectedByteCount2) && (receivedByteCount == receivedByteCount2))
        case let (.WrongByteCount, _): return false
        case let (.CorruptedResponse(expectedResponse, receivedResponse), .CorruptedResponse(expectedResponse2, receivedResponse2)): return (equal(expectedResponse, expectedResponse2) && equal(receivedResponse, receivedResponse2))
        case let (.CorruptedResponse, _): return false
    }
}

func == (lhs: ElectronicsError, rhs: ElectronicsError) -> Bool {
    switch (lhs, rhs) {
        case (.ElectronicsDisconnected, .ElectronicsDisconnected): return true
        case (.ElectronicsDisconnected, _): return false
        case (.UnrecoverableCommunicationNoise, .UnrecoverableCommunicationNoise): return true
        case (.UnrecoverableCommunicationNoise, _): return false
    }
}

The name of this file is ErrorTypes.swift. There is no ErrorTypes class. There is nothing in this file named ErrorTypes.

NOTHING IN THIS FILE IS AN OBJECT!!

We have several enums, which are not objects, that we are references for type conformity. We have UInts, which are not objects. We also have functions. Lots and lots of functions. That aren’t associated with a class. They’re just out there like llamas roaming free.

When I tried to understand this I felt like I went to a party and someone asked if I wanted to use another person’s liver. I didn’t know if was possible to call functions that were not associated with a class instance. I had never seen anything like this before. I couldn’t believe this would build and run and compile just fine. I felt like I fell down a rabbit hole and nothing made sense anymore.

Reorienting Myself with Reality

I, like many people, learned programming in the age of Imperative Programming. Java has been around for twenty years and many people learned programming with Java. A lot of us don’t know anything except the Object Oriented way of doing things. To many of us, this is what programming is.

It doesn’t have to be.

One reason I am so vocal in my defense of Swift is because this realization has completely changed my reality. I used to think there was only one way of doing things. Well, I won’t say that. There was one right way of doing things and then there was the “Dear god, what is this person thinking by having this property controlled in four different places?!” way of doing things.

Being exposed to Swift and seeing that you don’t have to put everything in a class has been a revelatory experience for me. It is forcing me to reevaluate everything I know about programming.

I never thought about what an object was before because there was no point because everything was an object. Now, I am trying to get a better understanding of what an object actually is. I wrote about the difference between structs and classes and at the time I really didn’t understand why you would want to use a struct instead of a class if they essentially do the same things. I now understand that you want to try to use structs when possible because they aren’t objects. Objects come with a lot of overhead. They let you do some more powerful things like subclassing through polymorphism, but you don’t always need to do those things. Looking at how powerful the enums are that Brad uses in his code, I am fascinated by how confined my own view was when I thought everything had to be an object and exist in a class.

So yes, I did ask what an object is. I know most programmers worth their salt can tell you the definition of what an object is, but I don’t think many of them stop to think about why we use them and if they are the best way of doing things. Or if they bother to wonder if objects are the only way of doing things.

Wrapping libxml2 for Swift

I have spent the last month or so working on a project where I am wrapping a legacy C toolkit, libxml2, in Swift. I have created a sample project here where you can obtain wrapper classes written in Swift allowing you to utilize libxml2 into your code without having to touch C.

My job at SonoPlot is to write control software for our robotics systems. One of our included pieces of software is a CAD program for users to use that creates XML pattern documents that that are parsed by our control software so that it can tell the robotics how to draw a pattern.

Since some of our pattern files can be very large and complex, it was important to us to be able to use the fastest XML parsing we have available. I benchmarked three different ways of parsing XML:

  • Tree-Based Parsing using NSXMLDocument
  • Event-Based Parsing using NSXMLDocument
  • Tree-Based Parsing using libxml2

I had wanted to include event-based parsing with libxml2, but that utilizes C function pointers, which are not currently possible with Swift.

I have included the profiler in my sample code for this project, but in case you don’t feel like running it yourself, my benchmarking showed that using libxml2 was four times faster than tree-based NSXMLDocument parsing and three times faster than event-based NSXMLDocument parsing.

Clearly, there is a large difference between using libxml2 and any permutation of NSXMLDocument.

What is libxml2?

libXML2 is a toolkit for parsing XML that is written in C. Back when the first iPhones came out, libXML was highly utilized because it was incredibly fast and the first iterations of the iPhone were not particularly powerful.

As the iPhone has become more powerful and the number of frameworks has become more robust, libXML2 has fallen out of use. Since it is a C toolkit, you are taking responsibility for your memory management. It wasn’t written for a specific language, so it is rather sprawling and has a lot of obtuse documentation. It’s also rather old. When I was looking into it they had sample code written in Pascal.

Basically, as things like NSXMLParser and the use of JSON became more prevalent and easier to work with, there hasn’t really been a need for most people to bother with this difficult toolkit.

Hooking Up libXML and the Wrapper Classes

libXML is included on your machine, but it isn’t included by default in Xcode. It will need to be important and linked to your project for Xcode to be able to see it.

Go to your project and find your Build Settings in your Project. Search your Build Settings for “Header Search Paths”. In your project’s search paths, add the following:

$(SDKROOT)/usr/include/libxml2

While still in your Build Settings, search for “Other Linker Flags.” Add this line to your linker flags:

-lxml2

Now go to your Targets and find your Build Phases. Find the tab that says “Link Binaries with Library”. Click on the “+” sign to load a new library to link to the project. Search for “libxml2.” There should be two results. Add both of those results to your project.

Lastly, you will need to import an Objective-C bridging header into your project. The Objective-C bridging header is a file that exists in this project, so you just need to drag it from the sample project over to your project.

After the bridging header is added to your project, go back to your Build Settings and search for “Objective-C Bridging Header”. You will need to add a line that has your project name and the bridging header name in it. For example, in the sample project LibXMLWrapperExample, the line added to the bridging header was:

LibXMLWrapperExample/Bridging-Header.h

A really good README going over this process is here. If any of my steps aren’t clear enough or something isn’t working quite right, use this as a backup for the instructions to hook this up. It can be incredibly obtuse and easy to forget one little step and have the whole thing not work.

Also, the way that I verified this worked was to look at a project I got this working on and I searched both the Target and the Project for “xml” to see where I had added search paths and linker files. This is a good way to do a sanity check to make sure that you didn’t forget anything.

LibXMLDoc

The first wrapper class I created is the simplest one: LibXMLDoc. In XML, you have a tree that is made up of nodes. In libxml2 all of the nodes are contained in an xmldoc. You need two things from the LibXMLDoc class : a document and a root node. Once you are able to extract the root node, you are able to traverse the entire tree to find anything that you are looking for.

Since we are dealing with C, we are responsible for our own memory allocation and deallocation. I had to remember to deallocate the LibXMLDoc when we are done with it.

LibXMLNode

The second class, LibXMLNode, is where we do a lot of the heavy lifting. This class is responsible for finding and extracting values from our XML document.

The first property I needed to set up was nodeName. nodeName is going to be the primary way we are going to be accessing and dealing with each node, so this is a pretty important value to have easy access to.

Since libxml2 is a C toolkit, the type we are receiving is going to be a C string. The other thing complicating this is that libxml2 is set up to deal primarily with pointers to their node and document objects. We need to take a pointer to a C string and somehow do some alchemy on it to convert it to a Swift string. Swift strings have a method on them called “fromCString” that I was able to use. Also when dealing with C string types, you need to use unsafe mutable pointers. I also had to figure out how to navigate through a C pointer to access the actual values that they were referencing.

I was able to get this all down to one line of code that did all of these things:

return String.fromCString(UnsafePointer(self.xmlNode.memory.name))!

From there, I needed to think about what we need to do with a node. Every node we encounter is generally going to be one of two ways:

  • It will be a parent node that contains children nodes but no value.
  • It will be a child node that might contain a value but has no children.

I set up two lazy properties in the LibXMLNode class to deal with these two eventualities: nodeValue and nodeChildren.

nodeChildren takes a LibXMLNode as a parameter and iterates through that node’s children until it encounters “nil.” It then returns an array of LibXMLNode objects.

The first time I wrote this code, I was getting many more nodes than I was expecting to get. By printing out the array of node children I found that every other node was a node, which mean that if I was expecting five children nodes, I was actually receiving eleven, because the first and last nodes were nodes and every other node in between was also . This was rather inconvenient, so I found a libxml function that checks to see if the node is a node. If it is, the function returns 1. I do a check on each node and if the function returns 0, the node is added to our LibXMLNode array.

nodeValue covers the other contingency where you have a node that contains a value that needs to be extracted. Since it is possible to have empty XML tags that do not contain values, this property has to be optional. We need to extract the value and look inside to see if we have anything in there.

I used the libxml2 function “xmlNodeListGetString,” which takes a document, a node’s children, and their index as parameters and returns either a C string or nil. If there is a value, we use the code we used in the nodeName function to extract a Swift string, we free the C string, and we return the Swift string. If the function returns nil, we return nil.

Raiders of the Lost ARC

So I was all excited that I figured all of this stuff out and I was ready to start testing my classes. I wrote a bunch of tests that all failed immediately.

While looking over the tests, I realized that every time I tried to access any of the properties on the root node, they were failing because the root node didn’t exist.

I was becoming incredibly confused and frustrated when Brad had me add a println() in LibXMLDoc between when we initialize the document and when we initialize the root node. It turns out that ARC was deleting the LibXMLDoc immediately after it was being initialized because it wasn’t being held on to or referenced anywhere. D’oh!

In libxml, the document controls the memory for all of the nodes, not the nodes themselves. Basically the way I was writing the code was that I only referenced the document once, where it gets initialized. From there, since there were no other references to the document, ARC deleted it along with all of the nodes it contains.

That was a problem. Since the document contains all of our nodes, we really need it to stick around until we are finished with extracting all of the nodes and their values. We have to create a LibXMLNode instance in the LibXMLDoc class to hold the root node, we couldn’t just have the LibXMLNode class point to the LibXMLDoc class. We had to have them point to one another without creating a retain cycle, so the LibXMLNode class has a strong reference back to the LibXMLDoc class to prevent the instance from being deallocate before we are done with it. I then went back to LibXMLDoc and make the reference to the LibXMLNode a weak reference to avoid a retain cycle.

There is still some juggling that needs to be done in order to make sure we are able to prevent the document from being eliminated and that we are able to get the root node.

The solution utilized here was to replace the strongly referenced LibXMLNode root node with a private, internal weak root node and a computed property checking to see if this internal root node has been set yet. If it has, it is returned. If it hans’t, we extract the root node, set it to the internal root node, and return it. Since computed properties are basically methods that look like properties, for all intents and purposes we are replacing a strong reference with a weak reference and a method.

We are trying to resolve a few things by taking this path. First, we are trying to avoid having the root node and the document deallocate before we can use them. Second, since we are using a class and a class is a reference type, we want to make sure that we only create the root node once rather than having a bunch of instances all pointing back to the same memory location.

And this, kids, is why you still need to think about memory management and ARC even if you started coding after iOS 5, like I did.

...and knowing is half the battle!

…and knowing is half the battle!

Adding Bundled XML Files

The last part of this sample application that I want to cover is including XML files rather than accessing them from an internet URL.

I have included in my sample project a relatively simple pattern file generated by our CAD program to use as an example.

One thing you have to remember to do when you include an XML file with your program is that you have to include it in the application bundle. I have included a convenience function in the LibXMLDoc class called “bundleForResource” that takes the the resource name and returns an NSURL. This can then be passed into the parser where it asks for the URL of the resource.

You also have to make sure that your file resource shows up in “Copy Bundle Resources” in “Build Phases.” My original attempt at creating a sample project was trying to make this a command line application, but I wasn’t able to copy the bundle resources (because there was no bundle) and it generated an IO error.

The last convenience function I included in the LibXML wrapper classes is the “outputXMLTree” function. This function is recursive and it walks through the document tree checking each node to see if it has children or values. I am using this function in the App Delegate to demonstrate the the classes have in fact parsed the included document correctly.

Conclusions

Before attempting to work on this project, I decided I was going to avoid dealing with C in Swift as much as humanly possible. Considering the nature of what we do here, where we use serial communication in C with our control software, that was an incredibly stupid and wrong-headed way to approach things.

Yes, it is a little more complicated. It required some more work, some tenacity, and some help from my boss who has been around the block a few more times than I have. As much as part of me would like to not think about it, C isn’t going anywhere. I want to work with micro controllers and firmware in the future and deciding not to get C to play nicely with Swift is basically a non-starter for the projects I would like to do.

Even if you think that XML parsing is as boring as dry toast, hopefully the code will help you with figuring out how to integrate older C code into your projects or at least give you a clean way to add better XML parsing to your applications.

Again, the sample code associated with this post is here.

Hit me up on Twitter if you have any questions about it.

My Defense of Swift

**Note: I am using an example in my blog of a post written by a developer in our community. I have noticed many posts with the same thoughts expressed in them and I am in no way attacking this particular person, who I respect a great deal. I want to preface this with saying I am in no way attacking the author of this piece or trying to single him out, so I hope he will not be offended that I am offering a counterpoint to his post.**

This morning I had someone send me a link to this article and asked me what I thought about it.

Honestly? I am kind of sick of everyone crapping on Swift.

I am tired of everyone saying the language is broken and that you can’t write real applications with it because it’s half baked and unusable.

I don’t mean to keep waving my credentials around, but I am working on a project where we are rewriting our software in Swift. We are not writing the usual weather app/something that pulls data from an API. This is some heavy duty crap. We are writing this on the Mac. We are using a serial port to connect to outside hardware. This is a legacy project that is on its third rewrite that has been around for ten years. So far we have not encountered anything that we can’t do in Swift that is being done in the original software.

For the last month or so I have been bashing my head against a project where I am implementing libXML in our project (which I am going to write a blog post about shortly.) Taking a really under documented C library where the sample code is written in Pascal and trying to get it to work in Swift has been a demoralizing massive pain in the ass. I have had to deal with all kinds of horrors that I didn’t know existed or were abstracted away so that I would usually never have had to deal with them again.

However, doing those things has made me a better developer. Just because I came into Cocoa programming after ARC doesn’t mean that I have no reason to think about it or know how it works.

I started learning programming three years ago. Prior to that, I didn’t know how to write a “for” loop without looking it up online. I was one of those noobs that people hate on Stack Overflow who ask how to do incredibly simple and stupid things. Learning programming was hard. It forced me to fundamentally change the way I think about the world. It was also hard because I had a lot of people who had been doing it longer than I had who were crapping on me because I didn’t know who the Gang of Four were or why we do the MVC pattern, or even what MVC means.

There are a lot of things that we think are easy and intuitive that aren’t either but we think they are because they are familiar. My boss told me about working with a woman who had a PhD but had never used a computer before. Our structure of navigating through folders and files is “intuitive” to us because many of us have been doing this for bordering on 30 years.

If you have been doing imperative programming since you were 12, then yeah, some of this stuff is going to feel complicated and unfamiliar. If you don’t have a painful, visceral memory of the pain it took to learn programming the first time, you might think that all of this stuff is complicated and broken and wrong.

I, however, do remember how hard learning programming was. I find learning functional programming and figuring out Swift to be no more difficult than it was learning Objective-C. It’s different. It isn’t broken. Yes, there are some things that will be refined over the next few years, but Objective-C wasn’t born completed either. It evolved over a period of years as Swift will evolve.

I got into programming because I wanted to learn how to solve complex problems. I am excited about Swift because it affords an opportunity to solve a complex problem in a different way than we did before.

I am worried that people’s opinions of Swift are being influenced by a few people’s bad experiences with it. When I have tried to advocate for Swift because of the work I am doing, I get my experiences brushed off because of my boss. I am told that of course Brad Larson can use Swift to control robots. He’s a genius. Us normal people can’t use it because it’s too complicated.

Again, there is a difference between broken, complicated, and unfamiliar. If you go into Swift thinking it should be just like Objective-C, you are going to be disappointed. If you go into it knowing that it is unfamiliar and that you have to fundamentally approach things a different way, then you might be okay with it. If programming was easy, then everyone would be doing it. Just because something is different than the way that you are used to doing something doesn’t mean that it is wrong.

I hope that people who are discouraged will eventually change their mindset about how to approach Swift or some other hybrid language with functional features. Life gets boring if you just do the same thing over and over again in the same way. Programming is a young discipline and we haven’t yet reached the point where we absolutely know that the way we are doing things is best. It will continue to grow and evolve and change. And that’s a good thing.