PragPub 2010-01: Issue #7

Table of Contents

Features

- The Daily Shoot
by James Duncan Davidson
Duncan talks about The Daily Shoot, his and Mike Clark’s clever idea that is motivating hundreds of photographers to work at their craft every day.

- Against SEMAT
by Jorge Aranda
You say you want a revolution? We’d all love to see the plan.

- Touching the Core
by Marcus Zarra
Marcus walks you through using the NSFetchedResultsController, a powerful new class in the Core Data API that can make your iPhone, iPod Touch, and Mac apps significantly richer.

- Much Ado About Nothing
by Paolo Perrotta
Paolo plumbs the depths of nothingness to show the power of metaprogramming in Ruby.

Departments

- Up Front
by Michael Swaine
Welcome to the first issue of PragPub for 2010.

- Choice Bits
Tweets, posts, and chatter on programming and life.

- Get a Life
by Daniel Steinberg
A different sort of log for the new year.

- The Working Geek
by Andy Lester
Andy suggests some ways to make 2010 better in his monthly look at the working life of a techie.

- Swaine’s World
by Michael Swaine
How I took off the cowboy hat and stepped away from the keyboard.

- The Quiz
by Michael Swaine
A monthly diversion at least peripherally related to programming.

- Calendar
by Jackie Carter
Author sightings, partner events, and other notable happenings.

- Shady Illuminations
by John Shade
The man with the camera really is trying to capture your soul.

Except where otherwise indicated, entire contents copyright © 2010 The Pragmatic Programmers.

Feel free to distribute this magazine (in whole, and for free) to anyone you want. However, you may not sell this magazine or its content, nor extract and use more than a paragraph of content in some other publication without our permission.

Published monthly in PDF, mobi, and epub formats by The Pragmatic Programmers, LLC, Dallas, TX, and Raleigh, NC. E-Mail support@pragprog.com, phone +1-800-699-7764. The editor is Michael Swaine (mailto:michael@pragprog.com). Visit us at http://pragprog.com

ISSN: 1948-3562

Up Front

’Tis a Gift to Be Simple
by Michael Swaine
Welcome to the first issue of PragPub for 2010.

“’Tis a gift to be simple,” the old Shaker song says, and the start of a new year always seems like a good time to question our assumptions, clean out the mental closets, and tune our habits to better harmonize with our goals.

In “The Working Geek,” Andy Lester lays out some simple resolutions for software developers for Twenty Ten. Daniel invites us to revisit a simpler time and a simpler technology as he teaches us how to build a slide rule in “Get a Life.” And I celebrate the virtues of an even simpler technology, handwriting.

Other writers in this issue embrace simplicity, too. Great ideas are always based on simple insights, and James Duncan Davidson and Mike Clark had one of those recently, which Duncan talks about in “The Daily Shoot.”

As an API gets more powerful it ought to make a developer’s life simpler, though it doesn’t always work out that way. Marcus Zarra shows how that can be the case for iPhone and iPod Touch developers.

Jorge Aranda questions whether a recent call for action in software engineering is really necessary. Metaprogramming Ruby author Paolo Perrotta keeps it simple by talking about literally nothing. And John Shade goes to the movies.

You’ll also find, as usual, a quiz, an events calendar, and other regular features in this issue, and in the back you’ll find a list of our back issues (six of them already!).

Here’s wishing you a productive, happy, and simply wonderful Twenty Ten.

Choice Bits

Overheard on the Intertubes

Wading into the chatterstream in hip boots, we wield the Axiom of Choice with gleeful abandon.

What’s Hot

Top-Ten lists are passé—ours goes to 11. These are the top titles that folks are interested in currently, along with their rank from last month. This is based solely on direct sales from our online store.

1^

NEW

ExpressionEngine 2.0

2^

9

Web Design for Developers

3v

1

Agile Web Development with Rails, Third Edition

4v

3

Pomodoro Technique Illustrated

5v

2

The RSpec Book

6^

8

Language Implementation Patterns

7^

NEW

Security on Rails

8v

6

Programming Ruby 1.9

9v

4

iPhone SDK Development

10^

NEW

Building a Dynamic Website with ExpressionEngine

11^

NEW

Programming Clojure

The January Guessing Game, iSlate Version

Santa Claus arrived early for Apple Inc. shareholders: The stock on Thursday surged $6.94, or 3.4 percent, to close at a record high of $209.04.... The buzz continues to build about the company’s widely anticipated (albeit unconfirmed) tablet computer. — Tom Petruno, Los Angeles Times

Nothing is official, but the evidence is pretty conclusive that Apple owns [domain names for] iSlate. It does not mean that Apple will use this name for the Apple Tablet, but honestly it would not fit to anything else. — I4U

Apparently, [Apple] registered the domain through brand protection firm Mark Monitor to conceal the fact that the domain name is theirs, as usual, but was briefly listed as the owner at some point in the past nonetheless. — TechCrunch

Personally, I’m voting for "Humongous iPod" as the name, or better yet, “GinormousPod.” — Alexander Wolfe, InformationWeek

The size of this “very soon” tablet will be 7-inch (100% sure). — Pinyotutorial

The screen size is said to be 10-inches for the rumored device. — Arnold Kim, MacRumors

Innolux, the panel-making subsidiary of the Foxconn Group, will be the initial supplier of touch panels for Apple's tablet PC, with Wintek standing a change of becoming a second supplier at a later time — Susie Pan, Digitimes

The company has rented a stage at the Yerba Buena Center for the Arts in San Francisco for several days in late January.... — David Gelles, Financial Times

Apple (AAPL) appears to be gearing up to build as many as 1 million tablet computers per month. — Phillip Elmer-DeWitt, CNN

One possibility—increasingly likely, we think—is that this is the first of several tablets Apple will announce over the coming months. — Dan Frommer, Silicon Alley Insider

It is designed to expand the iPhone and iPod touch media concept to its next potential level: as a slate-like replacement for books and magazines, plus all of the media, gaming, app, and web functionality of the iPhone and iPod touch. — Jeremy Horowitz, iLounge

A person close to a VP in textbook publishing mentioned to me in July that McGraw Hill and Oberlin Press are working with Apple to move textbooks to iTunes. — Gizmodo

I’m hoping we can get the newsroom more actively involved in the challenge of delivering our best journalism in the form of Times Reader, iPhone apps, WAP, or the impending Apple slate.... — Bill Keller, New York Times

Clearly, Apple sees a gaping hole—the publishing industry’s lack of vision for a working digital model—and a touchscreen tablet, combined with the App Store and this new in-app sales model, would seek to fill it. — Brian X. Chen, Wired

Apple’s forthcoming tablet could employ a dynamic surface that gives users tactile feedback when typing in order to identify individual keys, according to a new patent application revealed this week. — Neil Hughes, AppleInsider

By this time next year, we may have a whole new genre of computing. It’s an undiscovered country. — MG Siegler, TechCrunch

Reflections on Publishing in 2009

Newspapers have become deadweight commodities linked to other media commodities in chains that are coupled or uncoupled by accountants and lawyers and executive vice presidents and boards of directors in offices thousands of miles from where the man bit the dog and drew ink. — Richard Rodriguez, Harper’s

When I talk to groups of journalists these days about the state of our business, I feel like a motivational speaker in a hospice. — Bill Keller, Executive Editor of the New York Times

We’re going to have no paper, no printing plants, no unions. It’s going to be great. — Rupert Murdoch, chairman of News Corp.

There’s no doubt in my mind that when it finally realigns, we’re actually gonna see a kind of golden age of journalism. — Tina Brown, The Daily Beast

The same companies that spent decades telling lawmakers that they were explicitly not the guardians of the morality of the young—that they couldn’t be held accountable for sex, drugs and rock’n’roll, for gangsta rap, for drug-fuelled dance-parties—did a complete reversal and began to beat their chests about the corrupting influence of downloading on the poor kiddies. — Cory Doctorow

Every time DRM prevents legitimate playback, a pirate gets his wings. — Nathan Bowers

Reflections on Software Development in 2009

TDD is not my religion, it is one of my disciplines. It’s like dual entry bookkeeping for accountants, or sterile procedure for surgeons. — Bob Martin

I can honestly say if someone had shown me the Programming Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy. — James Strachan

I do believe I have post-traumatic Java syndrome. — Renae Blair

This is the Python 3K blindness: it’s harder for old-timers to appreciate how broken things are because they’ve got a good feel for where the dangerous swamps are, and ready-made duckboards for the areas they can’t avoid. And aren’t you supposed to get a bit wet anyway? — elliott hughes

From what I’ve seen of it, PHP isn’t so much a language as a random collection of arbitrary stuff, a virtual explosion at the keyword and function factory. — Jeff Atwood

There should be a half-life on software so old software just melts away over 10 or 15 years. — Alan Kay

Not all code needs to be a factory, some of it can just be origami. — _why

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding

On the internet, no-one knows you’re 14 year old or a raccoon. Until they use your software. — elliott hughes

The best way to market yourself is to be remarkable. — Chad Fowler

Surely There’s an App for That

Dog unwrapped and carefully ate Grandma’s Christmas present. Cat drank all the Christmas tree water. — Pragmaticandy

