🔗 The long arrow operator in C++

I’ve always enjoyed a step into the absurd. This long arrow operator fits the bill.

Now, before we continue, you should realize that this post is not a serious one.

This also introduced me to the left arrow and the WTF operator.


🔗 How I’d Teach Computer Science

I think this is an interesting idea, but it’s a bit short sited. I can’t emphasize this enough, but Computer Science != software development. There is definitely overlap between the two, however, it is certainly possible to have one without the other. I have met many software developers who were excellent at writing software that didn’t know the first thing about the time complexity of a given algorithm. I feel that distilling computer science down to what equates as process training is a disservice to the Computer Science field (says someone with a Masters of Engineering in Computer Engineering and Computer Science).

I do think offering courses with development methodologies in the curriculum is a worthwhile goal for college course work. I’m embarrassed to admit that fresh out of my college course work, I was fairly unfamiliar with source control. I had classes that taught us how to create UML diagrams to map model relationships for our OOD assignments, but I had not learned how to properly use source control, or how to plan a project, or what constitutes a good bug report. Shortly after landing my first job, I felt shame in what I didn’t know. I felt like a failure because I was unfamiliar with some of the technology stack. I felt inadequate around coworkers even though I held the highest degree. I remember being bitter towards my education.

Over time, my bitterness faded. I learned the different methodologies, different languages, and different tools of the trade. These came easy to me with a little patience. I still wish I would have had professors who had pushed us to use some of these tools/methodologies in our projects, but I eventually forgave them. I learned to be proud of my Computer Science background and it eventually set me apart from others in my field. It alone does not make me a better developer, but it’s an extra tool in my toolbox that others may not possess. I think this appreciation for my education has turned me off toward some of the formal education bashing that resides in my profession. There are many developers who tend to negatively view a traditional education. That’s okay. It’s their right. I just want to point out that those things are not equal, but they also don’t have to be mutually exclusive either.


How'd That Get in There?

A few weeks ago, Ashley and I were watching John Oliver’s piece on the state of Puerto Rico’s economy. One of the contributing factors in Puerto Rico’s current state is the limbo in which the territory finds itself. It’s not quite a state and it’s not quite a sovereign nation.

One of the more interesting revelations in the piece is that there were laws passed that hurt Puerto Rico that were buried in a larger bill. This intrigued me. My initial thought was, “Why would congress allow seemingly unrelated proposed laws in a larger bill?” I then immediately thought of all the terrible commits I’ve had in projects where I bury some seemingly innocuous change in a patch for a completely unrelated issue and it comes back to bite me on the ass. Suck.


Relying On Experience

I’ve recently been pushing for use of pull requests in our workflow at LunarLincoln. I believe code review to be an important aspect of development and I feel that pull requests promote code review with every feature added. This kind of attention to detail isn’t just for open source projects on Github.

My Bad

There is an issue to opening an, ideally, small pull request for every new feature: inevitably, a new feature will rely on a feature that exists in an open pull request that has not been approved yet. What do we do in this situation? Normally, I would just create my new feature branch from the open pull request branch and work away. I did not do that this time. I had not thought that far ahead. After a few commits on my new feature branch, I realized I needed the work from an open pull request branch. So I did the logical thing and merged. I did not include the --no-commit --no-ff. I unintentionally merged code from an open pull request onto my new feature branch. To make matters worse, I edited the merge commit and royally screwed up my feature branch. So much so that later, I was testing my new feature branch after having merged in the approved pull request, the changes from the approved pull request was missing. Yikes.

My Experience

What was I to do? I had never run into this situation before. My first thought was to create a new branch and manually copy over my changes, then open a pull request for this copied branch. This would surely work, but there were a few commits worth of work (about 8) and that seemed tedious.

After pondering for a bit, I did create a new branch. I then used git’s cherry-pick command to bring over the commits from my fubar’d branch and save face. I had never used the cherry-pick function, but I was aware of its existence from the docs and from previous developer given talks at meet ups. While I didn’t have direct experience with it, I was able to use my indirect experience and solve my problem.


🔗 Increase Defect Detection with Our Code Review Checklist

An interesting piece from Fog Creek regarding their review process.

I found this link on HackerNews and one of the comments on the story caught my eye:

I don’t believe a code reviewer should even have to know about the requirements of the feature/bug, and should focus more on the design/quality vs. whether it works.

I believe this is a fallacy. This is like saying an editor does not have to understand what he or she is reading as long as he or she is focusing on grammar. Should the editor not be able to ensure that the author is getting his or her point across? Should the reviewer not be able to ensure that the code should functions as intended? If the reviewer does not understand what the code is meant to do, how can he or she understand whether or not something such as a conditional is behaving correctly? That a loop ends at the proper step? While the reviewer may not need to know every implementation detail, the reviewer should have at least a working knowledge of what is expected of the product. I can write nonsensical code that does not cover the requirements for a product that is syntactically valid and even clean. Should the reviewer focus more on the design/quality of code? Sure. I just believe the reviewer should know at least what he or she is reviewing.


Beginners

