Outer-Dialogue

May 29, 2009

Overcome indentation in your init methods.

Filed under: Development — mbtyke @ 5:54 am

I really like the ideas in the Seven Pillars of Pretty Code paper at Perforce Software, especially the “Overcome Indentation” section. I try to keep my code as far to the left as is reasonable.

For instance:

if ( thing != NULL  )
{
    thing->doSomething();
    thing->doSomethingElse();
    thing->doSomethingMore();
}

… can become …

if ( !thing  )
    return;

thing->doSomething();
thing->doSomethingElse();
thing->doSomethingMore();

… and …

if (value == otherValue)
{
    thing->doSomething();
}
else
{
    thing->doSomethingElse();
}

… can become …

if (value == otherValue)
{
    thing->doSomething();
    return;
}

thing->doSomethingElse();

This is why I cringe when I see this in Apple’s tutorial documentation:

-(id)init
{
    self = [super init];
    if (self != nil) {
        // initialization code
    } else {
        return nil;
    }
    return self;
}

With this, I get to write my entire init method in two levels of indentation just so I can happily execute one return statement after the end paren.

This is also in some of XCode’s class templates, and in many cocoa books that I see. I wish they would update it to this. It looks far calmer to me.

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

    // initialization code

    return self;
}

I realize this is a small thing, but after looking over page after page of highly indented code, I get a little fatigued. I’ve really grown accustomed to tackling the small cases first so the meat of the method is at the end.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.