Book Review: Programming Google App Engine by Dan Sanderson

Programming Google App EngineI’m certainly no expert on the Google App Engine (which is why I read this book), so after fiddling around with it for a couple of my iOS projects and struggling to decipher the documentation of some of the more complex parts of the Engine, I was glad to get my hands on this book. It’s not that the App Engine docs are that bad, in fact the Getting Started section was very helpful and did get me started very quickly, it’s just that they are clearly written as technical docs. I’m not your standard software developer, and sometimes I need things laid out nicely and fed to me on a big soup spoon. And Programming Google App Engine is my spoonish saviour.

The book is well organized, and is distinct from some other books I’ve read for it’s conciseness and lack of filler content. The code examples are very brief, yet each demonstrates clearly the concept being discussed, so there is not much code reading to do in this book. On the other hand, this is certainly no cookbook or even a guide to writing an app engine app. What it is, is a thorough walk-through of the App Engine’s features, with several useful explanations of some of the unexpected and subtle complexities that would likely ensnare an unwary developer. He also points out many areas where Google’s implementation differs from what one would expect coming from a relational database background.

Three full chapters are devoted to the datastore, Google’s big table implementation of a database backend. An additional related chapter is the Data Modelling for Python. Standout issues from these chapters were:

  • the explanation of how query speed is increased by storing indexes of all possible queries and their results,
  • multi-valued properties
  • the distinction between transactions and fetches
  • Entity Groups and ancestor relationships between Entities

These were all features I didn’t even know existed before I read the book, and my knowledge and understanding of them will go a long way to helping me write more sophisticated and powerful App Engine apps. The chapters on the Memory Cache and Task Queues were also particularly interesting and useful.

I should confess that my interest in the Google App Engine is purely from the perspective of the Python language, so I skipped all of the sections and chapters related to Java. It does seem that the App Engine has been designed with Python in mind and there are many features available for Python that are not yet available for users of Java, and the book reflects this in its seeming emphasis on Python.

Apparently, the book is already dated because the Google App Engine is being updated all the time, but that doesn’t bother me because the book and the documentation serve distinct roles. The book gives you a “story” of what all the pieces are and how they fit together. When I run into a situation where the book’s information is dated, then I’ll refer to the current documentation to get the more up-to-date details. I don’t think the fact that this book is *gasp* 15 months old should be a deterrent from picking it up.

I actually read the book through my subscription to the O’Reilly Safari Books Online site, but I think it will be such a valuable reference that I’ve just ordered a print copy – and I don’t kill trees very often these days, so that says something about the book!


Combining Blocks, Properties and Animation in Objective-C

Blocks are a recent addition to iOS and Mac development. It’s a C-level feature, and is available in the XCode tools in Snow Leopard and for iOS 4.0 and later. The support in UIKit and Foundation libraries is still a work in progress, but a lot of important Cocoa classes already offer support for this language feature.

I’m not going to explain all the details of blocks. The Apple documentation does a fair job of that already. Good resources are Block Programming Topics and A Short Practical Guide To Blocks. Instead of rehashing that stuff, I’d like to explore some ideas of how to use blocks in our Objective-C programs. Learning any new language feature is like getting a new hammer for Christmas: You start looking for nails. I’m still early in my search for nails to hit with this hammer, but the first thing I wanted to try was inspired by my very limited knowledge of the javascript language.

Javascript, and other languages, have the concept of closures, which is a powerful but often poorly understood concept, but it forms the basis for a lot of the really cool stuff that’s recently emerged in web development, like jQuery. Blocks are essentially closures for Objective-C. And I wondered if you could therefore start assigning anonymous bits of code (and the variables in their scope) to object properties in Objective-C. It turns out you can, and it’s awesome!

I will step through some code examples to show you what I mean. And I’ve posted the sample project that all this code comes from here: https://github.com/silromen/ObjectiveScript

This sample project, called ObjectiveScript, is pretty simple. There’s an image we can animate by tapping it. We can switch how the image animates by tapping one of three buttons: Rotate, Scale and Transform. Once a button is tapped, we tap the image and it performs the chosen type of animation.

There are two main classes: the ViewController and the View which contains the image we want to animate.