Sheldon: Everyone at the university knows I eat breakfast at 8:00 and move my bowels at 8:20.

Leonard: Yes, how did we live before Twitter? — The Big Bang Theory

You know, there are certain days that remind me of why I ran for this office. And then there are moments like this—where I pardon a turkey and send it to Disneyland. — President Barack Obama

I now have the liver of a mid-twenties person. — Steve Jobs

Get a Life

Building a Slide Rule
by Daniel Steinberg
A different sort of log for the new year.

I’ve been rereading Nero Wolf lately. The writing is crisp, the language imaginative, and the setting is refreshing. The fictional detective mostly stays in his home and uses his wits to solve crimes. Archie Goodwin, his assistant, does most of the legwork.

And it is legwork, not webwork. The author, Rex Stout, died in 1978, so his books are definitely dated. Neither Wolfe nor his rivals in the police department have the technology or the resources you’ll find on your modern murder mystery shows like CSI and Law & Order. Wolf uses words like “flummery” and “pfui” and doesn’t have access to the internet or to DNA testing. When Archie is out running down clues he doesn’t have a cell phone where people can reach him. He has to go find a pay phone or borrow one.

But that’s part of the charm of the stories. Sure, we benefit from our modern conveniences, but it’s nice to step back and enjoy a story set in a simpler time.

It reminds me of math before calculators. I can do a whole lot more in math now than I could do thirty-some years ago, but I still fondly remember using log tables and slide rules to perform quick calculations. In this month’s column, let’s go back to that simpler time.

Decoder Ring

We’re not going to go deep into logarithms. For this article we’ll use common logs (logs base 10) but you don’t really need to know what that means. We need a log table—here’s one I created with the spreadsheet program Numbers.

If you want the log for 3.14, for example, you read down the left column until you find 3.1 and then you read across the top until you find .04. The cell that is in the same row as 3.1 and the same column as .04 is .4969. To four digits, the log of 3.14 is .4969.

So here’s fun fact number one: log a + log b = log ab. In words, the log of a product is the sum of the logs. I kind of think of the log table as a decoder ring—here’s how you use it to multiply 2 and 3 using logs.

1. Encode: In the table you can see that log 2 = .3010 and log 3 = .4771.

2. Calculate: log 2 + log 3 = .3010 + .4771 = .7781

3. Decode: Look through the entries in the log table until you find something close to .7781. The closest I find is .7782 which is the log of 6.00.

After much work you’ve discovered that 2 * 3 = 6.

You can deduce from our first fun fact that log a/b = log a - log b. In words, the log of a quotient is the difference of the logs.

Place Value

Before we move on, take another look at the log table. The encoded values are between 0 and 1. So the numbers you can take the log of are between 1 and 10. And that’s all you need, but you’ve got to take care of place value for yourself.

For example, suppose you want to leave a 15% tip on a meal that costs $4.75. You need to multiply .15 by 4.75. You can’t look up .15 in the table but you can look up 1.5. So to calculate the tip like this. log 1.5 + log 4.75 = .1761 + .6767 = .8528. In the table .8528 is smack dab in the middle of 7.12 and 7.13. Remember, it’s up to you to keep track of the place value. 15% of $4.75 can’t be $7.12 it has to be closer to 71 cents.

Constructing a Slide Rule

Logs let you replace multiplication and division with addition and subtraction, plus some encoding and decoding. A slide rule lets you forget about the encoding and decoding steps.

To make your own slide rule, you’ll need an 8 1/2 x 11 sheet of paper, a ruler, and a pencil. Turn the paper on its side and draw a horizontal line that is exactly 10 inches long. Draw a vertical line at each end and label it 1, top and bottom, left and right, like this.

Measure 3.01 inches from the left mark and make another vertical mark and label it above and below the line as 2. This comes from our table since log 2 = .3010. Similarly, make another mark that is 4.77 inches from the left and label it 3. We’ll fill in the rest of the numbers except 7 using the rules of logarithms. For 7 make a mark that is 8.45 inches from the left.

For the final step, carefully cut along the horizontal line. You now have a slide rule.

Multiplying on your slide rule

Take the top half of the slide rule and slide it to the right so that the left 1 sits on top of the 2.

Look under the 3. Mark it with a 6. Can you see that it is what you get when you add the distance from 1 to 2 to the distance from 1 to 3? Without any tables, you can read off that log 6 = log 2 + log 3. While you’re at it add a mark for 4 under the 2.

I’ve lined the two halves back up and made the marks for 4 and 6 on the upper scale as well. You should be able to figure out where the marks for 8 and 9 go. 8 is 2 * 4 and 9 is 3 * 3.

Running out of room

You should have figured out where 9 is by moving the top left 1 over the 3. The 9 should go directly under the mark for the 3. You can also see that the 6 sits directly under the 2, as 2 * 3 = 3 * 2.

How would we multiply 3 * 4?

If our past pattern holds we should look underneath the 4 on the top scale and that’s where the 12 should go. Unfortunately, this is past the end of the bottom half of the slide rule. So here’s another fun fact: when you run out of room using the 1 on one end of the scale, just use the 1 at the other end of the scale.

In this case, line up the 1 that is at the right end of the top scale with the 3 on the bottom scale. Now when you look for the 12 below the 4 you’ll find it between the 1 and the 2 on the bottom scale. This is correct once you realize that you’re actually getting 1.2 and it’s up to you to remember that it should be 12, not 1.2.

Dividing

We can’t use multiplication to place the 5. We need to use the fact that 10/2 = 5. So we subtract log 2 from log 10 to locate the 5. For log 10 we use the 1’s on either end of scale. I’ve set it up like this:

I lined the 2 in the top scale up with the 1 on the right side of the lower scale. So the 5 should go under the 1 on the left side of the top scale. This arrangement subtracts the log 2 from log 10.

And that’s it. You’ve created a nice slide rule and you can keep adding to it to fill in more values that you need. I’m not saying you should discard your calculator in favor of log tables and slide rules. That’s flummery. I am saying that it’s fun now and then to remember that we can. And I also think it’s a great way to reconnect to some of the underlying math that we don’t think about much anymore.

Share your slide rule experiences with Daniel and other readers in the magazine forum. -Mike

Daniel is the editor for the new series of Mac Developer titles for the Pragmatic Programmers. He writes feature articles for Apple’s ADC web site and is a regular contributor to Mac Devcenter. He has presented at Apple’s Worldwide Developer Conference, MacWorld, MacHack, and other Mac developer conferences. Daniel has produced podcasts for Apple featuring the work of developers and scientists working on the platform. He has coauthored books on Apple’s Bonjour technology as well as on Java Programming and using Extreme Programming in Software Engineering classes.

The Working Geek

New Year’s Resolutions
by Andy Lester
Don’t be an Eeyore. Don’t be a Dwight. Andy offers these and other tips to make 2010 better in his monthly look at the working life of a techie.

New Year’s resolutions are stupid. What was originally intended as a way to start new habits or set new goals has turned into a game. The idea of waiting until January 1st to change your behaviors is silly when you decide in mid-December you’re going to do exactly the opposite until the magic day. When we depart briefly from our new path on January 14th, we tell ourselves “Well, maybe I’ll do better next year,” and give up trying for another 352 days.

And yet any day is a good day to change bad habits or improve your work life. And the start of 2010 is as good a time as any. So here are some suggestions for the working geek. If you want to call them resolutions, that’s up to you.

Don’t Be an Eeyore

Winnie-the-Pooh’s donkey friend Eeyore always expected the worst to happen. What was charming and amusing in A. A. Milne’s books is annoying in today’s workplace. Eeyores always look bad.

Say you have a staff meeting where the boss asks everyone to stay an extra hour or two each night for the next two weeks to get some projects done before a big trade show. Nobody’s happy about it, but it’s the department Eeyore who says “Yeah, that’ll probably become standard even after the show.”

Maybe there’s an announcement that Christmas bonuses have been cut this year because of bad sales and the bad economy. It’s the Eeyore who mutters “Yeah, they’ll stay that way next year, too.”

It’s bad enough to think those things, because you’re not well-served by having a negative attitude in life. An Eeyore crosses over into career-damaging behavior by voicing these thoughts. Your co-workers don’t want to hear them, and your boss will peg you as having a bad attitude—and rightfully so.

Next time you feel the need to grumble about something at work, especially if it involves predicting the future, stop and shut up.

Improve All Your Written Communication

We live in email. We live on the Internet. The written word is how we’re judged. It only makes sense to expend some effort to make those written words, and the way in which they’re presented, as professional as possible.

Some people don’t take care with their online communication, justifying it with “Eh, it’s only email,” as if email is less important than other forms of communication. Whether or not you, as the sender, think that your words require care, that does not affect whether the recipient will share that view, nor does it affect how many people will see your mail.

Make spelling and capitalization a priority, especially with names of people. Use proper punctuation. Write complete sentences. Treat your email as if the entire world might see it, because that is a fact: anybody in the world might see it.

Revisit Your Résumé

A great place to start training your newly nitpicky eye is your résumé. You may never write anything that gets as much scrutiny, or upon which so much importance hangs. Check the spelling and capitalization of everything.

