Doctor Who: Series One- The Long Game

Eccleston and Piper take on the future.

Eccleston and Piper take on the future.

This is the last mediocre episode of the first series. Each episode after this is a classic or furthers the end game for this series. As such, this episode was kind of hard to get to because it wasn’t one of the ones I was super enthused about watching and reviewing for this blog series.

This one isn’t “bad” per se, it’s just not nearly as special as the stuff that comes after it.

Time to churn through this one and get to the good stuff!!

The Failed Companion

The point of the Companion in Doctor Who is to have an audience proxy. You’re supposed to be able to watch the show and imagine that you are the one traveling to distant times and spaces. They’re supposed to be relatable so that you can picture yourself as one.

Russell T. Davies trolled us a little with Adam. He established that not everyone is companion material. Some people are special and they get to be companions. People who are selfish Adam Eyeor thoughtless don’t get to keep their Golden Ticket, which is what happened with Adam.

Adam gets mentioned in an iO9 article about depressing Companion departures and for good reason. While his departure isn’t as depressing as Donna Noble’s, it still illustrates how one stupid decision can fuck you for the rest of your life.

I only saw this episode once and didn’t really grok why Adam was considered irredeemable. Going through it again, I am seeing small moments that foreshadow why he was kicked to the curb. We see the moment when he has the cell phone that can call the past that he knows he should give back to Rose, but you see him deliberate it and decide to keep it instead.

Things continue to get worse as the episode goes along. It’s rather disappointing to see someone give in to their base instincts. I realized as the episode went on that Adam is basically Biff from Back to the Future. If there was a sport’s record book available in Satellite Five we would live in an unfortunate reality. It’s too bad he can’t go back and invest in Apple when it was nineteen bucks a share.

Again, it’s really interesting to go back and see this episode and see all the stupid shit Adam does. I barely remembered this episode. Seeing the iO9 article I didn’t even remember Adam was a character. Going back and watching this I am puzzled why this didn’t leave a more visceral impact on me. The part where The Doctor is being given away because Adam opened up his mind to the High Intelligence to send a message to himself in the past to invent/invest in the right technology is really memorable and I honestly don’t know why it didn’t make a bigger impact.

Satellite Five

Wasting Simon Pegg is a sin against humanity.

Wasting Simon Pegg is a sin against humanity.

Yes, I am going to get crap from Chris Adamson, but this whole episode seems like a giant cautionary tale about Fox News and Rupert Murdoch. This is a prospective future where the human race lets itself be controlled by an infotainment industrial complex. There is a higher power using its influence to control the reality experienced by humanity to ensure that no one asks any questions about what is happening to society. People are allowing themselves to be blindly led and live in terror of amorphous threats with no solid or concrete parameters.

The plot device where people open their brains to the main computer is a decent allegory for our current social media experiment. People are voluntarily pumping their personal information out to people who capitalize on it and are using it to design ever more manipulative ways to contour our reality.

It’s kind of disappointing that they have Simon Pegg here and he isn’t using his real accent and he’s blond. All of his personality is kind of stripped. It makes me sad.

The Doctor and Rose

It’s fascinating to see how far Rose has come since the beginning of the series. This is only her seventh outing, but she is giving the grand tour to Adam like a pro. It’s kind of cute to see The Doctor watching her with a modicum of pride for her confidence in showing him the ropes. His little companion is growing up!! However, she hasn’t learned not to give away the TARDIS key yet. Bad Rose!

It’s interesting to see how proud The Doctor seems of Rose. In the first several episodes of this series he treated her as something of a pet. She was a curiosity. She was someone who was more remarkable than the people around her, but she was still an inferior human.

The bad CGI!!! It burns!!

The bad CGI!!! It burns!!

There are parts in the episode where The Doctor seems to delight in the growth that Rose has made over the course of the season. He chastises the woman who doesn’t think the heat is an issue by saying that Rose is asking all the right questions. It’s also fun to see Rose’s sort of smug, “Ha ha, I got praised by The Doctor!” look at this comment.

I find it personally fascinating to see how their relationship evolves over the course of this series. I don’t really feel that many other companions go through this process. The only other companion I can think of who really profoundly changes over the course of the series is Donna. This first series had to do a lot to introduce Doctor Who to a new generation of people while staying true to the old series. The decision to make The Doctor rather grizzled and militant and to have him slowly recover his lost whimsey was a really interesting and successful choice by RTD.