I believed that this negative behavior stemmed from arrogance, ignorance, and callousness. After reading the aforementioned article, however, I have switched my line of thought: I now believe this negative behavior stems from a deep insecurity that developers have of being wrong. I believe that we constantly fight to prove our methods (tools, languages, or platforms) are the correct choice. I also believe that this behavior is not necessary and that most developers will eventually grow out of it as though it were a juvenile phase in our adolescence that we will, hopefully, look back upon in embarrassment. I am at the embarrassment stage in my career now. I feel bad for the negative behavior that I exhibited in my development youth. I was not only negative, but borderline belligerent at times. I think this behavior started and manifested itself due to the environment in which I started working. We need to take our environment and who we surround ourselves with into consideration. You eventually become what with which you surround yourself. I am glad that I am starting to surround myself with positivity.


Better Git/Vim Commit Messages

I recently decided that my Git CLI experience would be greatly approved with the aid of spellcheck. Luckily, I stumbled across a post detailing how one can enable spellcheck in Vim (my default editor). Unluckily, it did not work for me with Yosemite’s default version of Vim in Terminal. After struggling with this for a bit, I finally decided to upgrade to the latest version of Vim via Homebrew:

$ brew install vim

After installing the latest version of Vim, I created my ~/.vimrc (I am guessing this is not created by default as I did not see it on my machine) with the following content:

set backspace=2
syntax on
autocmd Filetype gitcommit setlocal spell textwidth=72

The first line enables what I believe to be the correct behavior of the Backspace (Delete on Mac) key: while in insert mode, the character immediately to the left of the cursor is removed and the cursor moves to that position (along with the text shifting to the left). I stumbled across a post indicating that this is not the default behavior in Vim, but it is the behavior I expect.

The second line turns on syntax highlighting. What I found to be unique about this feature is that it will actually highlight your Git commit message in such a way that the “title” of your message is highlighted to indicate when your title is too long (the recommended length, according to Github, is 50 characters). It also helps highlight comments in your commit messages.

The third line is the “money” line. This line enables spellcheck for gitcommit files. This line also includes a nice little extra to wrap our commit message bodies at 72 characters per line, which is the recommended length according to Github.

One other little tidbit I came across is you can use the following to ensure that Git uses your preferred editor (meaning the version of Vim I have installed via Homebrew):

$ git config --global --replace-all core.editor $(which vim) -f

I am not sure if this change is strictly necessary; it may just be belts and suspenders, but I would rather be safe than sorry.

If you want to know more about my setup, be sure to follow along under my Environment section.


Android vs. iPhone Cage Match!

I have been asked to participate in a panel. The panel will be a debate/discussion between mobile developers on which mobile platform is the best. I have been tapped for the iOS side. Leading up to tonight’s event, I have been jotting down my notes on the talking points I was given by my team. I have decided to post my notes for posterity. Each section title will be a question that I was given by the iOS team, followed by my notes. Enjoy.

What Problems with the iOS Platform Still Need to be Addressed?

I find that there are many developer APIs in iOS 8 that do unexpected things or are broken. I believe that Apple could probably use a development cycle to just clean up the platform and make it a bit more robust. I think it’s atrocious that Apple still offers flagship iPhone models with 16GB of storage. I don’t really care about expandable storage, but the fact that the baseline model comes with a paltry 16GB is ridiculous. I can’t recommend that device to anyone. I also feel that it’s time for Apple to increase the amount of RAM found in iPhones. New iPhone models currently come with 1GB of RAM. I honestly don’t see a performance hit from this in day-to-day operation, but there are times when I notice it (mostly when I have had Safari in the background for a while and upon returning to Safari, my open tabs reload since they are no longer in memory).

How Long Would it Take to Become a Competent iOS Developer? An Expert Developer?

I honestly feel that both platforms are fairly equal in the length of time it would take for you to become a competent or expert developer. There are so many great resources out there for both platforms (the developer documentation for each platform is top notch and you can usually always find an answer to your question on Stack Overflow, which has a very active community for both platforms). I think the community behind iOS development is probably larger at this time, but its fairly comparable. I think you can probably become a competent developer for either platform in 2-3 months. You can become an expert developer in a year. The key is to have someone who can review what you write to keep you honest and to ensure that you are observing good coding practices (specifically for that platform).

Where do You See iOS as Superior?

I feel that iOS is superior in a few different areas (although I’ll admit that some of those gaps are closing and some of the ways I feel iOS is superior are purely subjective). These areas are developer tools, the development language/system, user experience, and the camera.

Developer Tools

I feel that the developer tools that Apple provides are still better than the tools provided by Google. I believe Google has closed that gap significantly with Android Studio (IntelliJ users rejoice!). My first Android development experience involved Eclipse and, while Eclipse is what is is, it always felt a bit hackie to me. I feel Google is still lagging behind when it comes to user interface layout. The Interface Builder piece of Xcode is so easy to work with and what you see is pretty much what you get. I think Instruments is far and away better than any of the profiling tools provided to Android developers by Google.

Development Language/System