- Perl, not PERL

- AS/400, not AS 400 or AS-400

- Photoshop, not PhotoShop

- ColdFusion, not Cold Fusion

- Red Hat, not RedHat or Redhat

- PostgreSQL and MySQL, not Postgresql and Mysql

You may not think it matters much, but to aficionados it very well may. It also makes the reader question how well you know a technology if you haven’t yet absorbed its correct spelling. Visit the website of the technology in question to see how the people behind it spell it, and go with what they have.

While you’re scrutinizing your résumé, optimize it. Question the value of each word. Just as you have no extra code in your programs, have no extra words in your résumé. If a sentence is no better with a word, remove it. For example, instead of “Maintained build scripts written in Ruby,” drop “written” to leave “Maintained build scripts in Ruby.” Better still, “Maintained Ruby build scripts.”

Stop Being So Smart

We techies are an intelligent lot, and proud of it. Thing is, that pride often comes across as arrogant to those not steeped in geek culture.

If you’re familiar with Dwight Schrute on “The Office,” he’s a perfect example of the kind of geek who gives the rest of us a bad name. (And if you sniffed “The British one is better,” I’m especially talking to you.) No matter the topic, Dwight can best his co-workers in their knowledge of a given topic. He stalks conversations waiting for a time he can pummel his colleagues with the strength of his brain.

When you’re talking with your colleagues, both techie and not, consider how much mental muscle you really need to put into a conversation. I’m not suggesting playing dumb, but don’t be a know-it-all. When co-workers talk about a new movie, think about whether you need to launch into a detailed history of the book on which it’s based. Stand back from the conversation and ask yourself if you’re trying to add to the conversation or dominate it.

Actively Avoid Drama

There’s an old saying about how when you sling mud at someone else, you always get it on yourself. When it comes to interpersonal drama at work, it’s easy to get dirty from the mud-slinging, even if you’re not an active participant. Don’t fall into the trap of getting involved, even passively, in battles with or about co-workers. At best it’s a waste of time, and at worst you risk damage to your career.

Drama is often personal, with certain people or groups disliking people or groups. Do the programmers think the testing department is a bunch of no-talent whiners? Maybe it’s that Kim and Darryl used to be a couple but now they just glare at each other when they pass in the hall.

Sometimes the drama will be about the company itself. Which department’s manager is incompetent? Is there a revolt in accounting over HR’s new vacation rules? It’s all just noise, and none of it is helpful. Get involved with the griping and gossip and you could get pegged as a griper, too.

Starting today, decide that if someone comes to you with gossip or a gripe about someone else, or the company itself, you’ll leave the comment alone, without taking the bait and joining in. When someone at work starts badmouthing another department, say “That sounds frustrating” and change the subject. If it’s personal, a simple “I’ve never had that problem with her” should do the trick.

Monitor Yourself Online

Next time you apply for a job, the hiring manager is going to Google your name and see what she finds. Do you know what people say about you? About things you’ve written? You should.

Google Alerts is a fantastic little tool that I don’t hear people talk about enough. Google Alerts lets you enter a Google search once, and Google will update you whenever the Googlebot finds new matches for your search, often within only an hour or two of the page’s publication.

The most obvious Alert search is your name, as a phrase in double quotes, but that’s just the start. Here are some more ideas:

- Your name ("Andy Lester")

- Your nick ("petdance")

- Your email address ("andy@theworkinggeek.com")

- Your company’s name

- Résumés related to your job market in your area of expertise (I have an alert for "résumé Perl Chicago" (but without the quotes))

- Titles from blog postings you’ve made

- Links to specific blog postings you’ve made using the link: syntax

Keep an eye on the results. It’s not vanity, it’s understanding your personal brand.

What Are You Changing?

Do you keep New Year’s resolutions? Are there bad habits you’re looking to break? I’d love to hear about them. Let me know at andy@theworkinggeek.com, or discuss them with me and other readers in the magazine forum, and I may include them in a future column.

Andy Lester has developed software for more than twenty years in the business world and on the Web in the open source community. Years of sifting through résumés, interviewing unprepared candidates, and even some unwise career choices of his own spurred him to write his nontraditional book on the new guidelines for tech job hunting. Andy is an active member of the open source community, and lives in the Chicago area.

Swaine’s World

Adventures of a Clint Eastwood Coder
by Michael Swaine
How I took off the cowboy hat and stepped away from the keyboard.

Before I ever studied programming, I was making a living as a programmer for hire.

I thought I was pretty good. I was a Clint Eastwood coder. I’d ride in, solve the client’s problem, collect my fistful of dollars, and ride out, never looking back. Maintenance was for settlers. I worked alone and I rarely commented. Clint Eastwood starred in spaghetti westerns; I wrote spaghetti code.

Then I started taking classes and learned that I didn’t know anything about writing code.

From Dan Friedman in Indiana University’s Comp Sci Master’s program, I learned Lisp and two principles.

First principle: Any function can—and should—be defined in five lines or less. Three lines if possible, often four, five only in special cases.

(defun factorial (n)

(if (<= n 1)

1

(* n (factorial (- n 1))) ))

Second principle: Solve the problem with 3-5 lines of code that would execute if certain help functions existed. Write those help functions using other help functions whose existence then becomes desirable. Recurse.

(defun solve (world-peace)

(if (solved world-peace)

(print-solution-to world-peace)

(solve (simplify world-peace)) ))

I doubt that either of these is exactly what Dan was trying to teach us. The second principle looks like my misinterpretation of Wirth: “The creative activity of programming... is here considered as a sequence of design decisions concerning the decomposition of tasks into subtasks and of data into data structures.... In each step, one or several instructions of the given program are decomposed into more detailed instructions. This successive decomposition or refinement of specifications terminates when all instructions are expressed in terms of an underlying computer or programming language....” [“Program Development by Stepwise Refinement,” Niklaus Wirth, Communications of the ACM, April, 1971.]

Anyway, I had principles. I had structure. I would never again write spaghetti code, because now I really knew how to write code.

Taking Off the Cowboy Hat

Back then, when I was a computer science student, none of us had computers. I realize that this is hard for some of you reading this to wrap your minds around, but just tell yourself, this was the Old West. It was actually Bloomington, Indiana, but back then we were all in virtual Dodge City.

Now don’t paint me as even older than I am. We weren’t handing in decks of punched cards to a white-coated operator. Heck no, that was the year before. And what we’d have been doing if we were mere students rather than privileged Comp Sci grad students. No, we had accounts on the university mainframe and access to terminals in public computer rooms. I was living off campus and didn’t have a car, so I batched up my work, and scheduled long sessions for myself on the terminals.

For a class with Mitch Wand, or maybe it was Gene Freuder, I decided to write a Lisp program to play five-card draw poker. Or maybe it was a different problem. And maybe I wrote it in Prolog. It was a long time ago, and I’m a little fuzzy on the details. I do remember that I set up a TV tray in front of my comfy chair in my off-campus apartment, got my first of many cups of coffee and a pen and a fresh new yellow pad, and started writing.

I wrote a top-level solution to the problem in five lines of Lisp—or possibly Prolog—and went on from there. I tackled the problem with my newly-embraced principles of five-line functions and stepwise refinement. I grew a mighty tree of desirable help functions in good clean four-to-five-line chunks of Lisp (or Prolog), not stopping until every leaf of the tree was “expressed in terms of an underlying computer or programming language.” It was a thing of beauty.

And it remained a thing of beauty until I got on my bike and pedaled in to campus and sat down at a terminal and started keying it in and debugging it.

Then it became a total disaster.

And it remained a total disaster right up to and past the deadline for turning in the assignment. Mitch chastised me severely. To have so much written and so little tested showed a fundamental misunderstanding of software development practice, Mitch said. Or possibly Gene.

Anyway, that’s how I became educated in the necessity of testing code as you go. Finally, now I knew how to write code.

Stepping Away from the Keyboard

More years would pass before I learned that I still didn’t know how to write code, and that it might actually make sense to write the test even before writing the code.

I share these embarrassing experiences from my early days as a programmer as a preface to saying something really obvious: It’s still useful to code offline.

Granted, programming has changed since those long-ago days. Today the tools and techniques we have for testing and debugging make it silly to think of making the bonehead mistakes I made back then. And when the typical programming project is made up of many pieces complexly combined, the idea that you might go off and write an entire program with pen and paper seems quaint.

But it’s not hard to think of reasons to work on paper for a while. I’m suggesting something more specific. Because I needed to find a way of referring to this tool that I find so useful, I call it the rhythm of focus.

It’s something that I use regularly in writing prose, and it’s one of the tricks that allowed me to finish a 50,000-word novel (well, draft of a novel) in 30 days in November. It’s really simple: when I find myself staring at the screen and no longer making progress, I print out the current chunk of writing and go somewhere else and hack away at it with a pen. This never fails to get me past the current difficulty. I see the work with a fresh perspective and I see a way of approaching my difficulty. I don’t necessarily solve any major problems in this way, but it gets my wheels out of the ditch. Every time.