Let’s start with the animateable view, here called SpecialView:


//  SpecialView.h

#import
@interface SpecialView : UIView {
	void (^animation)(void);
}

@property (nonatomic, copy) void (^animation)(void);
@end

Look at that property declaration! It’s saying that this object has a property called animation that we can assign an arbitrary block of code to, which returns nothing and takes no arguments. This is different than declaring a method, because the code in a method has to be defined at compile time. With a block, we can assign any code we want to that property at run time.

Now let’s look at the source code for our SpecialView.


//  SpecialView.m

#import "SpecialView.h"

@implementation SpecialView
@synthesize animation;

- (void)dealloc {
    [super dealloc];
	[animation release];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	[UIView animateWithDuration:0.85
						  delay:0
						options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse
					 animations:self.animation
					 completion:^(BOOL finished){
						 self.transform = CGAffineTransformIdentity;
					 }];
}
@end

There’s not a lot of code, but there’s a lot going on here. We’re synthesizing and releasing our property – that’s normal. We’re overriding touchesEnded and defining an animation we want to occur whenever a touch event ends on this view. Now, in the old days (last year), without going deep into Core Animation Layers, you animated a view by defining some changes to the view you wanted animated and bookending those instructions with [UIView beginAnimations: context:] and [UIView commitAnimations], and if it pleased you, you could specify a selector to run when the animation completed. But since iOS 4.0, there’s a block-friendly way of doing exactly the same thing, and that’s what is happening in this code sample. We’re calling the class method animateWithDuration:delay:options:animations:completion:. The animations and completion parameters are accepting blocks of anonymous code. What’s really special in this example, is we’re passing the contents of our view’s animation property as the block to execute for the animation. The completion code is always going to be the same, which is to undo any transformation that the animation has performed on the view by setting the UIView transform property to the identity matrix. But the animation itself could be any chunk of code we assign that animation property to.

So let’s see how the ViewController puts that cool feature into use.


//  ObjectiveScriptViewController.h

#import
#import "SpecialView.h"

@interface ObjectiveScriptViewController : UIViewController {
	IBOutlet SpecialView *specialView;
	IBOutlet UIButton *rotateButton;
	IBOutlet UIButton *translateButton;
	IBOutlet UIButton *scaleButton;
}

- (IBAction)onRotate:(id)sender;
- (IBAction)onTranslate:(id)sender;
- (IBAction)onScale:(id)sender;
- (void)setSelected:(UIButton*)sender;
@end

In the header, we have our outlets for the special view and the buttons. We have our handlers which are called in response to the buttons being touched, and we have a helper method that will be used to make the three buttons behave like radio buttons, so only one is selected at a time.

 
//  ObjectiveScriptViewController.m

#import "ObjectiveScriptViewController.h"

@implementation ObjectiveScriptViewController

- (void)dealloc {
	[specialView release];
        [super dealloc];
}

- (IBAction)onRotate:(id)sender {
	specialView.animation = ^{
		 [UIView setAnimationRepeatCount:1.0];
		specialView.transform = CGAffineTransformRotate(CGAffineTransformIdentity, 135.0);
	};
	[self setSelected:(UIButton*)sender];
}

- (IBAction)onTranslate:(id)sender {
	specialView.animation = ^{
		 [UIView setAnimationRepeatCount:1.0];
		specialView.transform = CGAffineTransformMakeTranslation(-175, -175);
	};
	[self setSelected:(UIButton*)sender];
}

- (IBAction)onScale:(id)sender {
	specialView.animation = ^{
		 [UIView setAnimationRepeatCount:1.0];
		specialView.transform = CGAffineTransformMakeScale(0.1, 0.1);
	};
	[self setSelected:(UIButton*)sender];
}

- (void)setSelected:(UIButton*)sender {
	rotateButton.selected = ([sender isEqual:rotateButton]) ? YES : NO;
	translateButton.selected = ([sender isEqual:translateButton]) ? YES : NO;
	scaleButton.selected = ([sender isEqual:scaleButton]) ? YES : NO;
}
@end

Notice how each button’s handler method assigns a chunk of animation code to the SpecialView’s animation property. Tapping these buttons doesn’t execute the animation, but they tell the view which animations to perform by feeding it the code to execute.