I believe the iOS development language du jour (Swift or Objective-C) is superior to Java. While language preference is purely subjective, there are some objective features where I feel like the iOS development platform is head and shoulders above the Android development platform. One of those is iOS’s Automatic Reference Counting (ARC) vs Android’s Garbage Collection. Garbage collection is an old idea that Android has implemented. It’s a methodology of reclaiming unused memory. It essentially scans the devices memory and determines which objects are currently being referenced and which objects are not. It then deallocates any objects that are not being referenced to reclaim memory (this is a very elementary example of how garbage collection works, so please forgive its crudeness). The issue with garbage collection is that it’s horribly inefficient. It’s slow (the length of the scan varies depending on the amount of memory in the system and how much of that memory is being used), requires more memory than other systems, and isn’t foolproof (it may be fixed by now, but I once knew of a way to guarantee memory leaks while writing Android code).

iOS has a thing called Automatic Reference Counting. ARC is not garbage collection (and to call it garbage collection is an insult). It’s a clever way of automatically managing your memory. It keeps track of how many references an object has (how many owners). When you reference an object, that object’s retain count increments. When you dereference an object, that object’s retain count decrements. Once an object’s retain count hits zero, it is released or deallocated. It is not foolproof, but it is definitely more efficient and requires less overhead.

User Experience