And then I go back online, starting in gently with the mindless task of keying in the changes I made offline. At this point I’m ready to work online again. In a longer piece of writing, this back-and-forth becomes a steady rhythm that keeps me moving forward. For the novel, I worked offline in the house in the evening and online in the office in the morning, every day. And in this way, I wrote an average of 1667 words a day for 30 days. It’s not just a matter of getting a different perspective on the work, although it is that. It’s also about getting in touch with the rhythm of your own attention. I call it the rhythm of focus, and I know from experience that it works for writing prose.

Does it work for writing code? In my limited experience, yes. As a programmer, I'm still a cowboy, though I hope not of the spaghetti code variety. I write chiefly for myself. And all I can say is that this is exactly how I worked on the most recent program I wrote, a cryptogram generator that I used for this magazine and for a staff party. It worked for me. It might work for you.

Michael Swaine is the editor of PragPub.

The Daily Shoot

Practice Really Does Make Perfect
by James Duncan Davidson
Duncan talks about The Daily Shoot, his and Mike Clark’s clever idea that is motivating hundreds of photographers to work at their craft every day.

Practice make perfect, right? That’s what we’ve all been told. I know that I heard it many times growing up as I was taking music lessons. At the time, confident in my own raw talent and ability, I dismissed the advice as patronizing and unreasonable. Either you had it or you didn’t. Well, not practicing didn’t work out so well. Looking back, I’m sure that I tortured everyone who ever heard me play a musical instrument.

As misguided as my youthful opinion about practice was, it turns out that my actions were proving my opinions wrong. There were two things back then that I devoted significant practice time to that would serve me very well later in life.

The first was dinking around with computers of one kind or another. My father purchased an early Apple ][+ and I spent many hours on many late nights peeking and poking that Apple ][+ and subsequent computers. Ludicrous amounts of time. So when the World Wide Web emerged in the 1990s, I was set. It turns out that what I had been doing was practicing. I put in so much practice, in fact, that it was an easy and natural transition from architecture school into a different kind of architectural career—one focused on building web applications and development frameworks.

The second thing I devoted a lot of time while growing up—in fact, through school and into my career as a software engineer—was photography. I picked up my first camera at a very early age and my grandmother fueled my interest by teaching me the basics of the darkroom. My parents couldn’t leave film around and expect it to stay unexposed. 110. Disc. 35mm. I shot it all. Later on, I documented my travels around the world while working on software with digital cameras. With all that practice, it was an easy and natural transition from a career in software into a career in photography.

Practice As Play, not Drudgery

Natural, that is, looking back on it. It’s only in hindsight that it becomes obvious that what I was actually doing was practicing at both software and photography. At the time, I just thought I was just having fun.

But it didn’t stop there. As accomplished as I might have been when I started shooting professionally, it’s what happened next that surprised me the most. As I shot thousands and then hundreds of thousands of frames, I noticed that I continued to acquire skills, and at a rapid pace. My relationship with and understanding of light deepened. And I finally sorted out that I was good at the things I was good at not because I was talented or gifted. It was because I was practicing intensely all that time and learning all the time—even though it didn’t feel like learning. I’m still learning today, and will be for as long as I use the camera.

Practice makes perfect. It keeps honing your skills for as long as you keep practicing.

If practice does indeed make perfect, then how does one set about it? Especially for an art and craft like photography, which most people practice just for the fun of it? Obviously, you don’t want to sit down and make it an obligation. That way is doomed to fail, just like making kids take music lessons when they don’t see the point.

What if, instead of a structured obligation, somebody would just nudge you and say, “Hey, why don’t you take a picture of something blue today?” It might be just enough of an excuse to get you to pick up the camera. Once you picked it up, you might spend some time tinkering with it. And, along the way you would pick up some practice. Practice that would feel like play, not like drudgery or an obligation.

This idea has been at the core of a number of conversations I’ve had with Mike Clark, a fellow software pro and amateur photographer. As Mike’s skills with his camera improved, he started looking for ways to keep practicing—some way to give himself a little push to get out there and use his camera. We always left those conversations off with the thought that, yes, it’d be nice, but we couldn’t see how to make it a reality for ourselves, much less for anybody else.

The Daily Shoot

Then one day we hit on the silly idea of using Twitter to give us a daily photographic assignment of sorts. Not a formal project, mind you. Just a quick nudge to see if we could encourage ourselves to pick up the camera and do something with it. Twitter provides a perfect medium for this. By forcing an assignment to fit into 140 characters, we’d ensure that it would be short enough to be wide open to interpretation. Perfect for letting people practice—and play around—from a quick and straightforward starting point.

Once we had that idea, it was a short series of steps to find CoTweet—a service that allows you to schedule tweets in a cron-like fashion—and then batch up a couple of weeks worth of assignments. In the span of a few hours as Mike and I played around, The Daily Shoot was born.

Within a few days, we’d proven to ourselves that the concept was sound and announced it to the world using the @dailyshoot Twitter account. We followed up shortly with a simple website and then a few weeks later with a much more sophisticated website built with Ruby on Rails, a framework that both Mike and I have a lot of experience in.

Along the way, thanks entirely to Twitter’s easy distribution of a simple idea around a large social network, we’ve built up quite an interesting worldwide community of hundreds of photographers who take the challenge and respond to our daily nudge to make a photograph. Many of these photographers respond to our assignments with a tweet that links to a photograph that they made. Better yet, it looks like many are using the assignments as a stepping stone to spending more time with their cameras.

In addition to photographs, we’ve received a lot of feedback. Some of the feedback has prompted us to add a feature. For example, anybody can now suggest an assignment using our website. This was a direct result of an exchange that I had with Lyza Gardner, a Portland-based photographer who is also a co-host of the Social Photo Talk podcast. For the most part, however, the feedback has been an outpouring of shout-outs for encouraging photographers to get out there and shoot.

That’s the entire point, of course. The Daily Shoot isn’t a contest. There are no winners and no losers. There are no grades and no recitals. There aren’t even any real rules to speak of. The only things we ask are that photographers don’t pull something out of their archives to link up, and that they edit their photographs down to one submission for any particular assignment. Beyond that, it’s wide open. If you miss a day or a week, that’s fine. Jump back in whenever. After all, the thing we’re trying to do is to continually encourage photographers to make photographs, not just “take a shot” once in a while. In a way, we’re providing a good excuse for people to have a bit of fun with their camera.

What’s next? That’s a good question. Mike and I have been listening to people who visit the site, who follow @dailyshoot on Twitter, and who have been providing lots of feedback. We want to keep The Daily Shoot evolving. Quite honestly, working on the website is the most fun that we’ve had working with software in a while. It’s a great marriage of things that interest us and it’s fascinating to watch the community respond. Plus, I’m humbled to think that we’re helping others in some small way do something they love.

James Duncan Davidson (@duncan) is a photographer and recovering software engineer. He travels the world making photographs at interesting conferences such as TED, Web 2.0 Summit, and RubyConf. His website is duncandavidson.com.

The photo of Rick LePage going low and finding the right angle is by Duncan Davidson. Mike Clark made the two winter tree photos and the pizza photo. They are used here with the permission of the photographers. The pizza was made by Daniel Steinberg.

Against SEMAT

Thinking Differently about a Proposed Software Engineering Revolution
by Jorge Aranda
You say you want a revolution? Well, you know.... Dozens of really smart people call for a software engineering revolution, and one grad student asks to see the plan.

You may have heard of a recent call for action that goes by the name of SEMAT (Software Engineering Method and Theory). It is backed by many of the great names in software industry and research; Ivar Jacobson, one of its proponents, presents it as a “revolution” whose goal is “to re-found software engineering as a rigorous discipline.”

What is it all about? The call for action itself is succinct, so it is helpful to reproduce it here for discussion:

Software engineering is gravely hampered today by immature practices. Specific problems include:

- The prevalence of fads more typical of fashion industry than of an engineering discipline.

- The lack of a sound, widely accepted theoretical basis.

- The huge number of methods and method variants, with differences little understood and artificially magnified.

- The lack of credible experimental evaluation and validation.

- The split between industry practice and academic research.

We support a process to re-found software engineering based on a solid theory, proven principles and best practices that:

- Include a kernel of widely-agreed elements, extensible for specific uses

- Addresses both technology and people issues

- Are supported by industry, academia, researchers and users

- Support extension in the face of changing requirements and technology

It seems, judging by the hundreds of supporters of SEMAT so far, that for many people this call for action is a way to build a much-needed consensus in our field. But a close analysis leads me to conclude that it is a misguided movement. Let me explain my reasons (and note that I’ve posted similar criticisms on my blog).

Words Matter

First, it’s important to remember that our choice of words matters. Research shows that the way we frame a problem influences the strategies we use to solve it, and blinds us to other potential solutions. One instance out of many: the name of the games we play biases our behavior. In a 2004 study, players of a board game called “the Wall Street game” were far more cutthroat and less cooperative than players of a board game called “the Community game,” even though the rules for both games were exactly the same!

For decades now, the dominant metaphor for software development, at least in academia and in the trade literature, has been to treat it like an industrial engineering problem. Thus we call what we do “software engineering,” we attempt to define and compartmentalize its processes, we institute measurements and quality control cycles, and we treat the whole thing more or less like an assembly line.

It is a useful metaphor, to an extent. The problem is that the metaphor is so ingrained that we tend to forget that that’s all it is, that knowledge work is not industrial work and that coding is not manufacturing. We convince ourselves that what we do actually is industrial engineering and then we wail in desperation when we see that we’re not up to the standards of other engineering disciplines.

Fads and Progress

In fact, software development has little to do with most established engineering disciplines, and some people in the community (notably, but not exclusively, Tom DeMarco) have spoken against this paradigm. For this reason it is frustrating and disappointing that SEMAT, a supposedly “re-foundational” effort, is still trapped in the old and worn engineering metaphor: it takes for granted that we do “software engineering,” and that we should strive to do what other engineers do instead of wasting our time with “fads” that are more like this season’s frivolous fashion trends than like the serious, professional, piecemeal progress we should be aiming for.

Let’s turn a blind eye to the fact that several of those “fads” were started or promoted by some of the signatories of SEMAT. It is true that fads are prevalent in the software industry. But some of them (for instance, object orientation or extreme programming) end up being pretty good ideas, and some become mainstream. We stifle innovation if we dismiss every grassroots innovation and every exciting new idea as nothing more than a capricious fad just because it doesn’t fit with our preconceptions of what progress should look like.

And what should progress look like? The SEMAT call for action offers several hints, not all of them far-sighted. For example, it tells us that we should evaluate and validate practices experimentally. I’m in favor of controlled experiments in software research, of course, but I don’t think they should be singled out as the only or the most important empirical strategy at our disposal. As a researcher who has applied both experimental and non-experimental methods in software development, I have seen that controlled experiments tend to abstract away important elements of the phenomena we study, whereas non-experimental methods, such as case studies, provide a richness that is necessary and insightful. But since we see that engineers give primacy to experiments, we feel we should imitate them.

Theory and Research

The second half of the call for action is as disappointing as the first, and more puzzling. SEMAT proposes to re-found the field with “a solid theory” that includes “a kernel of widely-agreed elements,” but the proposal is completely silent regarding which theory and which elements it intends to use. It is a jarring thought: a group of people picks up a theory and by decree, bypassing any kind of peer review process, determines that the software field shall be built upon it. To my knowledge there is no scientific field that has prospered under such a shoddy epistemological basis.

The problem is that if we have a kernel of widely-agreed elements, that in itself is our theory, and we don’t need to re-found anything. We do not have a theory precisely because we do not have a kernel of widely-agreed elements—and judging by the list of the signatories of SEMAT, it’s hard to see how such a kernel could arise. A few examples: the list includes Watts Humphrey (creator of SEI’s CMM) and Ken Schwabber (co-creator of SCRUM). It includes formalists like David Harel and pragmatists like Erich Gamma; agilists like Alistair Cockburn and measurement apologists like Capers Jones. The list itself suggests that, more than a kernel of widely-agreed elements, what we already have is several vaguely formulated and competing theories that need to be made explicit, refined, and compared. I believe this is where we should spend our efforts.

The rest of the items in the SEMAT statement are innocuous enough to be unobjectionable. I think everybody would agree that we need stronger theoretical frameworks, more and better links between practice and research, and practices that are flexible and technologically and socially valuable. We can all rally behind such a wishlist. But there’s nothing here to go on, no stake in the ground, no bold re-foundational vision; just a recycled wish to get rid of controversies and to be more like an engineering discipline. A revolution might come to the software field one day, but not today.

Discuss this article with the author and other readers in the magazine forum. -Mike

Jorge Aranda is a Ph.D. student in Computer Science at the University of Toronto. He researches communication and coordination in software teams, the development of shared understanding, group cohesion, and the fitness and convenience of the paradigms that our community uses, sometimes inadvertently, to study these concepts. His academic website is at www.cs.toronto.edu/~jaranda/

Touching the Core

Now iPhone and iPod Touch Developers Can Touch the Power of Core Data.
by Marcus Zarra
Marcus walks you through using the NSFetchedResultsController, a powerful new class in the Core Data API that can make your iPhone, iPod Touch, and Mac apps significantly richer.

Development for iPhone and iPod Touch is getting easier, and Apple is giving us access to more of its OS goodies. With the release of the 3.0 OS for the iPhone and iPod Touch, we gained the ability to use Core Data directly on our touch devices. With this inclusion came a new class to the Core Data API, the NSFetchedResultsController. The NSFetchedResultsController is intended to be the bridge between Core Data and the UITableView. However, that description scarcely does it justice.

In addition to just being a bridge between the two APIs (Cocoa Touch and Core Data), it also plays an active role in keeping the UI updated to what is occurring within Core Data. This syncing is powerful and easy, allowing us to update the Core Data repository asynchronously to the UI and the UI will “just work.” Getting it working is a little tricky, so I thought an article spelling it out would be helpful.

Constructing The Controller

Easily the most complicated step to using the NSFetchedResultsController is its construction. Fortunately this complexity pays off later when we are accessing it. The NSFetchedResultsController is constructed as a “wrapper” around the NSFetchRequest. The reason for this is that the data set the NSFetchedResultsController is working with is living (aka dynamic). When something changes in Core Data that impacts the results the NSFetchedResultsController is handling, it will respond to those changes. Therefore instead of just initializing with a static set of data, the NSFetchedResultsController is initialized with the information to construct that set of data. This allows the NSFetchedResultsController both to monitor the data and to “refresh” itself automatically.

Therefore, the construction of the NSFetchedResultsController starts off with the construction of a NSFetchRequest.

NSFetchRequest *fetchRequest = nil;

fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = nil;

entity = [NSEntityDescription entityForName:@"FeedItem"

inManagedObjectContext:[self managedObjectContext]];

[fetchRequest setEntity:entity];

[fetchRequest setFetchBatchSize:20];

NSSortDescriptor *sortDescriptor = nil;

sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pubDate"

ascending:NO];

