Objective-C Indentation Styles

Discussions with developers about their preferred indentation style often seems to stir the same passion as one’s preference for beer, wine or cocktails.

This post isn’t as much a tip or trick, as it is an opportunity for developers to share their variations and preferences when it comes to indenting code. Let me give you a quick run-down of how my Objective-C code typically looks. As you’ll see, if nothing else, I am consistent…

Functions/Methods

I like my braces on a line by themselves:

- (void) loginAttemptComplete:(id)results
{
  ...
}

This is consistent across all of my code, for example, here is how an interface definitions may look:

@interface LoginViewController : UIViewController
{
  ...
}

As far as parameters, I like to keep them on the same line:

int main(int argc, char *argv[])
{
  ...
}

Versus this:

int main(argc, argv)
         int   argc;
         char  *argv[];
{
  ...
}

If the list gets lengthy, I will wrap and indent:

- (void)searchBar:(UISearchBar *)searchBar selectedScope:(NSInteger)selectedScope didChange:(BOOL)didChange
                  top:(BOOL)top                  
                  color:(UIColor)color
{
  ...
}
Calling Functions/Methods

Again, I like to keep everything on one line when possible, this includes calling a function or method. I am generally okay if my lines extend past 80 characters given the expansive screen resolutions available on most machines:

[someObj: searchPrefs:(UISearchPrefs *)searchPrefs selectedScope:(NSInteger)selectedScope didChange:(BOOL)didChange];

However, I do have my limits on what is reasonable to squeeze onto one line;

[self showQuestionAndAnswer:[[[SharedData sharedModel] attributes] answerID]
                               questionID:[[[SharedData sharedModel] attributes] questionID]
                               filterID: [[[SharedData sharedModel] attributes] filerID]];
If else/if, while, for

Here is how I like to setup my if/else statements:

if (!returnData)
{
  ...
}
else
{
  ...
}

Also, I don’t include braces if the code does not require them:

if ([searchObj noSearchData])
  searchFlag = RESET;
else
  searchFlag = UPDATE;

My if/else statements look as follows, where the else if are on the same line:

if (!returnData)
{
  ...
}
else if ([httpResponse statusCode] != HTTP_OK)
{
  ...
}

As with the above, when I write while and for loops, braces stand alone:

while ([obj currentCharacter] != '?')
{
  ...
}
for (NSDictionary *dict in dataList)
{
  ...
}
Tab Stops

I prefer to indent two spaces, and always opt for space characters over tabs. For those who use tabs, is there a primary benefit of tabs that makes you choose one over the other?

Posting a Comment with Code

Please feel free to post code examples of your style. If you would like to post a comment and have your code color highlighted as shown above, using the following format:

<pre lang=”objc”>
your code here
</pre>