For my money, the iOS user experience exceeds that of Android’s user experience for the majority of users. On iOS, the only variability in user experience comes from the hardware. If you’re using an older device, your experience can be different than it would be on the latest and greatest hardware. Your experience can vary wildly on Android as you have different hardware manufacturers. Not only can your experience change based on the manufacturer’s build quality or the hardware specifications, but Android manufacturers are also able to “customize” (read: make it shitty) the operating system so that their devices may stand out amongst the numerous other Android devices on the market. You can, of course, install a different Android mod on your device. To me, that can be a bad user experience. I’m going to have a very difficult time explaining the steps of that process or why a person should even attempt to do that. Of course, I realize that one of the features or selling points of Android is the freedom for a more knowledgable user to customize his or her device. My opinion though is that the default experience that most users will have is a bad one. I doubt that first time, non-technical Android buyers are buying Nexus devices. I would guess that those first time, non-technical Android buyers are buying what the Verizon or AT&T sales person is recommending to them, which in many cases is an inferior product. I personally like the experience of stock Android Nexus devices. It’s just a shame that you can’t get that stock Android experience on most devices (it’s also a shame that Google no longer makes a normal sized device.

Camera

The last area where I find that iOS is superior is in the photos and the videos you can take with an iOS device. For my money, the cameras in iPhones produce better quality images than their Android counterparts. Android is closing the gap, but for the longest time I could usually take a look at two pictures (one snapped with an iPhone and one snapped with the leading Android device) and I could identify which one was captured with the iPhone and which one was captured with the Android device. Historically, pictures snapped with Android devices have always looked grainy or cloudy. When I’m at the park with my wife and son and I want to capture a moment, I’m never worried about getting a good shot with my iPhone. I know I’ll get a good shot with my iPhone.

Would You Ever Switch to Android? If So, What Would it Take?

I would possibly switch. I have used Android in the past as my daily driver. I just wasn’t “in love” with it. Certain components of the UI worked just differently enough (and, in my opinion, incorrectly) that it became irksome to use an Android device. I used a Nexus One (yeah, I’m one of the ten people who bought one of those). This was back in the 2.1, 2.2, and 2.3 days (fro-yo for life!). Out of quite a few UX things that irked me, two still stand out in my mind: tap targets and that damn back button.

I never became comfortable with the default Android keyboard (I’m aware I could have installed a third party keyboard, but I’m not a fan of that; I haven’t even installed a third party keyboard in iOS 8). My keyboard theory is that the default iOS keyboard placed the touch targets somewhere below the key view (and these would dynamically resize based on what you were typing). It felt as though the Android keyboard placed the touch targets right on top of the key view. I’ve always heard that when we tap on touch screens that we are actually tapping slightly below where we think we are tapping, so this theory always made the most sense to me.

The back button, in Android, is such a wildcard. What does it do? The simple answer is that it literally takes you back an activity (to use Android terminology). The OS keeps a history stack and as you navigate around your phone, it adds entries to that stack. If you hit the back button, it simply pops the top activity (the one you are currently viewing) off the stack and the activity that is now on top of the stack is the activity you’ll see. I always found this unnerving because if you don’t remember your navigation history, you don’t really have a way of knowing where the back button will take you. iOS always seemed a bit simpler to me. Each app is in control of its own navigation history. You’ll have a back button present if you have views in your history. If you reach the bottom of stack, there is no back button. To leave the app, press the home button.

For whether or not I would switch back to Android: it would really be a matter of Apple dropping the ball on what they have going. In my tastes and in my usage, my allegiance is Apple’s to lose. I’m a bit concerned about the quality of the operating system after some of the huge strides Apple has made in the past two versions of iOS, but, overall, it’s been reliable for me.


[1]: A memory leak is when an allocated object can not be deallocated until the process that owns the object is terminated or the system is restarted (depending on what owns the said object).

[2]: I just want a reasonably sized device and even the 4.7" iPhone 6 feels too large for me.


Radar Love

Earlier this year, there was a bit of a kerfuffle regarding filing bugs for Apple’s APIs and whether or not us developers should file them. In the past, I never really took the time to file them. I was either too lazy or assumed that the bug was in my code. I’ve always been pretty skeptical of faulting the tools for faults, but I’ve learned that occasionally we are charged with faulty tools and that this is okay. It’s part of development.

At Lonely Planet, we recently came across a particularly nasty bug that we determined to be an issue with iOS APIs. I created a sample project and filed a bug report with Apple. This is only my second filed bug report. Maybe it’s the newness of it all, but I’m not quite as jaded as some of the other developers out there. I hope I never fall victim to that, but I realize it’s all in context of past experiences.

Whenever I take the time to file a report, it makes me feel as though I am doing something good. I would want someone to file a report with me if I were to have a fault in my code. Why shouldn’t I return the favor?


Speed Kills

America is all about speed. Hot, nasty, badass speed. -Eleanor Roosevelt, 1936

Yesterday was kind of a crummy day. My back hurt. I forgot paperwork for my son that his daycare needed, which led me to me making two trips to his daycare (don’t worry, I picked up some nice coffee along the way). I had to sit in traffic. There were lots of little things that nagged at me yesterday. However, there was one big thing: I didn’t feel as though I accomplished much.

If you were to look at my commit history for yesterday, you might believe that I actually accomplished many things. You’d be mistaken. My commits were jumbled and incoherent. I wasn’t outlining my thoughts. I didn’t have a clear path. I kept hammering on my keyboard and slamming my head into that proverbial wall, but brute force was failing me. After hitting a teeth-gritting breaking point, the quote above came into my head. Here is my full commit message from when I hit that breaking point:

Nasty Commit to Save Work Attempting to add tests to verify that the link -> entity relationship is working correctly; Cleaning up some stringified keys and using NSStringFromSelector instead.

America is all about speed. Hot, nasty, badass speed. -Eleanor Roosevelt, 1936

That commit message makes absolutely no sense (and yes, I actually did include that quote in the message). I was frustrated. That commit touched fourteen files, contained two hundred and seventy-three additions, and disregarded fifty-nine deletions. It was a mess. Quite frankly, I’m ashamed of it.

I have been striving for small, granular commits. I want my commit messages to be concise. If I can fit an adequate description in the title portion of the commit log, that’s even better. This commit was cumbersome. It touched way to many files and made no sense. I can’t even begin to describe what I changed.

Today was much better. My commit history reads like a diary (albeit a confusing diary). I’m improving, but I’m not there yet. I’ve been debating on how I can go about making sense of what I do. Maybe I should keep a diary of what I’ve been working on. This could be beneficial as I encounter problems that seem familiar (Have I encountered these problems before? What did I do last time?) or even help shed light on what I should be doing or the path I should be taking. It would cause me to stop and think about what I’m doing or what I’m trying to accomplish instead of hammering as hard as I can on my keyboard.

Programming!


Defective Mood

As I age, I am perturbed that my mood is directly tied to what I feel that I am either accomplishing or not accomplishing at work or, rather, in software development. I have recently found that I can be quite foul if I encounter a problem in software that I am writing. I encounter many problems that do not affect me, but I have found that the ones that do affect me tend to have the same earmarks: an unfamiliarity with a framework or an API, a misunderstanding of how a framework or API is intended to function, or, my biggest fear, unexplained behavior of a framework or API. I was recently plagued many hours on an issue at work that I feared fell into the latter category.

I have worked with Core Data on many occasions now. We are using it in our project at work. However, I started noticing odd behavior in some of our tests. There were NSManagedObjects that were not updating as expected when importing example server responses. The tests were passing and unexpectedly not passing later. This was bothersome. I ended up stepping backward through our commit history until I narrowed it down to a particular commit (actually, a particular pull request being closed). My first inclination was to expect an issue with our .xcdatamodeld file (the backing of our Core Data model). All of the changes in this commit seemed innocuous enough. We were adding relationships and parameters to objects, but none of them should affect our import logic. After introducing these changes one by one into a detached HEAD state in our repo, I came to a startling conclusion: None of the data model changes actually broke our data import. This was terrifying. I was stumped. My mood was quite foul.

When you’re stymied by a problem, everything is stupid. Your computer is stupid. Your tools are stupid. The language is stupid. The framework causing you grief is stupid. Stackoverflow is stupid. Everything.

With the recommendation of a coworker, I took an early lunch. He rightly pointed out that I needed to step away from the problem. Once you’ve had your head down on a problem for an extended period of time with little progress, you become stuck. I was most definitely stuck. During our lunch break, we actually spit-balled ideas on what the issue might be. We came up with a few theories. I was reenergized. After being back in the office for a bit, my energy was zapped again. All of our theories were bunk.

I went back to the drawing board. Something finally caught my eye. It was a category for one of our NSManagedObjects that was overriding willChangeValueForKey:. I just happened to notice that this method was not calling super. Someone had forgotten to call super. I was vaguely aware that Core Data and MagicalRecord (a library to simplify the Core Data layer that we are using) use these methods for updating relationships. I am much more aware of that now. I added the super call. BOOM. I was back in business.

I believe the frustrating piece of this episode is the concern that something is now broken that had been working and there is no clear stressor at what triggered the issue. After making this fix and verifying the fix, I was elated. Not only had I fixed a particularly nasty defect, but I learned more about Core Data in the process.


My Environment Setup

I recently purchased a new 13" MacBook Air (which is a truly wonderful machine). Before I booted the machine for the first time, I started to contemplate what was needed for the machine to be setup for my development needs. I have, regrettably, avoided keeping track of what my environment looks like. I decided to change that. I have started tracking my environment setup on a static page on this site. It may not be the ideal setup for everyone, but I have found that it is the bare minimum of what I need (it is a work in progress and I plan to keep it updated as my methods and needs evolve).

If you have any questions about my setup, please feel free to ask.


Unintuitive Swift

In case you have been living under a rock, Apple announced a new language at this year’s WWDC: Swift. I have been anxious to work with the new language beyond reading the Apple supplied The Swift Programming Language and the new Playground Xcode feature (which is a new way to experiment with Swift without using it in a project). I have recently been working on a new personal project (I am not ready to talk in great detail at this time, but it is a Mac application) and since the project is still in it’s early stages, I decided to convert the project over and start using Swift in this project. Converting the project went smoothly and developers have the benefit of mixing and matching between Swift and Objective-C. I currently have a couple of classes written in Swift that play along nicely with the rest of my Objective-C code. I was skeptical when this capability was announced, but so far it has been working as Apple advertised.

This morning, I was writing some Swift code to validate the input in an NSTextField as it is typed by the user. I am attempting to validate the input as what I perceive to be a valid time format: "s", "ss", "m:ss", "mm:ss", "h:mm:ss", or "hh:mm:ss". In my initial implementation, I wanted to validate that only numbers and colons were input, to break apart the given string into components (with the token being the colon), and to assess each time component to ensure each component was an acceptable length. I am going to step through each one of these tasks and show what it would look like in Objective-C and what the equivalent looks like in Swift (or at least, to what it looks like in Swift to the best of my knowledge at this time; There may be more efficient ways of doing these tasks in Swift that I am not aware of yet). I’m also going to rant a bit about some things that I found confusing in my Swift implementation.

Validating a String’s CharacterSet

Given a string, I want to know whether or not the given string contains any forbidden characters. Given "07:07", the result would be false (does not contain forbidden characters); Given "07.07", the result would be true (does contain forbidden characters).

Objective-C

NSString *timeString = @"07:07";

NSCharacterSet *validTimeCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789:"];
NSCharacterSet *invalidTimeCharacterSet = [validTimeCharacterSet invertedSet];
NSRange rangeOfInvalidTimeCharacters = [timeString rangeOfCharacterFromSet:invalidTimeCharacterSet];
BOOL invalidTime = rangeOfInvalidTimeCharacters.location != NSNotFound;

Swift

So there are a few caveats with this solution in Swift. Swift has a Range class that does not directly map to the NSRange structure. I, for the life of me, could not figure out how Range actually works. Furthermore, Swift’s String class does not have a simple rangeOfCharacterFromSet: function (or it’s equivalent); Instead, it has a rangeOfCharacterFromSet(aSet: NSCharacterSet, options: NSStringCompareOptions, range: Range) function. I tried many things, but could not get Range to behave as I thought it would. I realize this has to do with how I think of NSRange and I am trying to just use NSRange in Swift, but I found it very confusing. After hunting through the developer forums, this is the solution I came up with:

let timeString = "07:07" as NSString

let validTimeCharacterSet = NSCharacterSet(charactersInString: "0123456789:")
let invalidTimeCharacterSet = validTimeCharacterSet.invertedSet
let rangeOfInvalidCharacters = timeString.rangeOfCharacterFromSet(invalidTimeCharacterSet)
let invalidTime = rangeOfInvalidCharacters.location != NSNotFound

or

let timeString = "07:07"

let validTimeCharacterSet = NSCharacterSet(charactersInString: "0123456789:")
let invalidTimeCharacterSet = validTimeCharacterSet.invertedSet
let rangeOfInvalidCharacters = timeString.bridgeToObjectiveC().rangeOfCharacterFromSet(invalidTimeCharacterSet)
let invalidTime = rangeOfInvalidCharacters.location != NSNotFound

Breaking a String into Components

Given a delimited string, I want an array of strings for each component. Given "mm:ss", the result would be ["mm", "ss"].

Objective-C

NSString *timeString = @"07:07";
NSArray *timeComponents = [timeString componentsSeparatedByString:@":"];

Swift

let timeString = "07:07"
let timeComponents = timeString.componentsSeparatedByString(":")

Iterating Over an Array Backwards

I will not bore you with the details on how to iterate over an array backwards in Objective-C. That really is not important in this observation. The real quirk is how you iterate over an array backwards in Swift. In Swift, you can iterate with a for-in loop:

for index in 0...3 {
  println(index)
}

The above code will loop four times (the ... in this case indicates inclusive, meaning <= 3; If you wanted to be exclusive, meaning < 3, use .. instead). I assumed that performing this loop in a reverse order would look like:

for index in 3...0 {
  println(index)
}

After watching the loop run for a few seconds, I realized how my assumption was false. My code was iterating many, many times. Have you seen the issue yet? Well, Swift is iterating from 3 to 0, incrementing. The loop starts at 3, then moves to 4, then to 5, 6, 7, and so on. Given enough time, index (which is an Int64 on my 64-bit Mac) will overflow into negative numbers, then slowly work it’s way to zero. I found this to be fascinating. I am not going to say this is a defect, but I will say that I believe this is misleading behavior, given prior experience with other languages. I would have expected the above code to start at 3 and work it’s way down to 0.

I could have used my time here to complain about this, but I will not. This has been talked about on the developer forums, so I will not add to it here. After some digging, I did find a way of accomplishing this task:

for index in reverse(0...3) {
  println(index)
}

Ah, of course: The intuitive reverse() function. How could I have missed that?

What I Learned

I have much to learn when it comes to Swift. It does not help that the language will be evolving while learning, but it makes sense to learn it early (in my opinion) so that I understand what my platform is moving toward. I am coming up on nearly five years of iOS experience and the code I am writing in Swift now makes me cringe. It makes me feel like I am in college again, writing terrible code. Have you ever looked back at code you have wrote while in college? Welcome to learning Swift.


Introducing CoreDataMate

A few years ago, I started development on a project that required long term persistence. Up until that point, most all of my persistence was handled on the server. This project required that I persist data locally on the user’s device, in conjunction with persisting data remotely on a server. As this was an iOS project and Apple is “all-in” with Core Data, I decided I had better get “all-in” with Core Data as well.

I read through every Core Data tutorial I could find on the internet. Regardless of how many times I tried, I just could not grasp what was happening in Core Data. After complaining about this to some of my coworkers, I had a few of them recommend MagicalRecord. I am not going to question the quality of this library; I have no doubt that it is well written and works as advertised. The issue is that I don’t understand what the library is doing behind the curtain. I use libraries all the time, but when I use them, I want to understand what they are doing (more or less) without blindly trusting them. For whatever reason, I simply cannot wrap my head around what MagicalRecord is doing. It seems as though you can arbitrarily create objects on any context and save them. This is one of the library’s goals. However, one thing I have come to understand is that you need to ensure that every thread has it’s very own context so that you don’t “cross the streams” so to speak. Try as I might, I simply could not ensure this using MagicalRecord. This is when I decided to go old school and purchase a book: Core Data (2nd Edition): Data Storage and Management for iOS, OS X, and iCloud.

Don’t cross the streams

After reading through Core Data (2nd Edition), I started writing what I called a “data manager”. The data manager is a simple class that acts as a gateway to your persistent store. The data manager houses a private context which is considered to be the master copy. You do not have direct access to this context from any public facing methods in the data manager. The context that you work with predominantly will be a child context of the private context. This child context is a main queue context that I have appropriately named mainContext. The main queue context will be the context that you predominantly work with. This is the context with which your UI will directly interact.

This is all great, except for the very real use case when you will need to write content to your persistent store. What then? Well, the data manager’s current pattern dictates that you create a new temporary context for your thread (this can even be the main thread if you like, the point is that you just want a temporary context with which to work) whose parent will be the data manager’s mainContext; you will then make any changes that are necessary on this temporary context. After you are finished, you’ll persist your temporary context which will write those changes upstream to the data manager’s mainContext. If that persist is successful, simply call:

[[CDMDataManager sharedManager] persist:YES];

which will write the mainContext’s changes upstream to the data manager’s private context (the BOOL value indicates that it should be a synchronous save; a NO here would result in an asynchronous save). At that point, your new content is in your persistent store and you have the added benefit of your UI already being updated with this content as your changes already exist on the mainContext.

This is a rudimentary example, but I wanted to show how easy Core Data can be to work with, with a bit of caution and understanding. Ready to check out the source code or give it a spin yourself? Head on over to CoreDataMate on Github to check out the source. If you’re impatient and want to play with the code (and you use Cocoapods) just add this to your Podfile: pod "CoreDataMate".


Wendy, Let me Explain Something to You

The Shining

Whenever you come in here and interrupt me, you’re breaking my concentration. You’re distracting me. And it will then take me time to get back to where I was. You understand?

My stepfather was an auto body man. He claims that he found his passion during his high school auto body class. After graduating high school, he spent most of his working life beating the dents out of cars. He spent most of his time working for car dealerships. Car dealerships would routinely purchase wrecked cars and hire auto body men to fix the vehicles so that they could in-turn sell the car for a profit. The dealerships would sometimes be able to make a profit of a few thousand per car.

The work was brutal. He worked year round in a shitty body shop with no air conditioning in the summer and kerosene heaters in the winter. Summer time in Kentucky finds temperatures routinely in the 90s and frequently breaking 100°F. The humidity in Kentucky during the summer is so high that a quick walk from the front door of your house to your car in the driveway would leave a thick layer of perspiration on your forehead at 7AM. The winter in Kentucky, while considered mild compared to the northern United States, can still be frigid.

He worked like a dog: forty to forty-five hard hours a week. He was paid hourly. As far as I can recall, he had no benefits. Sick? You’re missing out on pay. Vacation? You’re missing out on pay. He brought home $225 per week. To help make ends meet, he also freelanced on nights and weekends. There was a small detached garage at our house. He would work from 6PM (when he usually arrived home from work) until 9PM (an early night) or until 12AM (a late night). He would also catch up on his freelance work on Saturdays and rarely on Sundays. He tried to save Sundays for his day of rest, which usually involved watching a Winston Cup race.

He was also fortunate enough to be artistically talented. He could charge big money for a custom paint job, sometimes a couple of thousand, depending on the gig. Luckily, there was no shortage of young men who wanted a custom painted car to show off to their friends. Unfortunately, custom paint jobs eat up time. There are hours devoted to drawing out the initial design. Then there is the taping, which can take an entire night. Once the car is taped, the design needs to be drawn out, followed by intricate X-Acto blade work to cut out the pattern. Now you’re ready to paint. There are always many coats involved. And those take time to dry. Many designs require layers of work. It is not uncommon to repeat this process five to ten times for simple designs. If there are any imperfections or bugs (Kentucky summers are a hotbed for mosquitoes and other flying nuisances) the affected area would have to be wet sanded (sanding the painted surface while squeezing a wet sponge over the area), which would smooth out the surface. After all of this, the body still has to be clear coated to give it that protective layer and to make it shine. If done properly, the car will permanently look wet (which was always desired).

My stepfather claims that this was a labor of love. He felt that he was put on this earth to repair auto bodies and to paint them. I feel he was a bit disingenuous. I think his passion was actually art and that his canvas happened to be cars. I believe he repaired auto bodies as a means to an end, to afford him the chance to run his side business so that he could land the custom paint jobs.


I, on the other hand, feel that I was put on this earth to write software. It brings me joy. I have a job writing software. I should be happy about this. And, usually, I am. The issue is that I would like to do more. I would like to learn more. I would like to work on other projects, my own projects. But what do you do when, after working forty hours a week, you are so mentally drained that you can’t force yourself to work on your own projects?

In a manner of speaking, my stepfather had side projects. His side projects kept food on the table and clothes on our back. His side projects were a necessity. I have the luxury of making a very comfortable living in my day job. My side projects are strictly academic or for self advancement. It’s important to note that my side projects are not intended to draw income (although if they did, I wouldn’t be upset). What I have discovered is that passion alone has failed me in my drive to pursue side projects. When I walk into my house I am mentally drained. I want to spend time with my wife. I want to watch television (lately, I’ve been hammering through episodes of Top Gear, British version of course). I want to recuperate. “What about the weekend?”, you might ask. No dice. I’m still tired. I still want to relax and recuperate. But mostly, I want to enjoy my home. I want to take in what Nashville has to offer.

So where does this leave me? Usually agitated. I become irritable about not working on my side projects. If I do find the time and the drive to actually sit in front of my computer, I have rarely left my project in a place where I can quickly pick it back up. Every time I put down one of my projects, I have failed future Todd. I never leave notes for myself so that I know what was happening or where I should go next. If any distractions arise (even something as innocent as my wife wanting to spend time with me) I meet them with an unusually harsh response. I outwardly blame others for my inability to manage my own side projects. “I wish I had more time,“is a common refrain. But there are plenty of other developers who have side projects and they have the same amount of time as I do during a day. So what makes them different? My guess: Planning and priorities.

I would love to give up on side projects, but in my own mind I would feel like a failure for not having them. It seems as though every developer today has their day job and other projects at night onto which they contribute. If I don’t have a side project, am I less of a developer? Probably not. But it feels that way.


You Wanna Hurt Me?

A scene from Planes, Trains and Automobiles where John Candy confronts Steve Martin.

Go right ahead if it makes you feel any better. I’m an easy target.

In the movie Planes, Trains and Automobiles (Oxford comma be damned), Neal blames his ruined trip home on Del. Is Del trying to ruin Neal’s trip? No. Del is just being himself. He’s loud. He’s boisterous. He’s doing what he believes is right. He’s not out to ruin Neal. But Neal, being the cynic that he is, feels that Del is just a buffoon with intentions of malice. I’ve run into a few Dels during projects. And I’ve unfortunately became Neal in many of these situations. It’s not something that I’m proud of, but something that I’m working toward improving.

I recently started working on a project at work that we took in house. The project had been outsourced to a developer in South America, but was brought to use to finish that last 5%. I loathe the last 5%. The reason? It’s never just 5%. Inevitably there are foundation problems with the code. There are quirky little bugs. The application is slow. And the code? Horrific. It’s like you’re renovating a house and you hire me to paint it. I come in and immediately fall through the floor. After I dig myself out of the hole, I see water running down the wall and electrical wires dangling out of the ceiling.

I have a tendency to become bitter at this stage. A little at the project, but most of my bitterness comes at the expense of the developer who wrote the code. It’s easy to blame all of your problems on someone else. I wanted to criticize this developer. I wanted to shame this developer. I wanted to humiliate this developer. Why would I do this? Because I’m God’s gift to programming, of course. I would never make these juvenile mistakes. My code would be pristine. My code would have been well thought out. The application would have been flawless. I even feel that the developer may have even maliciously written terrible code. Maybe the developer was intentionally attempting to sabotage the project. Sometimes I have to catch myself and realize that he or she may just be beginning their journey of being a software developer and that he or she may need a little help along the way.

The issue with my hubris is that I’m forgetting a few truths. I used to be this bad (maybe even worse). I am embarrassed by the code that I wrote while I was in college. I sincerely hope no one ever sees code from the first project that I worked on. In hindsight, it was horrible. How did I overcome this? I was fortunate enough to have developers around me who pushed me and challenged me to become better. They gave me constructive criticism. It was face-to-face. There were no attempts at public shaming. I was lucky to work with developers who genuinely wanted to do good things and help others do good things. I believe this has been lost, somewhat, in the past couple of years at our company and by most developers. It’s easy to be snarky toward others with your first projects safely deleted or hidden on a thumb drive that happens to be buried in a drawer at your desk.

When I become irritated at another developer, I explain to them why I’m irritated. I open a code review on them and try to help them improve at their craft. Am I a saint? No. I sometimes exclaim hurtful comments out loud at my keyboard. I have judged the original developer of my current projects unfairly. I have refrained from attempting to belittle him or her on Twitter. After taking a little time to reflect on the situation, I simply regret that I will not have the opportunity to give them feedback. To help him or her improve at something that they love or at least care enough about to do for money. I realize my code is far from perfect, but I figure that if I can help others improve then others can help me improve.

I occasionally have to fight my urge to become Neal. After Neal has blown up at Del (one of the many times), Del goes on a heartfelt rant with this line: “I could be a cold-hearted cynic like you, but I don’t like to hurt people’s feelings.” Perhaps this world would be a bit better for developers if there were more developers out there who cared less about “burning” a fellow developer and more about helping a fellow developer improve. I’m slowly starting to learn this and make this change within myself.


I'm Kind of a Big Deal

A screenshot from Anchorman: The Legend of Ron Burgundy during the opening party at Ron’s apartment

I’m very important. I have many leather-bound books and my apartment smells of rich mahogany.

Saturday was kind of a special day (as far as software development goes). I opened a pull request for Shenzhen. Shenzhen is a gem for building .ipa files from iOS projects (it even has support for distributing files to TestFlight, HockeyApp, FTP, and S3). While testing the gem, I noticed a few problems with building schemes in workspaces. I cloned the project to my local machine, played around with the source, until I fixed the issue. It was a small fix, but I had a few concerns.

Lizard Brain

I’m a very novice Ruby developer and I feared I was making an ass out of myself. I thought that my change might be considered hackie. Perhaps I was not conforming to Ruby standards. I’ve written Ruby code in the past, but I rarely let it see the light of day. There are always other, more preferred ways of an implementation (Ruby has methods for everything) and I’m always concerned that I’m doing something wrong or embarrassingly wrong.

I’m also pretty green when it comes to Github. Up until this point, I’ve only had a few pull requests accepted from Martin M on his Maven CXX Plugin (mainly changes to keep the plugin updated to building iOS projects). I’ve worked with Martin. He’s incredibly gifted and he was incredibly kind to accept my pull requests (especially since I know I did them poorly; Sorry Martin).

On top of that, the author of the project is mattt. Yes, that Mattt. Mattt with 3 T’s Mattt. NSHipster Mattt. (Side Note: I’m loving the NSHipster: Obscure Topics in Cocoa & Objective-C book.) With such an extremely knowledgable and talented developer, it felt daunting to be offering a change to his codebase.

Saturday morning, I decided it was time to stop being scared. I needed to learn how to do this properly. The best way to learn: By doing.

I Have the Power!!!

First, I found this awesome walkthrough on forking, working, and opening a pull request on Github: How to GitHub: Fork, Branch, Track, Squash and Pull Request. After about an hour of work, I had successfully opened a pull request. I was thrilled. However, my excitement was tempered a bit. I have heard many stories of pull request purgatory where the author never accepts pull requests and open ones just sit there for all eternity. So I was excited, but I realized that just opening a pull request was half the battle. I had done all I could do: Make the changes, document everything thoroughly in the commit log, open the pull request, and re-emphasize the changes I had made (and why) in the pull request description. Luckily, later that day, I received a Github notification: mattt had accepted my pull request. I was ecstatic. As I read through the full message, I noticed that he cherry picked my changes to avoid the addition to the .gitignore of ignoring BBEdit files (not a big deal, I probably should not have checked that change in anyway; Force of habit really).

I Learned Something Today

I think the moral of my story is this: Just do it (Nike™). In all seriousness though, my biggest enemy is always that nagging voice in my head, telling me that I shouldn’t bother. Or that I’ll fail. Or that people will regard my contribution as meaningless to the project. Or that I’m doing it wrong. I’m constantly fighting this. But as I do more, I’m slowly quieting that voice. I’m not sure if I’ll contribute more to open source projects on Github, but now that I have this under my belt, I’m going to feel more confident the next time the urge strikes me.