NSArray *sortDescriptors = nil;

sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

Once the NSFetchRequest has been constructed we next need to build the wrapping NSFetchedResultsController.

NSFetchedResultsController *frc = nil;

frc = [[NSFetchedResultsController alloc]

initWithFetchRequest:fetchRequest

managedObjectContext:[self managedObjectContext]

sectionNameKeyPath:nil

cacheName:@"Root"];

[frc setDelegate:self];

[self setFetchedResultsController:frc];

[frc release], frc = nil;

The NSFetchedResultsController takes the NSFetchRequest that we constructed previously along with a reference to the NSManagedObjectContext, a section key path, and a cache name.

The section key path is used to generate the section names. If, for example, we are building an Address Book application, then we may want this key path to lead to the last name of the people being displayed in the table view.

The cache name is used to cache the data retrieved by NSFetchedResultsController for faster access while the UITableView is being used. If Core Data finds an existing cache with the same name and it matches the NSFetchRequest then it will load that cache directly and avoid the overhead of computing the section and index information. Otherwise the cache is deleted and rebuilt.

Once the NSFetchedResultsController has been constructed, we want to give it a delegate. This delegate, implementing the NSFetchedResultsControllerDelegate protocol, will receive callbacks whenever the data has changed. The above code block, taken from our example application (and linked to below), passes self as the delegate because this NSFetchedResultsControllerDelegate is being constructed by the UITableViewController.

So Now What?

Congratulations! You’ve made it through the hard part. So now that we have this wonderful NSFetchedResultsController, what do we do with it? To see this, lets start with the methods that a UITableViewDatasource handles.

- (NSInteger)tableView:(UITableView*)tableView

numberOfRowsInSection:(NSInteger)section

{

id <NSFetchedResultsSectionInfo> sectionInfo = nil;

sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];

return [sectionInfo numberOfObjects];

}

The -tableView:numberOfRowsInSection: is one of the two truly required methods in a UITableViewDatasource. However, as you can see from this implementation, the NSFetchedResultsController has reduced this method down to 3 lines of code. In fact you could easily reduce this to a single line of code. Since the NSFetchedResultsController is aware of both the data and the structure of the table, it knows exactly how many rows are contained in each section. All we have to do is ask it.

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView

{

return [[fetchedResultsController sections] count];

}

A less frequently used method, The -numberOfSectionsInTableView: method can also be reduced to a single line of code. Because the NSFetchedResultsController knows the number of sections, and calculates these for us automatically, it is again a single line of code to ask it.

Ordinarily the most complicated method in a standard UITableView is the -tableView:cellForRowAtIndexPath:. Fortunately the NSFetchedResultsController helps us a little bit here also.

- (UITableViewCell*)tableView:(UITableView*)tableView

cellForRowAtIndexPath:(NSIndexPath*)indexPath