29 Comments

  1. I like everything you do except I still use braces for single if (and else) statements, and four spaces per tab.

  2. For my part I always use tabs rather than spaces, combined with the listchars option in vi. It gives this kind of outline:

    if (test) {[do something];
    │   [do somethingElse];
    }

    That’s also why I don’t put opening braces on a newline, it’s not required with this setup.

  3. I prefer the opening bracket to be in the same line as statement that requires bracketed block. This way the code looks cleaner when all the methods or code branches are collapsed.

  4. I agree on everything, as purely stylistic.
    However, I always add the braces in if/else statement for two reasons:

    1) When I have to add a new line code, the branch is already insert:

    if (!returnData)
      object.property = 5; // You have to insert a branch
      return 0;
    else
      return 1;
    

    2) Cases as this:

    if (!returnData)
      return 0;
    else
      return 1;
    

    Could be write as:

    return (!returnData) ? 0 : 1; 
    

    Thanks for suggestions

  5. I’m with you on everything except for the point Giovambattista Fazioli makes — if I have a single statement for an if or else, I use braces, unless it’s easily and coherently written as a ternary. I have seen code blow up too many times when an extra statement got inserted unthinkingly between the if and the contingent statement.

    Eimantas — do you really collapse code all that often? It’s one of those things that sounds useful, but if you keep your classes / files small enough, there isn’t much need for it. And with Xcode, you can always navigate to the declaration you want pretty quickly even if it’s not visible on the page.

  6. I definitlty don’t do this : “Also, I don’t include braces if the code does not require them:” because it’s bug prone. Sometimes, you add a NSLog () in your else statement and then you realize it wasn’t in the else scope (after spending hours of not understanding what is happening).

    If I don’t put braces, I keep the code on the same line, so it is more obvious that there is no braces.

    • Karl, you should get an award for this response.

      With respect to coding style, I’ve seen too many variations to care about whether or not someone agrees 96% or 98% with the blog post; we all have our own opinions, there is no “right” answer. The most important aspect of coding style, IMHO, is consistency; this is where we really make code more (or less) legible.

      So, whereas most people of commented on their particular take on a good blog post, this comment addresses the issue of making use of the coding style: something that is sadly lacking in practice when developing in Cocoa (too few usable tools).

      I’ve looked at uncrustify before but never quite had the time to get it working; guess it’s time to take another look.

  7. It’s so rare when I find someone who codes the exact same way that I do! Most the time people code where open braces are placed on the same line with code:
    If (test) {
    do something;
    } else {
    do something else;
    }

    That is so much harder to read than the way “we” do braces. Sure there are more lines of text on the screen. However, it helps block the code out into intelligible chunks.

    I don’t know if there is a name for the style we use, but in my lowly opinion, it is really the only way to write code! ;)

  8. My first goal is to make my code readable, and I have revised some of my rules to adhere to this goal.

    Generally, I don’t mind where brackets are, but I really do care that the code is consistant.

    As for braces, and brackets, I put spaces between the braces, since it makes the code much easier to read. i.e.:

    while( firstVariable < secondVariable ) {
    ….
    }

    "while" is a key word, so it should be highlighted, plus, we all know the word( same with "if", "else", etc ). The variables between the braces are unique, so I do my best to make it stand out. The spaces between the braces and variables is something I picked up a couple of years ago at an old job, and it has stuck with me ever since.

  9. Also like code like you do and it irks me that xcode has no form of autoformatting, that have been part of other ides for years!

  10. I use the same style except I put braces on all my if statements. I wish people discussed how they comment their codes. I used to use //comment and then I switched to /*comment*/

    • Good call on the comment idea, I had the same thought when I was writing this post. I’ll post something in the next week or two…

    • I’m partial to using /* */ for multiline comments:

      /*
      * Start of a multi-line comment
      * Where I have a lot to say
      * About what’s going on
      */

      // Just making a note about something here

  11. My preferred style is opening brace on a new line. However Apple seem to be pushing for brace at end of line. This is especially noticeable when using blocks.

  12. I’m with everyone here who uses braces on all IF statements. I have experienced bugs caused by the inserting a new line on a IF statement that had no braces due to having only one line inside of it.

  13. Hey John,

    I always use tabs to indent code – image at the beginning of a line which is 3rd level indentation – if you use 2 spaces per indent that’s 6 strokes of the right arrow key to get to the beginning of the code, with tabs is just 3 – efficiency above all :)

    I always use also brackets for one line if blocks – I never know when I’ll need to add just an NSLog or something else inside and it’ll take me more time to figure out the code and where to put the brackets later on.

    Marin

  14. I have to say I differ on most of your style. I come from a Java background where these things have been thrashed about for years and still no-one fully agrees, but here’s my personal style:

    1. Open brackets occur on the same line as ‘if’, ‘for’ etc. Reason: Helps to keep methods visibly short.

    2. I indent with tabs. Reason: Allows developers in a team to have tab widths set to what they like without effecting layout. Second, is faster to cursor over.

    3. I always use brackets. Reason: Considered a good practice by Java developers because it minimises the chances of bugs being added when a developer adds a line to an if or loop. With brackets optional, it’s too easy to introduce a bug.

    4. I use 3 spaces per tab for indenting. I’ve tried 2 and 4, and found 3 to me about right for me.

    5. Comments are important. Contrary to some Java code ‘gurus’ they provide context that no amount of method and variable naming can.

    Derek

  15. This has been an on-going debate since I can remember.

    Personally I have used the same style almost since I began software development.

    method(parms)
    {
    variable names
     
     lines of code   indented 1 space from {
     
     if (something)
        {
        more code
        more code
        }
     else
        {
        more code
        more code
        }
     
    }

    I have always indented (spaces not tabs) my { as it makes reading the code much easier and it makes the code look prettier (LOL).

    Thanks for all your great information

  16. 3. I always use brackets. Reason: Considered a good practice by Java developers because it minimises the chances of bugs being added when a developer adds a line to an if or loop. With brackets optional, it’s too easy to introduce a bug.

    +1, hes completely right. Its not a matter of preference, its a matter of practice.

  17. “For those who use tabs, is there a primary benefit of tabs that makes you choose one over the other?”

    Tabs are the more semantically correct option, as one tab character means (and always represents) one indention. By adhering to this convention, you allow developers to view the code at whatever indent size they prefer using their editor’s settings.

  18. I never use new lines for the braces, and always use braces for all arguments, even if you don’t need to. I use the first line of functions for comments. Using tabs like python also keeps extended / heavily nested “if logic” easy to read. As a rule, I’ll format it with tabs and spaces before I “leave”, just in case I don’t come back for a year!

    -(void)functionx{
    //description of function here..
    
    If(){
    //do something 
    }else{
    //another thing..
    }
    
    While(){
    ...
    }
    
    }//end function
    
  19. I follow identical formatting as you with the exception of not including braces on single line if / else statements because a) I rarely have those and b) I’ll probably need to add a second line at some point anyway so might as well put them in to save me time now and keep my formatting consistent.

    I use tabs instead of 2 or 4 spaces for a few reasons:

    1. We no longer have the character encoding issues we once had when moving files between platforms. So there is no reason NOT to use tabs.
    2. Faster code navigation. I find my ability to navigate between lines / tabs and re-format code is drastically slowed when I have to press arrow key for each space rather than once for the tab.
    3. If someone else likes indents at 2 spaces (or some other odd number), using tabs allows you to share code while maintaining the indentation appearance you are accustomed to.

  20. It doesn’t matter stay open brace at the end of line or in a new one. First i always put open brace in a new line. But now I put in at the end. It’s spoil reading but code is shorter and you may see a more lines at one page.

  21. Putting braces on their own line allows you to treat the entire section of code as a block, irrespective of whether the block is a class, method, if, for, while, try statement, or otherwise… when moving the block to another location in code, you don’t need to worry about scope because the entire block is preserved in context. In many cases you can just drag it a new location in the code without editing.

    This also brings up the variety of different editors both GUI-based and command-line. On many editors it is possible to select an entire line by triple-clicking — selecting more lines by dragging. Adding, removing, or reorganizing code in a block is possible without constantly fiddling with the location of brackets because they stay completely out of the way. If you need to change the expression for the block, you are unlikely to accidentally delete the bracket. And even if you do accidentally delete the bracket, the defect will be visually obvious and consistant.

    Tabs should ONLY be used at the beginning of a line, and should be used without spaces. Why? Because everyone has different ideas about how big a tab should be and should look like in their own editors. Whether you use vi or Eclipse, code with only tabs at the beginning of a line will ALWAYS format properly to the user’s preferences.

    Want tabs later in the line? Don’t do it. Don’t bother trying to line things up in the middle of a line because somebody somewhere will surely never benefit from your aesthetic sensibility due to their personal views regarding tab-size.

    Putting a // comment at the end of a line? Just put a space before it and you’re good.

Comments are closed.