The combination of blocks, properties and core animation is powerful, and this example is just scratching the surface. This gives developers another way to conceptualize and organize their code, and having more options is always a good thing.


Mixing PopoverControllers with ModalViewControllers

When building an app on the iPad, sometimes you need to display a Popover, and tapping a button on that Popover will launch a Modal View. When you’re done with the Modal View, it flies away (gotta love those animations), and you’re back to the Popover.

This doesn’t seem like a stretch, but if you’re not careful in how you do it, iOS has some nasty surprises in store for you.

So here’s what you’re trying to accomplish:

Let’s take a first attempt at the code for this:

@implementation ModalPlusPopoverViewController
...
// When the Go Button is pressed, we create a view controller, embed it in a popover controller and present it.
- (IBAction)goPressed:(id)sender {
	MyViewController *theViewController = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil] autorelease];
	UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:theViewController];
	[popoverController setPopoverContentSize:CGSizeMake(400, 400) animated:NO];
	[popoverController presentPopoverFromBarButtonItem:(UIBarButtonItem *)sender
						     permittedArrowDirections:UIPopoverArrowDirectionUp
									       animated:YES];

}
@end
@implementation MyViewController
...
// Inside the popover, when the "Launch Modal" button is pressed, we create our modal view controller and present it
- (IBAction)launchModal:(id)sender {
	MyModalViewController *theModalViewController = [[[MyModalViewController alloc] initWithNibName:@"MyModalViewController" bundle:nil] autorelease];
	theModalViewController.modalPresentationStyle = UIModalPresentationFormSheet;
	[self presentModalViewController:theModalViewController animated:YES];
}
@end
@implementation MyModalViewController
...
// To dismiss the modal, the user taps the Dismiss button, and we dismiss ourselves
- (IBAction)onDismiss:(id)sender {
	[self.parentViewController dismissModalViewControllerAnimated:YES];
}
@end

With this code, everything seems to work well at first glance. When you tap Launch Modal, the modal view slides up from the bottom, and when you tap Dismiss, it slides down again.

But now rotate the iPad and try again. This time, the Modal view slides up from the bottom, but when you dismiss it, it flies out to the left!

And it gets worse. If your modal view happens to be a MFMailComposeViewController, which is a handy class to make it easy for users to send email directly from your app, when you try to dismiss it, it actually causes your app to rotate, even though the iPad is still in landscape orientation.

So what’s going on here?

When you launch and dismiss a modal view from a popover, iOS is doing some strange things under the hood. If you put a breakpoint on shouldAutoRotateToInterfaceOrientation in your popover view controller, you’ll find it gets called when you launch and dismiss the modal. If you examine the call stack you’ll see this call:
[UIViewController _preferredInterfaceOrientationGivenCurrentOrientation:]
So there’s some calculation going on under the hood that’s making an orientation decision. When your modal view is MFMailComposeViewController and you dismiss it, you actually get the wrong orientation passed to shouldAutoRotateToInterfaceOrientation: you get UIInterfaceOrientationPortrait when what you’re expecting is UIInterfaceOrientationLandscapeRight. And this is why your iPad display rotates. And I suspect some similar behaviour is causing the modal view to slide out in the wrong direction.

So how do we fix this?

It turns out our mistake is launching the modal view from the popover. It’s this call from the MyViewController class:
[self presentModalViewController:theModalViewController animated:YES];
Here, self refers to the MyViewController class, which is embedded in a Popover. What we need to do is launch the modal view from the underlying view controller, the one that launched the popover view. In our example, that’s ModalPlusPopoverViewController. The problem is the view controller in the popover has no reference to the underlying controller, so we need to add code for that. Our fixed code looks like this:

@implementation ModalPlusPopoverViewController
...
- (IBAction)goPressed:(id)sender {
	MyViewController *theViewController = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil] autorelease];
       // We now tell the view controller we're embedding in the popover that it should launch modal views from this view controller
	theViewController.baseViewController = self;
	UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:theViewController];
	[popoverController setPopoverContentSize:CGSizeMake(400, 400) animated:NO];
	[popoverController presentPopoverFromBarButtonItem:(UIBarButtonItem *)sender
							  permittedArrowDirections:UIPopoverArrowDirectionUp
											  animated:YES];

}
@end
@implementation MyViewController
@synthesize baseViewController;
...
- (IBAction)launchModal:(id)sender {
	MyModalViewController *theModalViewController = [[[MyModalViewController alloc] initWithNibName:@"MyModalViewController" bundle:nil] autorelease];
	theModalViewController.modalPresentationStyle = UIModalPresentationFormSheet;
	[baseViewController presentModalViewController:theModalViewController animated:YES];
}
@end

I’ve omitted the header file code here, but it should be clear what the header files contain based on the source. Now our modal view behaves as expected when we dismiss it. And if we’re presenting a MFMailComposeViewController, it doesn’t auto-rotate the app behind our backs.

The moral of this story is to be careful which objects you launch your modal views from, especially when you’re launching them from Popovers.


The Problem With Free

There is a bit of a religious war going on between those who think app development should be happening with open web technologies (HTML, Javascript, CSS) and those who prefer to develop less-open apps using native technologies, like CocoaTouch for the iPhone. As an idealist who fantasizes about a perfect socialist world where everything is free and people work on what interests them, rather than what will earn them a paycheque (because everything is free), I have a lot of sympathy for the free argument. But there’s a problem. I am an independent software developer, and I need to get paid. Sadly, I live in the real world, where nothing is free.

I recently published an iPhone app that is a user-friendly wrapper around the Ottawa transit schedule website. I’d like to use that as a concrete example in this somewhat philosophical argument. In thinking of a project like this, there are some fundamental, even philosophical, design decisions that need to be addressed. There are four major paths to consider here for what such an app will look like:

  1. Free web-based app
  2. Paid web-based app
  3. Free native app (iPhone, blackberry, etc)
  4. Paid native app

The argument for the free web-based app is a strong one. It is free to use. Everyone loves free. It’s standards based. That’s huge. Anyone with a web browser can use it, including iPhone, etc. On the iPhone, you can add web bookmarks to your home screen, so a well designed web app will be nearly indistinguishable from a native app. Plus, it will work on any other device, as opposed to a native iPhone app, which will clearly only work on, well, iPhone. The downside is, of course, that it’s free. As the developer, you don’t get paid. Now you can get creative, and host advertising, or sell merchandise, blah, blah, blah. But the bottom line is, people use the app for free. You’re only going to make money those other ways by having many, many users.

Now you could make the same app, but make it a paid web-app. And then nobody will use it. Because people don’t pay for stuff on the web. And they’re certainly not going to pay for a web app that gives them the same information they could get elsewhere for free (which would be the case for a transit schedule app). One reason I ultimately side with the native app camp is that people don’t pay for web sites. If you build a web app, most people won’t pay for it. Convert that app to the iPhone and put it up on the app store, and magically, people will start paying. That’s just the way it is.

Now we come to the native apps, and we’ll start with the category I have the hardest time understanding: The free native app. I’m not talking about free apps that are part of something bigger, like the CBC Radio app, or the CTVOlympics app. No, those apps have to be free. Let’s stay close to the original example here, so we’re not comparing apples to oranges. Take, for example, a free transit app. Why would you do that? People will gladly shell out 99 cents to buy an app – not even a useful app. They’ll spend money on a Truth or Dare app, or an app with pictures of bikini-clad women. Why do they spend money on this crap, when they can get it all for free on the web? I don’t know why, but they do.

So why are developers putting the time and effort into writing useful apps (both web-based and native) and then giving them away for free? One argument is that they want the renown and glory of writing a cool app that has a lot of users, with the benefit of their software becoming their de facto job resume. But think about it. 99 cents is practically free. Take the transit example. In Otttawa, it now costs at least $2.50 to take a ride on the bus. So paying 99 cents for something useful and non-consumable, is a bargain. Plus, the developer gets paid. You are only paid 70 cents once Steve Jobs gets his, but that’s 70 cents all the fame and glory from the free app won’t get you. Now consider, if only 2000 people buy your very reasonably priced app, you’ve made $1400. Now write 10 of those relatively easy to produce, but still useful and well-priced apps. Maybe even charge more than 99 cents for some of them. Now you’re making thousands of dollars. Now you’ve got an income. Now you don’t need a resume, because you’ve already got a job. You’re making money writing software. Isn’t that what you want to do? And guess what, you own your software. Your buddy who gives away his work, has to spend his days writing bank database software to earn a living, so he can go home and do what really interests him in his spare time. But the work he really values, he gives away, so he can boost his ego, and he can buff his resume so he’ll get a job doing work he doesn’t really want to do.