{

UITableViewCell *cell = nil;

cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

if (!cell) {

cell = [[[UITableViewCell alloc]

initWithStyle:UITableViewCellStyleSubtitle

reuseIdentifier:kCellIdentifier] autorelease];

[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

}

[self configureCell:cell atIndexPath:indexPath];

return cell;

}

While the construction of the cell remains unchanged, we can easily retrieve the correct NSManagedObject with a single line of code. However, for reasons explained below, we handle the population of the cell in another method: -configureCell:atIndexPath:.

- (void)configureCell:(UITableViewCell*)cell

atIndexPath:(NSIndexPath*)indexPath

{

NSManagedObject *mo = nil;

NSString *temp = nil;

mo = [fetchedResultsController objectAtIndexPath:indexPath];

temp = [[managedObject valueForKey:@"title"] description];

[[cell textLabel] setText:temp];

temp = [[managedObject valueForKey:@"author"] description];

[[cell detailTextLabel] setText:temp];

}

Depending on how the data is constructed, determining the right dataset for the cell can be a complex operation. However with the NSFetchedResultsController it is again a single line of code to retrieve the correct NSManagedObject and then use it to populate the cell.

Where is the Magic?

While all of this is nice, and probably is enough justification on its own to use a NSFetchedResultsController, there is more. When the data has changed outside of the control of our UITableViewController, it would be nice if the controller was notified so that the table could be refreshed. This is where the true power and utility of the NSFetchedResultsController lies. With the implementation of four methods, our UITableViewController can automatically receive notifications of changes in the data and respond appropriately. The four methods correspond to a simple workflow: I am about to do something, I am doing something, I am done doing something.

I Am About to Do Something

The -controllerWillChangeContent: method is the “I am about to do something” phase of the notification. If our table structure is simple and short (i.e. one section and a dozen rows or so) then we can just call [[self tableView] reloadData] and be done with it. However, assuming our table view is more complex, we want to start a transaction against the UITableView in preparation for the “I am doing something” methods that are about to follow:

- (void)controllerWillChangeContent:(NSFetchedResultsController*)controller

{

[[self tableView] beginUpdates];

}

A call to [[self tableView] beginUpdates] tells the UITableView that we are going to be making one or more changes to its structure and for it to wait to make visual changes until we are done.

I Am Doing Something

The -controller: didChangeSection: atIndex: forChangeType: method is one of two methods in the “I am doing something” phase of our workflow. This method is called once for each section that has been added or removed. Fortunately this method is easy to handle: we simply instruct the UITableView to insert or remove the section affected.

- (void)controller:(NSFetchedResultsController*)controller

didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo

atIndex:(NSUInteger)sectionIndex

forChangeType:(NSFetchedResultsChangeType)type

{

NSIndexSet *set = [NSIndexSet indexSetWithIndex:sectionIndex];

switch(type) {

case NSFetchedResultsChangeInsert:

[[self tableView] insertSections:set

withRowAnimation:UITableViewRowAnimationFade];

break;

case NSFetchedResultsChangeDelete:

[[self tableView] deleteSections:set

withRowAnimation:UITableViewRowAnimationFade];

break;

}

}

The -controller: didChangeObject: atIndexPath: forChangeType:newIndexPath: method is a bit more complicated. This method is called once for each row that is affected. This could be an insert, delete, move, or just an update to the data. For each of those possible states we need to handle it by informing the UITableView.

- (void)controller:(NSFetchedResultsController*)controller

didChangeObject:(id)anObject

atIndexPath:(NSIndexPath*)indexPath

forChangeType:(NSFetchedResultsChangeType)type

newIndexPath:(NSIndexPath*)newIndexPath

{

UITableView *tv = [self tableView];

switch(type) {

case NSFetchedResultsChangeInsert:

[tv insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]

withRowAnimation:UITableViewRowAnimationFade];

break;

case NSFetchedResultsChangeDelete:

[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]

withRowAnimation:UITableViewRowAnimationFade];

break;

case NSFetchedResultsChangeUpdate:

[self configureCell:[tv cellForRowAtIndexPath:indexPath]

atIndexPath:indexPath];

break;

case NSFetchedResultsChangeMove:

[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]

withRowAnimation:UITableViewRowAnimationFade];

[tv insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]

withRowAnimation:UITableViewRowAnimationFade];

break;

}

}

I mentioned above that the population of the UITableViewCell was extracted into its own method for a reason. The -controller: didChangeObject: atIndexPath: forChangeType: newIndexPath: method is the reason. When a row is updated as opposed to inserted, deleted or moved, we want to just refresh the values displayed. Instead of duplicating the cell population code here, it is moved into its own method, which is then called from both the -tableView:cellForRowAtIndexPath: method and here.

I Am Done Doing Something

The final method, which completes the workflow, is the -controllerDidChangeContent: method. This is our “I am done doing something” call. It is here that we close up the transaction for the UITableView so that it can update the user interface. If we need to update other aspects of the user interface (perhaps a toolbar), this would be the appropriate place.

- (void)controllerDidChangeContent:(NSFetchedResultsController*)controller

{

[[self tableView] endUpdates];

}

See It in Action

To see a fully working example of the NSFetchedResultsController I recommend downloading the example RSS Reader that I posted on GitHub.

In this example I set up a UITableViewController as described in this article and use it to display the headlines from the PragProg RSS Feed. Apart from the use of a NSFetchedResultsController, the interesting part of this example is that the retrieval of the data is completely separate from the UITableViewController. The retrieval is performed in a NSOperation and written directly to the Core Data Repository. Because of the NSFetchedResultsController, however, the data is automatically updated in the UITableViewController as soon as the operation performs a save on the NSManagedObjectContext.

The NSFetchedResultsController is a powerful addition to our toolkit for Cocoa Touch development. It allows us to remove a tremendous amount of code from our UITableViewController objects.

And of course, less code means fewer bugs :)

Discuss this article with the author and other readers in the magazine forum. -Mike

Marcus S. Zarra is the owner of Zarra Studios LLC and the creator of seSales and iWeb Buddy as well as being a co-author of “Cocoa Is My Girlfriend",” a wildly popular blog covering all aspects of Cocoa development. Marcus has been developing software since the mid-1980s and has written software in all of the major technological fields. Marcus has been using Core Data since its original release in OS X 10.4 Tiger and has released numerous applications and papers covering all of the topics of Core Data including the book, Core Data: Apple's API for Persisting Data on Mac OS X for The Pragmatic Programmer.

Much Ado About Nothing

Gazing into the Abyss of Ruby’s nil, amongst Null Objects, Ghost Methods, and Black Holes.
by Paolo Perrotta
One thing that we learn from exploring the metaprogramming features of Ruby is that nothing is a deep concept.

Talk about an exhausting Monday!

You’ve spent the entire day pair programming with Bill, your excellent, experienced, and sometimes exasperating buddy. The two of you are putting the final touches to the Alarm Manager—a useful piece of Ruby code that sends alerts to your colleagues when the main company-wide application has a glitch.

The Alarm Manager is just a short program, but it sports a flexibility to rival Twitter. It can send different kinds of alarms to any remote device, from brand new iPhones down to vintage pagers. Here is the cornerstone Alarm Manager class:

class Alarm

def device

CONFIGURATION.current_user.device

end

def send_default

10.times { device.ring }

end

def send_discreet

device.ring

end

def send_silent

100.times { device.flash }

end

end

The Alarm#device method reads the device associated with the current user from a CONFIGURATION constant. Your program can send alarms to any device, as long as the device can flash a light and ring. The send_default method rings ten times, send_discreet only rings once, and send_silent just flashes the light for a while.

You’re just one click away from a working Alarm Manager. After configuring the system with the devices of all your colleagues, you and Bill fire the last functional test... and watch in horror as it fails.

NoMethodError: undefined method 'ring' for nil:NilClass

Luckily, it doesn’t take much to find the cause of the error: Bob, your absent-minded colleague, recently lost his cell phone. Now the CONFIGURATION class doesn’t return any device for Bob—instead, it returns nil, Ruby’s value for an uninitialized object reference. When Alarm attempts to call ring or flash on nil, the call fails with a NoMethodError.

Uninitialized references are a common nemesis of object-oriented programmers. (Just ask a Java coder how many NullPointerExceptions she’s seen in her life!) How can you avoid this problem?

As a first attempt, you and Bill check the object returned by device to ensure that it’s not nil. For example, Alarm#send_default becomes:

class Alarm

def send_default

»      return unless device

10.times { device.ring }

end

# ...

It just takes that single line of code to push old Bill into one of his legendary bursts of complaining. “I don’t want to add an extra if to each and every method!” he exclaims. “I think I know a better way to fix this problem. Let me show you something...”

Null Objects

Bill is eager to show you a magic programming spell known as Null Object. A Null Object is just a regular object whose methods do nothing.

Bill grabs a scrap of paper and draws a picture to show you how a Null Object is supposed to work. The idea is that you can replace an uninitialized reference with a Null Object. You can then call methods on the object, and the object will trash your messages without raising an error.

In some situations, “doing nothing” might mean returning zero, writing a zero-length file, or returning an empty string. In the case of your Alarm class, “doing nothing” just means that both the flash and ring methods are empty:

class NullDevice

def flash; end

def ring; end

end

Alarm#device can now return the configured device if it exists, and a NullDevice if it doesn’t:

class Alarm

def device

CONFIGURATION.current_user.device || NullDevice.new

end

# ...

If you’re new to Ruby, you might find the line of code in device confusing. Bill explains that this idiom is called a Nil Guard. Alarm#device only returns CONFIGURATION.current_user.device if it’s not nil.

