October 2011 saw the passing of giants:
By his vested Interweb powers, Tim O’Reilly has declared that October 30 be Dennis Ritchie Day. In his honor, I wanted to write something that’s been bothering me about the way people are learning Objective-C:
As a programmer, your most fundamental tools are the programming languages you use. If you don’t know the tool, you simply won’t be able to express things with both simplicity and power. And while I’m glad for the sudden interest in Objective-C, I’m troubled that so many people treat it like some kind of bastardized Java. They jump straight into messaging syntax and Foundation classes, while bypassing the powerhouse that’s available to them.
That powerhouse is the C language.
Unlike other offshoots of C, Objective-C is C. In fact, it’s a strict superset of C. This means that anything you can do in C, you can also do in Objective-C. Or to flip that around, if there are pieces of C you’re not familiar with, you’re missing out on a tool that powers… well, nearly everything.
Let’s look at a concrete example: Say you have a UITableViewController. Table cells are often very similar. Let’s say the only difference between cells is
Amount of code executed to set up this data structure: Zero.
“That’s an opportunity to reduce all this code into something data-driven,” you say. Well done! …Oh, but the approach many might choose is to put this information into NSDictionaries, in an NSArray. And you have to encode the selectors as NSValues. And you have to do all this at some known time like -viewDidLoad.
Whoa there cowboy, let me save you some trouble. C to the rescue! First, define a struct to hold information about each cell:
Now define a static array of that type.
Amount of code executed to set up this data structure: Zero. Zip. Nada.
Now think about how these different data structures will be read in -tableView:didSelectRowAtIndexPath:. Assume we’ve already set
NSUInteger row = [indexPath row];
cellInfo[row].selector. That’s just a memory address calculation.
If you’re an old-timer, dust off the old K&R, in honor of Dennis Ritchie. Amazing, for such a short book.
But if you program Objective-C and don’t own a copy of The C Programming Language, do yourself a favor: >Buy one today. (Remember to expense it.) You’ll step into a time machine and go back to 1978. It may not be fresh, but it sure is relevant. Go through the exercises. Remember:
Jon is a coach and consultant on iOS Clean Code (Test Driven Development, unit testing, refactoring, design). He’s been practicing TDD since 2001. You can learn more about his background, or see what services he can bring to your organization.