It speaks to the strength of their relationship that The Doctor didn’t kick Rose to the curb as well after this incident. She wanted to bring Adam with them. She gave him the key. She made a mistake. He could have decided he was done with her after this, but he needs her and he knows it. There wasn’t a moment when he even considers that course of action. It speaks to the strength of their relationship even this early in the season that it feels natural that he wouldn’t take it out on her. Also, that would have disrupted the season and that would have been an unwise choice.

One of the complaints that I have about the Moffatt era Doctors is how little they seem to grow and evolve. Yes, you can argue with me that this past series with Clara and Danny Pink was somehow different, but it really didn’t capture me in the same way this series did. I don’t know if it’s the chemistry between Eccleston and Piper or if he was just such a good actor that no one else has been able to approach what he did. I truly believe he shows the greatest range of realistic emotions of all the modern Doctors. Peter Capaldi never really captured the extreme goofiness and the extreme menace that Eccleston oscillated between throughout each episode of this series.

For now I am delighting in watching his relationship with Rose. When they break onto Floor 500, The Doctor comments that everyone seems to have dropped out besides Rose and himself. And he likes it that way. So does she.

Don't fuck with us.

Don’t fuck with us.

The Future is Fragile

One of the biggest aspects of most science fiction from the twentieth century is this pervading idea that humans will conquer the galaxy. Except we don’t mean militarily. We will colonize space and explore strange new worlds. If you look at Star Trek, humanity is at the epicenter of galactic civilization. In Doctor Who, thousands of races interbred and descended from humanity. In Doctor Who, humanity has a destiny that The Doctor spends so much time to shepherd to fruition.

One aspect of this episode that is interesting and terrifying is just how tenuous that future is. The future we view in this episode isn’t the future we expect from humanity, but one that is terrifyingly similar to the one we live in now. A future where all of humanity’s information about the world is manufactured and filtered through a mechanism to warp our basic potential.

One of the reasons I hate the current Star Trek movie reboot is that J. J. Abrams clearly didn’t understand what made Star Trek appealing to begin with. Star Trek came out at the height of the Cold War and it was created to give hope to humanity that one day we would overcome our differences and move forward into the future united rather than divided. I feel like this episode is kind of like what would have happened if at various critical points in our history our better natures didn’t prevail and we never progress past where we are now. It really drives home this idea that the future is fragile. We have the potential to do great things but it takes very little to derail our bright future.

However, it’s nice that in our evil media future that we no longer just have the male/female genders, we have male/female/multisex/undecided/robot. Tolerance is always a good lesson.

Conclusion

I am glad I went back and rewatched this episode. It didn’t leave a huge impact on me initially, but there is a lot of good stuff in here that I missed the first time through.

Now that we are through the slow part of the season, we get to go and visit one of the strongest episodes of New Who: Father’s Day. Stay tuned!

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.

To Make Life Important

There is a scene in the last episode of the first season of Six Feet Under that asks an incredibly important question:

Tracy Montrose Blair: Why do people have to die?
Nate Fisher: To make life important. None of us know how long we’ve got. Which is why we have to make each day matter.

I think about this a lot in my more morbid moments, which I have had more of recently.

I have spoken about being depressed somewhat openly because I think it’s important to acknowledge that people get depressed. I think we tend to stigmatize people who don’t conform to what we think of as “normal,” which includes people with depression, the transgendered community, and people who experience things most others do not. I am somewhat dismayed by our society’s uncomfortableness with others having non-normative emotions and experiences.

I saw several amazing talks by Leon Gersing, aka Ruby Buddha. Seriously, if you ever have a chance to see him speak, DO IT!!

In one of his talks, he said he spoke to people about what their goal was in life. Many people told him their goal was to be happy. He laughed at that and said, “Good luck with that! Happiness is an emotion. Happiness is transitory. Happiness only has meaning because you have misery to counter it. If you’re happy all the time, you just feel normal.”

The Neurotypical Dance of Shame!

The Neurotypical Dance of Shame!

I was at the doctor and I saw this book: “Eeyore, Be Happy”. Eeyore is the perpetually depressed character from Winnie the Pooh. I was rather disturbed by our society’s willingness to ignore his feelings because they make us uncomfortable. We have an idea about how we want people to be and we don’t want to recognize the ugly reality that life is more complicated than we care to believe.