If CONFIGURATION.current_user.device is nil (or false), then Alarm#device returns a NullDevice. Now, no matter what happens, the device method will always return something that you can safely call ring and flash on—so you can avoid littering the callers of Alarm#device with defensive ifs.

However, grumpy old Bill is not satisfied yet. “This Null Object looks really Java-ish,” he mumbles, frowning. “I think that we can make it more like idiomatic Ruby. Here is how...”

Playing Ruby’s Strengths

In most languages, an uninitialized object reference is just a big arrow pointing at nothing. On the other hand, in Ruby there is no such thing as “nothing.” The nil value is actually a regular object—the sole instance of NilClass:

nil.class     # => NilClass

Another powerful feature of Ruby is that classes are never closed. You can always re-open and modify an existing class, NilClass included. This means that there is no need for a NullDevice class. Instead, you can define flash and ring on NilClass itself:

class NilClass

def flash; end

def ring; end

end

Now you don’t need to check whether CONFIGURATION.current_user.device is nil. In fact, nil itself has become a Null Object: you can call flash and ring on it, and it will do nothing. Wonderful!

However, you probably don’t want to pollute NilClass with your own domain-specific methods. As Bill is ready to observe, you can find a more elegant solution in yet another Ruby magic spell: a special method named method_missing. If you implement method_missing, it will intercept all calls to methods that don’t exist. Just replace NilClass#flash and NilClass#ring with method_missing, and method_missing will take care of all calls to nil:

class NilClass

# Calls to flash(), ring() or other unknown methods

# end in method_missing().

# The asterisk means that arguments are ignored.

def method_missing(*); end

end

Now you can say that flash and ring are Ghost Methods, because the caller thinks they exist, but actually they don’t.

Bill draws a picture to show you how your new Null Object works:

If you use Ghost Methods instead of flesh-and-bones methods like flash and ring, you also get another advantage for free: if you add new methods to your devices (say, a beep method), then you don’t need to add the same methods to nil. Instead, nil will simply ignore calls to any method that it doesn’t know about.

Beyond Null Objects

Just as you’re about to turn off your computer and call it a day, you and Bill get one of those last-minute change requests. Your boss wants an Alarm#send_urgent method for devices that have a controllable light:

class Alarm

def send_urgent

100.times do

device.light.change_to_red

device.ring

device.light.turn_off

end

end

# ...

“This is wonderful!” Bill exclaims, smiling for the first time this week. (For a moment, you think that he’s slipped away for good). “If we’d stuck with the NullDevice class, now we’d also need a NullLight class, to call change_to_red and turn_off. Instead, with our nil-based solution, we don’t have to write a single line of code. Here, let me draw a picture...”

The trick here is that Ruby has no such thing as a “void” method. Instead, each and every method always returns a value. In particular, an empty method always returns nil. Now, look at your NilClass again:

class NilClass

def method_missing(*); end

end

NilClass#method_missing is empty, so it returns nil. This means that any call to a Ghost Method on nil returns nil itself. You can then call another Ghost Method on nil, chaining arbitrary calls like in the case of device.light.change_to_red. When used this way, a Null Object such as nil is also called a Black Hole. A Black Hole sucks your method calls into an infinite depth of Null Objects, avoiding the problems associated with uninitialized references.

On the other hand, Black Holes can cause their own share of trouble. After all, NoMethodErrors are there for a reason: they help you spot bugs in your code. A Black Hole can mask those bugs and make it more difficult for you to notice when things go wrong. Bill’s recommendation is that you should try Black Holes yourself, and decide whether they work for you. After all, there is at least one popular language (Objective C) where all null reference are Black Holes by default.

However, this interesting discussion can wait for another day. Today, you and Bill can finally slip out of the office and dump yourselves in the nearest pub!

Paolo Perrotta has more than ten years of experience as a developer and writer. He worked for domains ranging from embedded to enterprise software, computer games, and web applications. These days, Paolo coaches agile teams for a huge Internet fashion shop and teaches Java to developers throughout Europe. He lives near Bologna, Italy, with his girlfriend and a cat. He likes the Ruby language so much, he wrote a book about it.

The Quiz

Who Said What: The Language Creators
by Michael Swaine
The following table contains the names of 19 notable (and quotable) language creators, each paired with his or her most famous language creation. We’ve done that match-up for you. Your challenge is to match each notable quotable language creator with a quote.

Following the table you will find 19 quotes by these language creators. The third column of the table is for your convenience in solving the quiz. If you’ve printed it out, you can enter the number of the quote in that third column.

You will find, though, that things don’t quite match up. If you identify all the quotes, you will find two quotes by one author and no quote by a different author. The odd man (or woman) out is the ultimate answer to this month’s quiz: Which language creator is unrepresented by any quote?

Please do not confuse our quiz with this one: Programming Language Inventor or Serial Killer?

Language Creators and their Languages

Language Creator

Language(s)

Quote

Dennis Ritchie

C

Bjarne Stroustrup

C++

Grace Hopper

COBOL

Bertrand Meyer

Eiffel

Chuck Moore

Forth

John Backus

Fortran

Rob Pike

Go

James Gosling

Java

John McCarthy

Lisp

Stephen Wolfram

Mathematica

Tony Hoare

CSP

Niklaus Wirth

Pascal

Larry Wall

Perl

Rasmus Lerdorf

PHP

Guido van Rossum

Python

Yukihiro Matsumoto

Ruby

Alan Kay

Smalltalk

David Farber

Snobol

Alan Cooper

Visual Basic

The Quotes

1. “The wonderful thing about standards is that there are so many of them to choose from.”

2. “When the world becomes standard, I will start caring about standards.”

3. “When I read commentary about suggestions for where [my language] should go, I often think back and give thanks that it wasn’t developed under the advice of a worldwide crowd.”

4. “Don’t you hate code that’s not properly indented? Making it part of the syntax guarantees that all code is properly indented!”

5. “I believe consistency and orthogonality are tools of design, not the primary goal in design.”

6. “Our thirty year old belief that there is only one kind of computer is the basis for our belief that there is only one kind of programming language.”

7. “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.”

8. “No matter how cool your interface is, it would be better if there were less of it.”

9. “As for our grandchildren, only the paleontology professors among them will know what C++ was.”

10. “I invented the term ‘Object Oriented’ and I can tell you that I did not have C++ in mind.”

11. “All processes, whether they are produced by human effort or occur spontaneously in nature, can be viewed as computations.”

12. “You can have quality software, or you can have pointer arithmetic; but you cannot have both at the same time.”

13. “Real programmers can write assembly code in any language.”

14. “I am convinced that there is a need for high quality software, and the time will come when it will be recognized that it is worth investing effort in its development and in using a careful, structured approach based on safe, structured languages.”

15. “All computer languages are write-only.”

16. “Everyone needs computer programming. It will be the way we speak to the servants.”

17. “I prefer to have as little as possible to do with Bertrand Meyer.”

18. “It’s been a really weird summer.”

19. “I could tell you stories that would curdle your hair.”

Last month we presented you with a Sudoku puzzle with a twist—it used letters instead of digits and hidden within it was the name of a kind of document sometimes written by software developers.

Solution to Last Month’s Quiz

M

A

N

I

F

E

S

T

O

S

O

E

M

T

A

F

N

I

I

F

T

O

S

N

M

A

E

E

M

F

N

I

S

T

O

A

N

T

O

E

A

M

I

S

F

A

S

I

F

O

T

E

M

N

F

I

A

T

M

O

N

E

S

O

E

M

S

N

F

A

I

T

T

N

S

A

E

I

O

F

M

Calendar
by Jackie Carter
Author sightings, partner events, and other notable happenings.

Author Appearances

- Jan 11-14, Obtiva, Chicago IL
Ruby on Rails TDD Boot CampNoel Rappin

- Jan 13, Inman News ConnectTech NYC
“Tips and Tricks for Working with the iPhone SDK”Mike Mangino

- Jan 13, Dallas Java User Group
“Unit Testing and Mocking with Groovy”Venkat Subramaniam

- Jan 13-15, Obitva’s Ruby on Rails TDD Boot Camp, Chicago IL
Ruby on Rails TDD Boot CampNoel Rappin

- Jan 13-15, CodeMash 2010, Sandusky, OH
Keynote: “The Mother of All Bugs”Andy Hunt

- Jan 13-15, CodeMash 2010, Sandusky, OH
“Introduction to iPhone SDK Development;” “How Do You Do That on iPhone?;” “Oh Crap! I Forgot (or Never Learned) C!”Chris Adamson, co-author of iPhone SDK Development

- Jan 13-15, CodeMash 2010, Sandusky, OH
“A Taste of Cocoa” (An intro to Mac OS X development); “Come for the Phone Stay for the Mac”Pragmatic Bookshelf editor and author Daniel H. Steinberg

- Jan 13, Inman News ConnectTech NYC
Tips and Tricks for Working with the iPhone SDKMike Mangino

- Jan 21, Grand Rapids Java Users Group
Driving Behaviour w/Cucumber on the JVMZach Dennis

- Jan 21, ACCU London
“Naked Objects”Dan Haywood

- Jan 21, Chicago Nerd Social Club, Chicago, IL
“Effective Job Interviewing From Both Sides of the Desk”Andy Lester

