Left is Right

In a 2005 Pimp My Code post, Wil Shipley challenged the Objective-C idiom for class instantiation. The traditional method is something like this:

- (id)init
{
  if ((self = [super init])) {
    // Success!
    // Initialize your ivars, etc.
  }
  return self;
}

For a number of reasons, Wil pushed a different idiom:

- (id)init
{
  if (! (self = [super init]))
    return nil;

  // Success!
  // Initialize your ivars, etc.

  return self;
}

This felt strange to me until I realized that it looks an awful lot like other conditional blocks of code I’ve written. Take this snippet from my MailQueue project, for example:

public function addMailRecipient($mailRecipient)
{
  if (! is_a($mailRecipient, 'MailRecipient'))
    // Failure: Improper type
    return FALSE;

  if ($this->addressExists($mailRecipient->address()))
    // Failure: email address is already on the recipient list
    return FALSE;

  // Success: Add recipient to recipient list
  $this->_list[] = $mailRecipient;
  return TRUE;
}

What this function and Wil’s constructor idiom have in common is that the normal flow of control follows the left margin of the code. This is one of those little things that makes a HUGE difference when you’re writing a project of any non-trivial size (or when you’re working on multiple projects at once in multiple languages.) Try to write your code so that your conditionals test for failures instead of successes. This enables anyone who reads your code (including you!) to more easily follow along.

This entry was posted in development and tagged , , , . Bookmark the permalink.

Comments are closed.