We want Eeyore to be happy because his depression makes us feel bad. We want everyone to be happy. I see similar feelings expressed by introverts who feel like we, as a society, value extroversion so they are supposed to conform to our expectations and feel incredibly uncomfortable with trying to be themselves.

I have spoken to a lot of people who feel that their natural emotions and feelings are seen as deviant and threatening who are incredibly depressed because they feel they are not “normal.” I try to do what I can to assure them that they are not creepy or deviant, but there is only so much I can do.

I have had people approach me about going to see a psychiatrist and getting on anti-depressants to make myself feel “better.”

I respectfully decline to do so.

I do not want to numb my experiences. I am going through a rather traumatic time and I don’t think taking a pill that blunts this experience is the best thing for me. I would rather experience my sadness so that when it alleviates and I feel happy again, it will mean something.

I know our society is uncomfortable with melancholy and sadness. I know we want everyone to feel happy all the time and not talk about our various disappointments and let downs. We don’t want to hear about people’s failures even if they learned far more from a failure than they did from a success. I don’t think that’s healthy. I think for happiness to have meaning, you need something to contrast it to.

I am not saying I don’t think anyone should take anti-depressants. I know if you are thinking of taking your own life that numbness is probably preferable to thinking that there is no point in going on any longer. I am just saying that it is my choice to not take anti-depressants. I am trying to use meditation and mindfulness to deal with my depression. It is my choice to fully embrace and experience my sadness. I want to experience my feelings in my own way and everyone is entitled to choose how they deal with their own lives.

I am bothered by the fact that we have an idea that there is only one way of doing anything. I think there are many ways of doing things and what might work for 100 people might not work for you. You should be able to choose how you experience your life and no one should pressure you to do something you don’t want because it doesn’t fit in with their narrow view of what is “normal.”

I feel incredibly privileged to be in a position where I can live my life the way that I want. I know many people are not so lucky, which is why I am speaking about this. It would probably be safer for me personally not to disclose this information publicly, but I feel that it is important to talk about it because if we ever want anything to change, we need to acknowledge that a problem exists. I am sick of seeing my friends pretend to be someone else because they don’t feel like they themselves are okay. I would like to change that.

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.

Functional Programming in Swift: Chapter 3 – Wrapping Core Image

**Note- I originally took this post down because I wasn’t really happy with how I organized it. I also believe that this series has a larger readership than I originally envisioned and I felt that the assumptions I made about this post were confusing. I am going to repost this post and figure out how to proceed in a way that is useful to everyone who is reading my blog. **

I am writing a series of blog posts analyzing the code and concepts from each chapter in Functional Programming in Swift. I am assuming if you are reading this that you are following along in the book, so I am not references their specific code snippets in my blog.

The purpose of this chapter is to show the reader how to do a very important thing in programming, which is wrap a framework or an API written in another language, such as C.

Being able to integrate lower level code into your applications is a really important skill to be able to master. Over the last month I have had a project where I had to write a few wrapper classes around XML-parsing functionality in the C library libxml2, which I will write about in a later blog post. Learning how to search the sparse documentation for this library and figuring out how to integrate it with Swift was a really interesting and painful learning experience. Even though a lot of times I wanted to hang my head and weep in despair, after I got it working I felt kind of like one of those douchebag programming ninjas that recruiters keep contacting me looking for.

This might not be the best sales pitch for why you should care about this stuff, so without further adieu, I will get to the content.

Core Image

Even though the focus of this chapter wasn’t specifically on learning Core Image, I wanted to take a moment to talk about it because it’s a neat little framework.

Core Image is a framework that allows you to add filters to photos in both iOS and Mac applications. Core Image is very similar to GPUImage, except GPUImage is open source, so you can go in and actually see how all of the shaders were written. Core Image has a few more filters than GPUImage has. In iOS 8, Apple opened up the ability for you to write your own Core Image filters, which wasn’t possible before.

Core Image is, as my coauthor Chris Adamson calls it, “stringly typed.” If you want to use a filter from Core Image, you have to reference it in a string. If you spell the filter name wrong then your project will fail silently. Whereas you can use auto-complete on other parts of your project to ensure that you don’t get felled by spelling errors, there is alas no auto-complete in Core Image.

