Steven Jewel Blog RSS Feed

14 Apr 2014

Modal Programming

I've stumbled upon a technique for programming that has helped me be more productive. Essentially, you switch between two modes while writing new code. First, you write the entire program, but you don't try and write it correctly. Instead, you focus on the structure of the program. Don't look up any APIs during this phase, or do any research at all. Instead, just pretend like you know what the API calls are going to look like.

As a simple example, if I were writing a program that would send a tweet whenever a website's content had changed, I might write something like this first:

require 'twitter'
prev = nil
loop do
  page_content = Net::HTTP.get "http://paulgraham.com/essays"
  prev ||= page_content

  if page_content != prev
    twitter = Twitter.login ENV['username'], ENV['password']
    twitter.tweet prev
  end

  prev = page_content
  sleep 60 * 60 # one hour
end

As I was writing the code above, I resisted the urge to research which was the best "gem" (ruby library) to use, what its API was, and even what the proper URL was for the site. Even when the amount of code to be written is longer, I'd still write out as much of it as I could. It's fast to write because you don't have to worry about looking things up. I wouldn't even worry about syntax issues if the language is new to you.

The second step is to make it work. . For the first step it's important to minimize distractions and get in the zone, but for the second step a lot less concentration is necessary. This is more than just normal debugging, since you might have to fix up some things that are obviously broken, but it's a similar process. Your unit tests or integration test will guide you to the parts of the code that don't work yet, and you'll only need to focus on a few small details at a time.

I won't actually go through this exercise for the example code above, but the first error I'd encounter is that I don't have a library named twitter, so now I'd be off to find a twitter gem that could do what I needed.

Conclusion

By consciously adopting this approach, I've found that the total time it takes me to create a program has been reduced. There's also a lot less that I need to keep in my head at any one time, since I don't sweat the details until absolutely necessary.

Comments or corrections to blogcomments@ this domain.