Writing good software and then giving it away ultimately devalues the work developers do. Prices for apps on the Apple App Store are ridiculously low because developers undervalue the work they do, and even worse, a huge portion of those apps are free. New marketing avenues for software, like the App Store, are a game changer for independent software developers. You can earn an income focusing on what you do best without having to worry about retail channels and manufacturing CDs and online payment gateways. You just write software and sell it. So don’t throw the opportunity away by giving the software away.

If you could package a web app and list it on the App Store, then I might join the web-based camp, but I won’t join the free camp, because the work I do is worth something, and I want to work on what interests me, I want to own what I create, and I want to get paid for it.


Anchor’s Aweigh – For TransitWay

January 20, 2010. The day I finished the first application of my independent software development career. Shipping code doesn’t come along very often – a few times per year at most, so when it happens it’s a big deal. And because of my extended sabbatical, the last time I shipped software was in 2006 – a lifetime ago in the internet age. That was was in the year -1 B.iP. (Before iPhone).

Fast forward to year 3 A.iP. and today I submitted my first app, TransitWay, to the App Store. Everything about this project was engineered to be small, simple and relatively quick, so I could experience the entire software development cycle in a short timeframe (less than 3 months). The app is small. The feature set is small. The market is small. The development cost (in time and money) is small.

My previous development experience was completed within the comfortable confines of a well organized, successful company with full-fledged software, QA, and marketing departments. There was always somebody within 100 metres who knew more than I did about some topic critical to the success of our product, development-related or not. When you start developing software on your own, you get what you ask for: you are on your own. You have to wear many hats, sometimes at the same time. And in order to ever hope to make money, you need to be focused on shipping software. That means knowing your strengths and weaknesses, and choosing a project small enough to complete in a reasonable amount of time, and that supports your enterprise in its current state. The current state of my enterprise is that I’m alone, I’m slightly nervous about what I’m capable of doing with just my ideas, my laptop and my internet connection. So I chose to build a piece of software that I knew there was a need for (because I needed it), and that seemed ridiculously simple, too simple to be a proper project. That turned out to be a fantastic decision. And that ridiculously simple project? It took me nearly 3 months of part-time development time to complete and polish, certainly longer than I had planned, but still a quick turnaround for shippable software.

While I physically work alone, with nothing more than Google and Stack Overflow for co-workers (oh, and the Hannibal Lector action figure on my desk), I have made a conscious effort to grow my professional network. So far, I have joined three local groups in Ottawa: a local Mac User Group, the local chapter of CocoaHeads and its splinter NSCoder group. These groups are critical to my success, because as much as I would love to do everything myself, I can’t, and I have so much to learn from these people. I’ve already found two graphic designers – one who did the TransitWay logo for me, and learned countless life-saving tips from the people I’ve met through my network. These groups are also a potential starting point for drumming up word-of-mouth advertising for my projects.

As I wait for Apple Corp. to pass judgement on my app, I’m taking a breather to reflect on my progress, and to contemplate my future. If my submission is rejected, I’ll be stuck working on TransitWay for a little while longer, but beyond that, I have at least three potential projects on my plate. One is an iPhone game. One is TransitWay 2.0. One is to complete the recipe and meal planning project I started over a year ago, with both desktop and iPhone components. Which ever project I choose, it will certainly involve a whole whack of new learning, and hopefully I can build on the experience I’ve gained from completing the TransitWay iPhone app.


Book Review: Programming the iPhone User Experience by Toby Boudreaux

The title of this book offers a hint to the duality of information it offers. It tries to be both a programming book and a User Experience book, focused exclusively on the iPhone, and squeezed into a mere 165 pages. I think the book would have been more effective had it chosen one of these topics to focus on, but on many levels it still registers as a successful text which adds value to any iPhone developer.