If you’re interested in how to write shaders for either Core Image or GPUImage, I recently wrote an article about it for Objc-io. There are a lot of other neat photo articles in this issue too, so be sure to go check it out if you want to know more about how to use photos in your iOS/Mac applications.

But enough of my own buzz marketing, on to the actual content of the chapter…

Wrapper Type

Generally speaking, Core Image has a rather repetitive pattern. You take an image, filter it, then you take that result and feed it to the next filter you are using.

If you’ve ever used Core Animation or another framework that affects the output of what goes on your screen, you will know that the order you implement your changes in affects your output. The same thing goes for your image filters. If you add more than one filter to an image, changing the order will change what the output image looks like.

Since you are using a filter chain where you are taking the output of one operation as the input of another, it makes sense to encapsulate this functionality into its own type. In this case, the type is a function that takes a CIImage and returns a CIImage.

CIImage filters all take different types of parameters. Some filters only take an image as a parameter while other ones many more. We want to be able to customize our filter functions to take the correct number of parameters. Regardless of what kind of filter we are making or how many parameters they take, we want each of our new custom filter functions to return a function that conforms to the Filter type alias. Naming this function type makes our code cleaner and safer by assigning a name to it and removing code we would have to write over and over again.

Convenience Initializers and Computed Properties

We want to make it easier to extract the output image so that we can chain this filter’s output image to the input of the next instance of our CIFilter class. We are using a convenience initializer and a computed property to extend the class to customize it for our needs.

The class extension has three pieces we are going to look at: a convenience initializer, a computed property, and a typealias representing a dictionary that holds our Core Image parameters.

Any time we create an instance of a class or a struct, we have to handle initializing it. Back in Objective-C we had our pattern of [[NSString alloc] init] to initialize our instances. We still have to initialize our instances, but like many thing in Swift, this process has been simplified. Instead of the long, verbose way of initialization, we just use “()”, which is a void function call. This initialization function is void by default, but life wouldn’t be very interesting if we couldn’t customize things to suit our needs.

Just because the default initializer is a void function does not mean that it always must be. If we have want to pass in parameters to the initializer, we can do so. In the example used in this chapter, we are trying to customize the CIFilter class. We are doing that by extending the class to include the functionality we need.

The normal CIFilter initializer just takes the name of the filter being used. We want to initialize the filter with the dictionary of parameters along with the name. In order to make it easier and clearer what we are doing, we are typealiasing the dictionary of parameters and passing that type into our convenience initializer. Within the convenience initializer, we are calling CIFilter’s designated initializer, essentially wrapping the base CIFilter initialization within another function that allows us to do more.

The last piece of our extension is a computed property, which is our coveted output image. We are treating an outputImage property that is of type CIImage and instead of just setting it to a CIImage, we are checking the value for the key that we are using (which in this case is the name for the CIFilter we want to use) and returning a CIImage.

Computed properties are interesting. They do not store a value. Instead, they are a getter to find and set properties and values indirectly. It is my impression (which, if wrong, I would really appreciate someone correcting for me) that they are similar to functions but with slightly less overhead. Natasha The Robot says in this post that a computed property is a function disguised as a property. I am on the fence about what the difference is between a function and a computed property, so I am on the fence about how to handle them. Would like to write about them further in a future blog post, so hit me up with any thoughts you have at some point in time.

Compositing Filters

Anyone familiar with special effects or Photoshop might be familiar with compositing. Compositing is the art of layering multiple images and filters together to create a single new image. Compositing encompasses everything from making collages out of multiple images to generating large Photoshop pieces of art that have hundreds of layers.

The way we are using compositing here is that we are taking several simple image filters and we are combining them together to make a larger, more complex image filter. Many of the large, complex image filters in both Core Image and GPUImage are composites of smaller, simpler filters.

Core Image has an entire section of filters that are exclusively used to composite images. If you have a chance, it’s a lot of fun to play with compositing filters. If you work with Photoshop and you’re familiar with the various blend modes, these are represented in this category of Core Image filter. You can get some really awesome effects using compositing and blend modes in your photography and I encourage you to explore them.

The first composite filter we are creating is one that superimposes a color on top of the original image. It is made up of the CIConstantColorGenerator and CISourceOverCompositing. The Color Generator is just creating a blanket color layer whose output is not at all affected by the underlying image. The Source Over Compositing is simply taking one image and placing them over another. In our case, it is placing the Color Generator layer on top of our image we want to filter.