- Jan 23, UGI ALT.net conference, Milan
RESTPaolo Perrotta

- Jan 28-29, Japan Symposium on Software Testing
Keynote and a tutorialJohanna Rothman, author of Manage It! Your Guide to Modern, Pragmatic Project Management, Behind Closed Doors: Secrets of Great Management, and Manage Your Project Portfolio: Increase Your Capacity and Finish More Projects

- Feb 9-11, Speakerconf 2010, Aruba
TBABrian Marick

- Feb 11, Moscone Center, San Francisco
Macworld Expo

- Feb 17-18, PyCon 2010 Atlanta, Georgia
Tutorial session: Test Driven Web DevelopmentTravis Swicegood

- Feb 22, Skills Matter, London
“How to have your Domain Driven Design cake and eat it too”Dan Haywood

- Feb 22-24, JAX London conference
“Agile Coaching Secrets”Rachel Davies, coauthor of Agile Coaching

- Mar 8-9, Devnexus, Atlanta, GA
Java related topicsVenkat Subramaniam

- Mar 16-17, Scandinavian Developer Conference, Göteborg Sweden
“I Think I Finally Understand Mocks” and “Artisanal Retro-Futurism Crossed With Team-Scale Anarcho-Syndicalism”Brian Marick

- Mar 18-29, SPARK IT, Bangalore
Groovy and Java topicsVenkat Subramaniam

USENIX Events

- Feb 23–26, The Fairmont San Jose, 170 South Market Street, San Jose, CA 95113.
FAST ’10: The 8th USENIX Conference on File and Storage Technologies. Sponsored by USENIX in cooperation with ACM SIGOPS. “FAST ’10 brings together storage system researchers and practitioners to explore new directions in the design, implementation, evaluation, and deployment of storage systems.”

O’Reilly Events

- Feb 22-24, New York Marriott Marquis Times Square, 1535 Broadway, New York, New York 10036 USA
TOC: O’Reilly Tools of Change for Publishing. The O’Reilly TOC Conference “will decipher the tools of change in this industry and help cut through the hype for a more profitable future in publishing.”

- Mar 30-Apr 1, San Jose Marriott, 301 South Market Street, San Jose, CA 95113
Where 2.0: “Now in its sixth year, the Where 2.0 Conference is where the grassroots and leading edge developers building location-aware technology intersect with the businesses and entrepreneurs seeking out location apps, platforms, and hardware to gain a competitive edge.”

Other Happenings

- Jan 7-10
CES

- Jan 10
Donald Knuth is 72.

- Jan 11
Tony Hoare is 76.

- Jan 19
24th anniversary of the computer virus.

- Feb 9-13
Macworld Expo, SF

- Feb 12
Darwin Day: Charles Darwin’s 201st birthday.

- Feb 24
Steve Jobs is 55.

- Feb 29
Herman Hollerith’s 150th birthday.

- March 16
Richard Stallman is 57.

Shady Illuminations

Avatar
by John Shade
The man with the camera really is trying to capture your soul.

I finally bowed to social pressure and saw Jim Cameron’s Avatar. Or as one reviewer called it, Dances with Cats in the Uncanny Valley. I have to admit, it was smurftastic.

The astronomically expensive movie will undoubtedly make tons of money for Cameron and stimulate the economy. To the extent that the science fiction movie aftermarket is the economy. I do worry about its effect on impressionable young minds, though. Jon Udell tweeted after seeing the movie, “I want a ponytail... and also to be taller, thinner, and bluer.” Disturbing, yes, but understandable. Zoe Saldana, who had just finished playing Uhura in Star Trek 2009, here proves that blue is the new black, doing more for blue skin than Rebecca Romijn, Smurfette, and the ingestion of colloidal silver all put together.

The Valley of the Dolls

Most people who have seen Avatar seem to feel that Cameron pulled off the feat he had to pull off: to go beyond motion capture to the holy grail of emotion capture and vault across the Uncanny Valley. Don’t tell me you haven’t heard of the Uncanny Valley? It’s a place you don’t want to be. Nobody has explained it better than Frank Rossitano on 30 Rock:

“As artificial representations of humans become more and more realistic they reach a point where they stop being endearing and become creepy. [Points at graph.] We like R2D2 and C3PO. And up here we have a real person, like Han Solo. But down here we have a CGI storm trooper or Tom Hanks in The Polar Express. That’s the problem: You’re in the Valley now, and it’s impossible to get out.”

You’ve seen Beowulf? It crashed and burned in the Uncanny Valley. Although that is (barely) a matter of opinion. We each have our own Uncanny Valley. Mine is broad, stretching from Fantasia (classical music scares me) to anything with Arnold Schwartzenneger in it, from Twins to the government of California.

To jump the Valley, the avatars in Avatar don’t have to look human, because they aren’t, which made Cameron’s challenge a little easier. He only had to make his avatars look like Na’vi, a race of aliens created by his creative team. As I say, a little easier.

By the way, Jim Cameron is a techie, and the title of this movie is a techie’s title: sly, self-referential, and overloaded. “Look at me,” Cameron is saying, “In this movie about avatars standing in for people, I’ve replaced the actors with digital avatars. Am I cool or what?”

That’s so meta: the title refers to the content of the movie and at the same time to the making of the movie. What does that remind me of? Oh, yeah, Mel Brooks, 1976: Silent Movie, a silent movie about the making of a silent movie. Mel Brooks was making meta when James Francis Cameron was driving a truck and dreaming about being a director.

Too Fat to Play

Cameron didn’t invent avatars, although all the people milling around on deck in the long shots in Titanic were totally digital. Sky Captain and the World of Tomorrow co-starred a synthespian version of Laurence Olivier. And after Brandon Lee died in the making of The Crow, a stunt double finished the remaining scenes and Lee’s face was digitally overlaid on the stunt double’s. That movie was a critical and popular success, so who am I to suggest that they jumped the shark on the way into the Valley?

Avatars replacing actors in movies, that’s the future that Jim Cameron wants to create. But we’re already used to running our own avatars in first-person shooter computer games and in virtual worlds. Still, I’m not sure what Microsoft is saying with a recently disclosed patent application for “Avatar Individualized by Physical Characteristic.” Maybe, “You’re not cool enough to play this game.”

The patent envisions an avatar generator for virtual environments. Using “physical characteristic nonvolitionally obtained from a user” (oh really?) via “a third party health data collection repository, a healthcare smart card, a real-time physiological sensor (e.g., blood pressure, heart rate, blood glucose, peak flow, pedometer, etc.),” the generated avatar might look fat if you’re overweight or limit your play time if you aren’t keeping up with your exercise plan. Or it might prevent you from misrepresenting your gender, ethnicity, political affiliations, or intelligence—if I’m reading the patent app correctly.

It’s not hard to imagine the apps that this would enable. Anorexia: the Game would be a natural. I’m sure Jon Udell would snap it up in a minute. I can also imagine the high-minded Will Wright no-competition game that will come out of this: The Slims (the family that loses together wins together). (Can you tell that Will went to a Montessori school?) Yep, I can see how Microsoft will profit from people’s body-image issues, but I’m really eager to see how they make money off revealing users’ gender and politics.

The Darfstellar

Jim Cameron claims to be shocked when actors ask him if he plans to replace actors entirely. Why of course he doesn’t. Movies need stars, he explains, and while he longs for the day when movies stars’ personalities and images are totally avatarized and he can plug them in and play them like drum loops, he knows that you will always need those living, breathing human beings to promote the movies on talk shows and at supermarket openings.

Pretty much everything that Jim Cameron imagines about replacing actors—which has been his dream since he quit driving a truck—can be found in the 1955 Hugo-award-winning science fiction novelette “The Darfstellar” by Walter M. Miller, Jr. In that novelette, actors sell their personae to be used in avatars, until one disgruntled actor causes all kinds of chaos by secretly standing in for one of the avatars in a production. Following the script, one of the avatars shoots the real actor with what turns out to be a real bullet. Lots of irony and meta in the story. It’s worth a read even today. Especially today.

That novelette had some other interesting ideas. Like this one:

“Whatever you specialize in, another specialty will either gobble you up, or find a way to replace you. If you get what looks like a secure niche, somebody’ll come along and wall you up in it and write your epitaph on it. And the more specialized a society gets, the more dangerous it is for the pure specialist. You think an electronic engineer is any safer than an actor? ... You’ve always got one specialty that’s safe.... The specialty of creating new specialties. Continuously. Your own.”

And that’s more or less a definition of—but I’ll let you have your own view of what that’s a definition of. You don’t have to come up with the same answer that Miller offers in the novelette.

There’s one more detail about that novelette that Jim Cameron might want to bear in mind as he continues to re-engineer our cinematic experience. In Walter M. Miller’s vision of the avatarization of artists, it wasn’t just actors who got replaced. It was also directors.

Discuss this column with John and other readers in the magazine forum. -Mike

John Shade was born in Montreux, Switzerland on a cloudy day in 1962. Subsequent internment in a series of obscure institutions of ostensibly higher learning did nothing to brighten his outlook. He claims to be his own avatar.