I actually read this book twice: once when I first started out with iPhone development, and again nearly two months later, once I had a degree of comfort with the iPhone. Those were two completely different experiences. I would recommend waiting until you’re well into your first iPhone app before you read this book. There will still be time to fix any horrible user experience gaffes you have committed, and you’ll find the detailed code examples much more useful.

For the novice iPhone developer, the book hits you hard with a combination of information that is either too detailed to be of use now, or so basic, it doesn’t seem worth including in the book. There are detailed code examples of handling multi-touch swipes, and several pages earlier, there are diagrams with long lists of Cocoa class hierarchies. Neither of these were what I was expecting from a User Experience book, and neither were helpful in guiding me in crafting a good user experience for my first iPhone app.

More useful from the beginning were the discussions of Cooperative Single-Tasking (Chapter 5), Progressive Enhancement (Chapter 8 ) and UX Anti-Patterns (Chapter 9). These were filled with useful User Experience (UX) suggestions that could be applied right away to designing an iPhone app. Chapter 9 on anti-patterns is a particularly useful walk through an iPhone Hall of Shame, with some useful explanations of why these practices are wrong, and suggestions for what can be done instead.

Once I had more experience under my belt, both the Touch Patterns (Chapter 6) and the Interaction Patterns and Controls (Chapter 7) chapters with all their code examples were more useful. They play out like a reference text for adding features to your app. You want to make a custom scroller? There’s a code example for that. I even found the first three chapters more useful once I had experience with creating an iPhone app. These introductory chapters are often criticized for being fluff or filler, but they actually work as a useful checklist for your app, especially as it relates to the Mobile Human Interface Guidelines (HIG). Is it an Immersive Application or a Light Utility? Is it following the Mobile HIG guidelines for its class of app?

Programming the iPhone User Experience is a good iPhone book. Read it through once, absorb some UX do’s and dont’s, skip the detailed code examples that don’t apply to you now, and then come back to them later when you need them.


Disclaimer: I had a free copy of this book to review, which my Cocoaheads development user group received from O’Reilly to read and review.


DevDays Conference De-Briefing

I attended the DevDays conference in Toronto on October 23. I’m only writing about it now. I know.

I drove down with two others Ottawa CocoaHeads and we stayed at the passable Downtowner Hostel, in the gay district. The night we got there, we decided not to stop in for a drink at the bar called Zippers. When we got back, there was a cockroach on Phil’s backpack. But it was cheap!

The Conference

This was a low-cost one-day affair with a list of speakers covering a wide array of technologies. Unfortunately for me, a lot of it was web-focused: Python, ASP.NET MVC, Ruby, jQuery for example. Most of it was interesting though, and did encourage me to finally pick up that Python book, and throw some jQuery around the next time I need to build a cool web site – which will be as soon as I’m done writing my first software project.

A highlight of the day was the one and only Joel Spolsky. He was a great presenter with an important message about software developers thrusting too many decisions on end users and then patting themselves on the back for giving their users so many options. He backed it up with some interesting anecdotes and facts. He also came back and talked a bit about FogBugz, his company’s solid project management software. I last used FogBugz in 2006 when I think it was still mostly about bug tracking.

The other highlight for me Greg Wilson, a prof from the U of  T. He preached that developers need to use evidence based practices in their work. So, that means, not doing something because that’s how it’s always been done. Do it because you can point to scientific evidence (yes, studies) that prove it is the best way to do something. I can’t do him justice, so here’s the link to his slides: http://www.slideshare.net/gvwilson/bits-of-evidence-2338367 Like Spolsky, Wilson had a great presence on stage and his talk was engaging.

Conclusion

I wasn’t really excited about what I got out of the conference. It’s hard to know what you’ve learned when it’s not technical, and much of the talks weren’t very technical, and those that were, were mostly over my head. But it’s interesting that what I did enjoy most were the least technical talks. Those are what I walked away from feeling like I’d learned something. I know this all sounds contradictory. Such is life.

Will I go back next year? I think so. I’ll have been doing this for a year (hopefully) and should be in a very different place technically – and hopefully financially? And I may get more out of it with a different perspective. I have signed up for FogBugz on Demand, and I’m looking forward to getting started with that soon.