After we create this composite filter, we are chaining it to the output of the blur filter. So, first we are taking our image, applying the blur filter, then taking the output from the blur filter and applying our composited red filter to the top. We are specifying that the opacity on the red filter is only twenty percent so that the the second filter doesn’t completely block out the first filter or the input image.

Adding Functionality

Since being able to compose two or more filters together is an incredibly useful thing to be able to do and something we might need to do many times, it makes sense to write a custom function to simplify this process. Also, considering the number of inputs we are dealing with for this functionality, being able to simplify the code and avoid missed parens is a good use of our time.

The composeFilters() function being defined takes two filters as parameters and returns a new filter. In the code sample, we see that we are setting a variable to hold the output of this function, which is a filter. We are then creating a second variable that will hold the output of the filter we just created. Since the output from the composeFilters function is a filter, when you use the variable you are calling a Core Image function that is filtering the image being used as a parameter. When I read through this at first, it took me a little bit to parse apart the logic.

Infix Operators

Infix, Postfix, and Prefix notation is a complex way of labeling a phenomenon most programmers are familiar with: Where to place an operator.

Infix operators are placed between two operands. Which is an obtuse way of saying you write an equation like this:

X + Y

The operator, in this case the “+” sign, gets placed “in-between” the numbers it is operating on.

Prefix operators are placed, just as they sound, before the operands:

+XY

I’ll bet you can figure out how to write a postfix operator now:

XY+

What do these operators do? Why are there a bunch of them?

Think back to your Algebra class. Remember PEMDAS? That acronym helps us remember the order of operations. If you want to isolate two numbers that you want to add together before the result is multiplied, you had to put parentheses around them to ensure that the product was calculated, not just the first number. Infix, Prefix, and Postfix operators affect the order of operations in mathematical calculations. All equations can be represented and translated in each style, so theoretically you don’t lose any functionality by not understanding how to use each type of operator.

These operators are incredibly common in mathematics. Since Haskell and other functional languages evolved from Lambda Calculus, there are a lot of operators and notations that are foreign and unfamiliar to people like me who flunked calculus and grew up on imperative programming.

Swift lets you write your own custom operators. There is a list of ASCII characters that can be used to write custom operators. You have to specify what type of operator you are defining. If you are defining an infix operator, as we are doing here, you need to specify the direction of associativity. In standard mathematical equations we have associativity from left to right. You can choose left, right, or none. None, which is the default, means that you can’t place your custom operator next to another operator with the same precedence.

I am still trying to figure this part of the chapter out. I don’t know why the custom operator “>>>” was chosen. I don’t know if the character is significant or important. My understanding of the code as written is that instead of using a text label for our composeFilters function, we are using symbols. I know this is a common thing in languages like Haskell and unfortunately I haven’t delved into them enough to be able to fully answer my own questions about how infix operators are being utilized here. Again, if someone has an answer, I would appreciate a ping on Twitter.

Currying

Currying is the process of taking one function that takes multiple parameters and breaking it down into a sequence of functions that each take a single argument. For example, if you were writing a function that took two floats as a length and a width for a rectangle, you could rewrite this function to take the first parameter and then evaluates a sequence of functions, each of which take one parameter.

Currying is found in languages like Haskell. In Haskell, the language only allows you to pass one parameter into a function. Currying is a way to get around this constraint.

Side note: Both Haskell and curried functions are named for Haskell Curry. Curry was a mathematician and logician who hopefully didn’t get his lunch money stolen too often for having such a strange name.

Currying gives us some options for customizing our functions. Currying allows us to seed functions by supplying too few arguments and using it as a basis for fully implementing another function. It allows us to choose if we want to apply the function to all of our parameters.

Since this post is getting rather long, I don’t really want to write a comprehensive explanation of currying and why you want to use it. I will save that for another post. The concept of currying is introduced in this chapter, so I wanted to cover it just a little. I would also like to look over the code from this chapter to get a better grasp of currying before I try to explain it further.

Conclusion

There was a lot of stuff being touched on in this chapter. Core Image, infix operators, and currying. These are complicated frameworks and concepts, so again, don’t get frustrated if you got through this chapter not fully understanding how everything works.

Up next, we have our old functional friends Map, Filter, and Reduce. See you next time!

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.

