How do you indent your code?

Talking about indentation styles is like talking about religion. Everyone thinks there is only one true way to indent code, and everyone else is wrong. But let’s do it anyway. I want to know if my readers are “doing it rite“.

Personally, I use the BSD/Allman style:

if(a==b)
{
	// do something
	foo();
}
else
{
	// do something else
	bar();
}

I find that it produces very clear and readable code. Braces align with each other – for every open brace, there should be a closed brace on the same indentation level. This makes it easy to identify blocks of code. I like the extra white space created by placing the opening brace on a line of it’s own.

The other extremely popular style seems to be K&R:

if(a==b) {
	// do something
	foo();
}
else { 
	// do something else
	bar();
}

I fucking, hate, hate, hate this one. I always feel compelled to fix it by putting a newline before each opening brace. It just looks ugly and does not contribute to code readability. In BSD/Allman, an empty line with the opening brace is very visible cue letting you know that a code block has been opened. It’s hard to miss it – even if you are just skimming through the code. And even if the indentation gets messed up in some deeply nested statements, you can easily figure out what belongs where by simply counting braces.

In K&R counting braces is not that easy – especially if the opening statement is really long and the left brace either drops off the right edge of the screen, or word-wraps around messing up your indentation.

So, which way do you indent your code? Or perhaps you use another style not mentioned here? I know there are bunch of other ones like BSD/KNF, Whitesmiths, GNU, Banner style and etc. But they are all pretty much variations on the two styles above. For example the GNU style is like BSD/Allman but you indent the opening and closing brace by 2 spaces. Go figure.

Anyway, feel free to disagree with whatever I said here, and defend your favorite indentation style. I also dare everyone who uses one of the oddball styles (ie, not BSD/Allman or K&R) to stand up and represent. :mrgreen:

[tags]indentation styles, coding styles, bsd/allman, k&r, coding, code readability[/tags]

This entry was posted in Uncategorized. Bookmark the permalink.



