Thoughts on formatting blocks

When I first started writing serious Objective-C code in 2005, I had the benefit of a stern taskmaster in Aaron Hillegas of the Big Nerd Ranch, on proper style. He read us a list of standards to follow, such as class methods always appear before instance ones, that all braces for methods and ivar wrappers appear as the first character of a line (well I think that’s what he said). In addition, this is the proper method syntax:

- (NSString *)foo:(SomeClass *)name;

The ‘-‘ or ‘+’ the first character, a space, the type, the name, no spaces between the ‘:’ and the next character, etc as you can see.

With blocks, well, I never saw a style I liked in sample code, and the sample code is all over the place in terms of styles. After a few months I’ve settled down to an uncommon style (which I hope to make less common by publicizing it!):

[dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *obj, BOOL *stop))
    {
        ... the code
    } ];

Using this style makes it very easy to spot the blocks in code, and also to visually identify where blocks are when you quickly scan a big file.

To my eye, putting the braces directly under the ‘[‘ makes it look too much like a simple C block unconnected to the line above.

Note that I’ve changed the id key and id obj to specific types. I totally forget where I picked this up – I may in fact have just tried to use it and found it would work. It sure saves me a lot of time in created a second object casted to the id value or using one or more casts within an expression.

When I assign a block variable, it gets a bit more tricky, but this is what I do for multi-line blocks:

dispatch_block_t b = ^{
                          ... code
                      };

I’ve really gotten to like this style, now with my strong opinions on C, Objective-C, and blocks styles I’m afraid I’ll never be able to integrate into a coding group that has already written a style guide. YMMV

Advertisements

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 )

Google+ photo

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

Connecting to %s