Functional Programming in Swift: Chapter 2- Thinking Functionally

*Note: I strongly recommend following along in the book with this blog post. I am not going to be recreating the diagrams or the code here, so if you don’t have the book open when you are reading this post, you will be very confused and I would not like that.*

This first full chapter of Functional Programming in Swift introduces one of the most important new concepts in Swift: Higher Order Functions. I will get into higher order functions in a moment, but first I would like to give a little bit of context as to what the example of the chapter is about.

Battleship

The example used for this chapter is called Battleship. I, like many other people, associate Battleship with the board game. Since many programming textbooks use common games with known rules to teach programming concepts, it was understandable that many people thought that this example would be about the board game Battleship. This is not the case.

Back in 1994, the Office of Naval Research was exploring rewriting some of its defense software. Like any good agency, they didn’t want to just pick a programming language out of a hat. They wanted to benchmark which language would be the most efficient language to use for this project. They were concerned with a few factors:

- Development Time
– Lines of Code/How Concise is the Code
– Human Readability
– Maintainability

For a very long time, functional programming languages were considered to be impractical for real world applications. They were an interestring curiosity and another approach to programming, but the enforced static nature of functional languages and the lack of mutable variables seemed to doom functional languages to never be implemented in actual projects.

This study proved that a purely functional language could not only be used effectively in a real application, but also proved that this approach could be even better than an imperative approach.

If you look over a lot of the examples in this chapter, you will notice a lot things that are not present in our traditional games of Battleship:

- Checking the range of your weapons
– Avoiding engaging enemies too close to your ships
– Taking the location of friendly entities into your equations

These are not things we think about when playing the board game Battleship, but they are incredibly vital things to consider if you are a naval ship engaged in battle with actual enemy combatants. These are not small considerations. You don’t want to accidentally frag your fighter jets when you are aiming for an enemy ship. Any targeting program that you design must account for all of these considerations.

This beginning chapter takes this example and shows how Hudak and Jones were able to work around these constraints in a functional manner that was more efficient and easier to maintain than the traditional imperative way of approaching these problems.

Imperative Complexity

Our initial calculation is very simple. We are assuming our ship is at a location and we are trying to determine if another point is within range of our ship. Our range is represented by the radius of a circle and we are simply passing the location of our ship (position) and the distance we can shoot (range).

We are then using the Pythagorean Theorem to determine if our target point is within range of our ship. a squared plus b squared equals c squared. In our case, target.x squared plus target.y squared should be less than or equal to our range squared. Our first function is taking the square root of the two target coordinates and returning it only if this qualification is met.

In order to keep things clear, we are using a type alias so that we don’t have to remember that the CGPoint object is our position and the CGFloat is our distance. We will see type alias again, so don’t forget it.

So far, so good.

As the program grows in complexity, it becomes harder to continue to maintain the function. We keep adding additional parameters and constraints. I am going to honestly say at this point I developed code blindness and stopped looking at the code. Suffice it to say, this once simple function grows to a large mess of spaghetti that kind makes me weep for the future of human civilization.

I am not going to untangle the spaghetti code because we aren’t supposed to be doing this anyway and I am not going to encourage you to write unmaintainable code. Bad Swift developer!!

Going to skip ahead to the functional way to deal with these constraints.

The Functional and Rational Approach to This Problem

There is one very important thing to remember about functional programming versus imperative programming:

- Imperative programming is about telling the computer how to do something.
– Functional programming is about telling the computer what to do.

In the above spaghetti code, we were getting over wrapped up in how the conditional logic would deal with all of the various contingencies of our problem. If our point is in range but it is also too close to a friendly, what do we do? It is easy to get overwhelmed by the complexity of implementation.

So let’s take a step back and ask what are we actually trying to do, without thinking about how it will get done.

We want to know if our point is in a region where we can target it.

Remember when I told you to remember type alias? We are bringing it back here. A type alias allows you to assign a label to an existing type so that if you have multiple objects/properties/variables that are all the same type, you can assign a label to the one specific instance of that type.

We know that strings and numbers and classes are all types, but there is another thing in Swift that now qualifies as a type: a function.

Functions in functional programming are values, no different than strings or structs. They can be passed around and referenced exactly the same way you would work with any other kind of value. The best analogy I can think of for this is a string. In C we didn’t have real strings. Stings were an array of chars that were eventually, in later languages, encapsulated into their own type. As you work more with functions as their own discreet values, it should get less weird to think of them in this way.