28 Responses to How do you indent your code?

  1. Cocoa Crusty UNITED STATES Mozilla Firefox Windows says:

    I use a variation of the BSD/Allman style. Something like this:

    if ( $i == 1 )
    {
      // Do Stuff
      $j = $i;
    }

    It works for me. And I agree with you, the second style (K&R) is hard to read.

    Cocoa

    Reply  |  Quote
  2. Cocoa Crusty UNITED STATES Mozilla Firefox Windows says:

    Sorry about the ... stuff… It didn’t really work out how I wanted. Take care!

    Cocoa

    Reply  |  Quote
  3. hdw UNITED STATES Mozilla Firefox Windows says:

    I hate it most when no standard is chosen. Random coding. I feel obligated to fix the code one way or another. Pick a standard, any standard!

    Reply  |  Quote
  4. Miloš UNITED STATES Mozilla Firefox Windows says:

    BSD/Allman all the way…when I used to code a lot that is :)

    Reply  |  Quote
  5. Luke UNITED STATES Mozilla Firefox Ubuntu Linux says:

    Cocoa – no worries. I fixed it up a little bit. Is that how it was supposed to look?

    hdw – good point. It can get really confusing when the code shifts from one style to another without any rhyme or reason.

    Miloš – btw, I think most instructors at MSU generally prefer BSD/Allman. Most of the K&R stuff I have seen on campus was produced by the students with C/C++ backgrounds.

    Reply  |  Quote
  6. Rob UNITED KINGDOM Safari Mac OS says:

    What browser actually renders this HTML code correctly? The <code> element does not respect whitespace in the way you seem to think it should.

    (And, of course, you’re pretending to use XHTML, but you’re serving as text/html, which will cause all browsers to treat it as tag soup, and you’ve got loads of XHTML bugs, anyway.)

    Reply  |  Quote
  7. Rob UNITED KINGDOM Safari Mac OS says:

    Nice comment system that you can’t handle plain-text comments, by the way.

    Reply  |  Quote
  8. Luke UNITED STATES Mozilla Firefox Ubuntu Linux says:

    Rob – few things:

    * I’m allowing limited HTML in the comments so that people can use links, quotes and etc.

    * Because of the above, angle brackets < and > are treated as HTML

    * Therefore, you should use the HTML entities &lt; and &gt; whenever you want to actually display angle brackets

    * A person who knows the difference between XML and XHTML and took the time to validate my website should be aware of the above

    As for the doctype and XHTML bugs – I didn’t really write this WordPress theme. I know this is not an excuse, but I’ve been to lazy to fix it since most browsers actually don’t mind.

    That said, the CSS styling on the <code> tag is a little wonky. I need to fix it.

    Reply  |  Quote
  9. Rob UNITED KINGDOM Safari Mac OS says:

    Actually, it’s < and & that need to be escaped.

    But you’ve demonstrated that even you can’t list the escaping rules correctly without taking a step back to think.

    I’m aware that such a crappy comment system (and such lousy HTML, and such lousy security) can all be blamed on WordPress. But how can so many blogs vent so long and so hard about so many topics, and yet the blogging system they’re using gets a free pass? When others have crap interfaces or technical bugs because they’re too lazy to fix them it’s absurd, but when you accept minor technical shortcomings for your own convenience it’s not a big deal?

    I admit this has little (or nothing) to do with you, beyond the fact that your entry on indentation does not actually display any indentation. It’s just a personal gripe about WordPress blogs in general…

    Reply  |  Quote
  10. Luke UNITED STATES Mozilla Firefox Ubuntu Linux says:

    Hmm… I can see the indentation in Firefox and IE. I haven’t tested Safari, because it doesn’t run on Linux. :( I’ll try to figure something out to fix it.

    Btw, I always found it funny that WordPress by default puts a link to the validator in the sidebar, but it’s themes almost never validate. :P

    Re: comment system – I can either escape < and > or allow HTML. I can’t do both. Any comment system which consists of a simple text-box, and which accepts any HTML will have the same issue – if the HTML going in is broken, then the output will look odd.

    I could use WYSIWYG editor but then we run into another problem – usually these WYSIWYG things produce horrible HTML that does not validate, and looks just plain ugly.

    And for the record – I don’t recall ever ranting at length about someone else’s personal WordPress blog serving wrong Doctype, not validating, or having a quirky comment system. :)

    Reply  |  Quote
  11. Rob UNITED KINGDOM Safari Mac OS says:

    [quote comment=”4960″]Re: comment system – I can either escape < and > or allow HTML. I can’t do both. Any comment system which consists of a simple text-box, and which accepts any HTML will have the same issue – if the HTML going in is broken, then the output will look odd.

    I could use WYSIWYG editor but then we run into another problem – usually these WYSIWYG things produce horrible HTML that does not validate, and looks just plain ugly.[/quote]

    A simple checkbox for text/html (which defaults to plain text) works, as does a popup menu for choosing between any of (maybe several) formats. And I notice that wordpress does quotes using tags in square brackets—yet more invisible escaping that could screw up comments if you weren’t looking!

    I’m a big fan of markdown-style text fields, myself.

    [quote comment=”4960″]And for the record – I don’t recall ever ranting at length about someone else’s personal WordPress blog serving wrong Doctype, not validating, or having a quirky comment system. :)[/quote]

    No; that’s me. And the only way I avoid hypocrisy is by not having a blog at all. Throwing stones is fun when you don’t have a house of any kind.

    Reply  |  Quote
  12. Luke UNITED STATES Mozilla Firefox Ubuntu Linux says:

    [quote comment=”4961″]A simple checkbox for text/html (which defaults to plain text) works, as does a popup menu for choosing between any of (maybe several) formats.[/quote]

    You know…. I didn’t even think about that. LOL

    [quote comment=”4961″]And I notice that wordpress does quotes using tags in square brackets—yet more invisible escaping that could screw up comments if you weren’t looking![/quote]

    No, that’s just a plugin that does this. WordPress itself does not have a built in quoting capability.

    [quote comment=”4961″]No; that’s me. And the only way I avoid hypocrisy is by not having a blog at all. Throwing stones is fun when you don’t have a house of any kind.[/quote]

    LOL.

    Reply  |  Quote
  13. naum UNITED STATES Mozilla Firefox Mac OS Terminalist says:

    K&R, and I don’t have my well worn copy of the K&R C Progamming Book handy, I could swear the “else” comes on the same line as the ending brace…

    # php/perl
    if ($someCondition()) {
      # do stuff for if
    } else {
      # do stuff for else
    }
    # ruby
    if 
      # do stuff for if
    else
     # do stuff for else
    end

    Cleanest style IMV, though if working on other’s code (which I don’t do anymore ;)), I will maintain the style of the original author(s)…

    Reply  |  Quote
  14. naum UNITED STATES Mozilla Firefox Mac OS Terminalist says:

    WordPress does really suck on comment handling… …it just borked a post where I gave an example of K&R where the brace and the ending else for the initial if are on the same line, which is my preferred style…

    Reply  |  Quote
  15. naum UNITED STATES Mozilla Firefox Mac OS Terminalist says:
    #php/perl
    if (cond()) {
      # do stuff for if
    } else {
      # do stuff for else
    }
    #ruby
    if something 
      # do stuff for if
    else
      #do stuff for else
    end
    Reply  |  Quote
  16. (heh my anti-spam word was foobar)
    I use the way you hate, mainly because it is simpler for me to find the opening bracket…

    Reply  |  Quote
  17. Rob UNITED KINGDOM Safari Mac OS says:

    (felt I should contribute something relevant)

    I very much prefer the K&R style. Practically, I like not wasting a full line for an open brace (vertical real estate is precious), but philosophically I view the open brace as part of the ‘if’ (or ‘for’ or ‘while’ or whatever). When I type a close brace, I care about the type of block I’m closing, not the fact that it’s a block.

    Only blocks that I create purely for scoping get open braces on lines of their own.

    Reply  |  Quote
  18. Cocoa Crusty UNITED STATES Mozilla Firefox Mac OS says:

    @Luke: Yeah, that is how it is supposed to look except I don’t put the newline between the opening statement (if (1)), etc. Basically, just like your first BSD/Allman excerpt but no extra newline when opening the code block.

    Cocoa

    Reply  |  Quote
  19. Luke UNITED STATES Mozilla Firefox Windows says:

    Seriously – I think it’s just some strange side effect of the CSS I use to format my code blocks – for some reason, any blank spaces will suddenly “end” the block. Weird.

    Reply  |  Quote
  20. Luke UNITED STATES Mozilla Firefox Windows says:

    Here is the CSS I use – can you fix it?

    code {
    	color: black;
    	background-color: #f8f8f8;
    	border-top: 1px solid #ddd;
    	border-bottom: 1px solid #ddd;
    	display: block;
    	padding: 10px;
    	font: 0.9em 'Courier New', Courier, Fixed, monospace;
    	white-space: pre-wrap;
    	white-space: -moz-pre-wrap;
    	white-space: -o-pre-wrap;
    }

    The pre-wrap stuff seems necessary to enforce white space – like tabs to stick. If I remove it, the browser eats all the tabs. But the same attributes seem to add extra blank space around each line, and cause the block to break if there is a single blank line inside.

    Reply  |  Quote
  21. Fr3d UNITED KINGDOM Mozilla Firefox Windows says:

    The indenting style I use depends on the language I’m writing.

    For PHP:

    if (condition) { 
    	do_stuff();
    } else {
    	do_something_else();
    }

    C# or Java:

    if (condition)
    {
    	do_stuff();
    }
    else
    {
    	do_something_else();
    }
    Reply  |  Quote
  22. Luke UNITED STATES Mozilla Firefox Windows says:

    [quote comment=”4968″]Yeah, that is how it is supposed to look except I don’t put the newline between the opening statement. Basically, just like your first BSD/Allman excerpt but no extra newline when opening the code block.[/quote]

    Actually, that is the BSD/Allman – the extra newline is just an artifact of the pre-wrap CSS attribute.

    Reply  |  Quote
  23. Starhawk UNITED STATES Mozilla Ubuntu Linux says:

    I use BSD/Allman despite a strong C background. It easier to read and makes more sense to me. BTW I never knew it was called “BSD/Allman” actually i never thought about calling it anything, it just works for me and is a habit now. haha

    Reply  |  Quote
  24. Luke UNITED STATES Mozilla Firefox Windows says:

    I didn’t know it was called that either, until I checked wikipedia. :P

    Reply  |  Quote
  25. Luke UNITED STATES Mozilla Firefox Windows says:

    Ok ladies! I fixed the coding issue. Now you should be able to use blank spaces, and be free not to escape HTML characters – and you will get nice code hilighting.

    Just don’t use the <code> tag – use <pre lang=”language”> where language is the name of the language you want to use (like java, php, perl, csharp and etc..)

    I made the code button default to java. Here are some examples:

    Java:

    public class Foo
    {
    	// most awesome variable evar
    	String bar;
    
    	public Foo(String bar)
    	{
    		this.bar = bar;
    	}
    
    	public String getBar()
    	{
    		return bar;
    	}
    
    }

    PHP:

    < ?php 
    
    	function foobar()
    	{
    		// do something awesome
    		$foo = "bar";
    
    		echo "the foobar: " . bar;
    	}
    ?>

    Lisp:

    ; fibonacci series
    (defun fib (n)
    	(cond
    		((= n 0) 	0)
    		((= n 1) 	1)
    		((+ (fib (- n 1)) (fib (- n 2))))
    	)
    )

    The supported languages are:

    actionscript, ada, apache, applescript, asm, asp, autoit, bash, blitzbasic, bnf, c, c_mac, caddcl, cadlisp, cfdg, cfm, cpp-qt, cpp, csharp, css-gen, css, d, delphi, diff, div, dos, eiffel, fortran, freebasic, gml, groovy, html4strict, idl, ini, inno, io, java, java5, javascript, latex, lisp, lua, matlab, mirc, mpasm, mysql, nsis, objc, ocaml-brief, ocaml, oobas, oracle8, pascal, perl, php-brief, php, plsql, python, qbasic, rails, reg, robots, ruby, sas, scheme, sdlbasic, smalltalk, smarty, sql, tcl, text, thinbasic, tsql, vb, vbnet, vhdl, visualfoxpro, winbatch, xml, xpp, z80

    Have fun. :)

    Reply  |  Quote
  26. Mirko GERMANY Mozilla Firefox Ubuntu Linux says:

    @Rob speaking of “precious vertical real estate”: I lately accidentaly ;) discovered that my LCD in the office allows rotation (instead of 4:3, it becomes 3:4). works great for coding, web browsing and writing documents. I also dislike 16:9 monitors, because menu and status bar waste even more space. in the 3:4 configuration, this effect is also diminished.

    my home LCD does not allow this rotation (but the next one certainly will), so I could not try that in Linux. anybody?

    Reply  |  Quote
  27. Ein Doofus UNITED STATES Google Chrome Windows says:

    So this on the net and I had to add my 2 cents. I’m trying to get used to looking at Allman now after coming from the Java world and it looks awful. It reminds me of those double-spaced papers from high school.

    I mean the key to reading code a block of code is the indentation, so why would you indent two lines when one is enough? Are you seriously telling me that you can’t tell where the block of code begins with this:
    if(a==b) {
    // do something
    foo();
    }

    Allman creates an unnecessary amount of white space.

    Reply  |  Quote
  28. Davidson Google Chrome Linux says:

    at my college, all teachers use the K&R style, I simply ‘fix’ all the codes that are available for it; curiously when I started programming I used only this style but after a while Allman won me over, regardless of whether the code may be greater readability greatly increases.

    Reply  |  Quote

Leave a Reply

Your email address will not be published. Required fields are marked *