We can create a type alias for a specific function type. In the example in the book, we are creating a type alias for a function that takes a Position as a parameter and returns a Bool.

So instead of our initial function that uses the Pythagorean theorem and returns the result of that calculation, we are instead returning a closure that performs the calculation. Closures are simply unnamed functions. Basically we are taking the logic we had before and putting a nice, shiny function wrapper around it. We are wrapping a riddle inside of an enigma.

Why would we want to do this?

Let me give you a real world example of this in practice:

I work at a company called SonoPlot. My boss, Brad Larson, wrote a blog post about our project to rewrite our robotics control software in Swift. Since we are dealing with interacting with hardware, there are a lot of things that can go sideways that you don’t have to deal with when you are working with just software. Sometimes something goes screwy when we are communicating with the hardware and if we just send the command again it will go through just fine. Other times, the hardware is disconnected.

We don’t always know which one of these situations we will be in. We don’t want to keep sending commands to our robotics if they are not connected or on. Alternatively, we don’t want to tell the user that the robotics are not connected when they actually are.

To get around this situation, we created a special function called “runCommandAndAttemptSoftRecovery()” that takes a function as a parameter. We wrap many of our hardware functions in this function. “runCommandAndAttemptSoftRecovery()” will try to run the function we are passing in and if it doesn’t pass, it will attempt run the function again. If the function fails a second time, we handle the error.

Sometimes you will have some functionality that is important to apply to many parts of your project, such as our hardware commands. In times like those, being able to pass a function into the function makes it possible to reuse a piece of code in ways that weren’t possible with Objective-C or an imperative language.

In the example in the chapter, we are trying to figure out a way around the creepy spaghetti code and conditional logic. Rather than creating one Frankenstein’s Monster of a function that has to account for all of these things, we are creating a lot of small functions that account for discreet parts of this problem.

We check if the point is within range of the circe. We check the offset. We write a function that combines known areas that are in range so that they are in one data set instead of two. Each of these functions returns a function of the same kind, so they can work together to narrow down more discreetly if a point is within range of the battleship without hitting a friendly craft.

This is a rather difficult example to explain and I will honestly say that at this point I can only explain it on a high level. I strongly recommend looking at the final code and referring back to each individual function to see how they work together. There are truly reusable functions in the final function that behave differently based on their inputs and parameters. Sometimes looking at a final piece of code and following the logic through its various rabbit holes is the best way to understand how something works. That’s why we dissected frogs in high school biology class, even though I swear some of my teachers were sadists….

Takeaways

This is an introductory chapter. It isn’t expected for you to genuinely grok all nuances of functional programming from this.

Here are the points I would take away from this chapter:

  • Start thinking about what you want your code to do rather than how you are going to implement it.
  • Start trying to mentally break things down into smaller pieces. Instead of having some big, scary function full of state and conditional logic, think about what you are trying to do in smaller steps.
  • Get used to the idea that functions can be passed around like variables. Think of functions as things that take one thing and turn it into something else. If you have a piece of wood, that can be turned into many different things. It can be a table, a desk, or a bookshelf. If you think of a function that takes a piece of wood and returns a piece of furniture and think about how each piece of furniture can be different, this might give you a better idea about how to conceptualize passing functions in Swift.
  • Don’t get discouraged!! This is a different way of thinking. It isn’t going to be intuitive. I have been working on this for nine months and I have barely gotten to the point where this chapter makes sense. That is one reason I am doing these posts. This is just to get your feet wet with some functional concepts. You are not expected to fully understand everything at this point in time. If you feel dumb right now, join the club. You’re not the only one. Just keep working at it and eventually something will click.

I wanted to recommend some resources I am using to try and work through this book to get these concepts to make more sense:

I will try to add to my list of resources as I encounter new ones. If people have sources they particularly like and want to make me aware of them, please ping me at @redqueencoder

Again, if a lot of this is still super confusing, that’s fine. You’re in the right place. We’re all trying to figure out how to please our new functional overlords. It will take a while and no blog post anyone is going to write is going to make this immediately intuitive. Think back to when you learned programming for the first time. It took a while, didn’t it? Learning how to think takes some time and some work. Don’t get down on yourself. Keep at it.

Up next, we are tackling some Core Image. Stay tuned!!

Doctor Who: Series One- Dalek

EXTERMINATE!!

EXTERMINATE!!

Ah yes, the inevitable Dalek episode. It was always coming. It would be like having a Star Trek series without Klingons. It just wasn’t going to happen.

It’s hard to remember a time when the Daleks hadn’t been run into the ground. After half a season of new villains, it’s kind of nice to see a familiar face. We are also treated to a few breadcrumbs about the Time War that destroyed the Time Lords.

The Dalek

I do have to admit, I was a little more thrilled at seeing the Dalek than I thought I would be. Even though the species has been retconned and run into the ground, the moment when the lights come on and the Dalek starts yelling “EXTERMINATE!!” is still incredibly exciting. The reveal was done incredibly well and this has helped this episode age pretty well.

It can be hard figuring out a good way to reintroduce an old character to audiences who may not be familiar with the source material. Seeing how genuinely terrified Eccleston looks after handily dealing with a bunch of crises over the last few episodes is one of the reasons this episode is still so effective.

I realized that nearly every Dalek episode from New Who follows the same theme of them finding a Dalek that seems to be different than the other Daleks, one that has feelings and is capable of growth. The companion tries to convince The Doctor that this one is a special, unique snowflake. The Doctor gives the Dalek a chance, only to find out he was right all along. It’s really repetitive. It’s like watching Lucy snatch away the football from Charlie Brown.

I haven’t watched any Old Who, so not certain if this repetitive theme was actually a new idea back in 2005.
DalekEccleston

The Doctor

Eccleston does a tremendous job of selling The Doctor as someone who can be genuinely menacing. He spends a lot of time in the series being cuddly and adventurous, but this episode really drives home the point that The Doctor is a powerful being who has killed people in the past. He is the sole survivor of a war that wiped out two races of people, one of which was his own. The first few episodes sell him as the lonely god, the last of his kind. This is the episode where you realize that he is the one responsible for him being the last of his kind. His confrontation with the other last member of a wiped-out species is incredibly tragic.

On one hand, you can point to him and say that he made choices. He pulled the trigger that wiped out two species and he survived. What does he have to complain about?

It’s incredibly difficult to make the hard choice and to live with its consequences.

The Doctor’s interaction with the Dalek force him to process and deal with something he’s been running from since “The End of the World.” He doesn’t want to think about how he is responsible for a mass genocide. He wants to heal and explore. He didn’t want to be put in the position of destroying his own people. He wants to forget. This theme is explored in much greater detail during the 50th anniversary special, but it’s bones are established here, in this episode.

Facing uncomfortable reality.

Facing uncomfortable reality.


The scenes watching him torture the helpless and ridiculous looking Dalek are kind of disturbing. We’re used to this idea that The Doctor saves people and does impossible things. Watching him sink to a level of torturing a helpless creature and enjoying it is terrible.

I am actually interested in how many times The Doctor does terrible things. I know he’s done many over the course of the new series, but every time we encounter one it’s always disturbing.

On some level we expect The Doctor to be better than us. He’s not a human. He has lived for a thousand years. We expect him to be above all of our petty, meaningless concerns, to be more than we are. Watching him behave like a beast who enjoys tormenting the Dalek is terrible, not just because the act itself is terrible, but because the person doing it should be beyond such behaviors.

Adam Mitchell

We’re going to get into him a little more in the next episode, just wanted to mention that we are going to see him again.

Henry Van Statten

It’s nice seeing what the British think about Americans, but all things considered, if the Daleks were real I could totally see some asshole one percenter being the person who collects extra terrestrial artifacts.
roseDalek

Conclusion

This was an important episode in that it brought an iconic villain back to the Whoverse. I guess I didn’t have as strong of a reaction as I thought I might all things considered. The episode was good, but its impact has been blunted over the years by seeing the same Dalek story over and over again. Supposedly this Dalek and The Doctor are the last of their kind, yet the Daleks keep coming back over and over again. Why is it that the Daleks can keep coming back over and over again, yet the Timelords are irretrievably lost in time and space and meaning? Hell, we found out a year ago that they are still out there and not a peep about them in the current season. Well, except for The Master, but let’s not get into his own problems right now…

Up next, we have “The Long Game,” in which we find out what happens when The Doctor picks up someone who isn’t really meant to be a companion.