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

Related Posts:

  • March of Progress
  • Awk One Liners
  • Indenting Brackets
  • Posting Twitter Updates using Java
  • The Matrix (Multiplication)
  • Substrings in Windows Batch Files
  • How much memory do I have?
  • Mounting Windown 2k3 Share in Ubuntu Dapper
  • Code Segments in Latex
  • The cost of elegant code…

  • 26 Responses to “How do you indent your code?”

    1. Gravatar Cocoa Crusty UNITED STATES Says: Reply to this comment

      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

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    2. Gravatar Cocoa Crusty UNITED STATES Says: Reply to this comment

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

      Cocoa

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    3. Gravatar hdw UNITED STATES Says: Reply to this comment

      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!

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    4. Gravatar Miloš UNITED STATES Says: Reply to this comment

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

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    5. Gravatar Luke UNITED STATES Says: Reply to this comment

      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.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.2 on Ubuntu Linux Ubuntu Linux
    6. Gravatar Rob UNITED KINGDOM Says: Reply to this comment

      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.)

      Posted using Safari Safari on Mac OS Mac OS X
    7. Gravatar Rob UNITED KINGDOM Says: Reply to this comment

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

      Posted using Safari Safari on Mac OS Mac OS X
    8. Gravatar Luke UNITED STATES Says: Reply to this comment

      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.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.2 on Ubuntu Linux Ubuntu Linux
    9. Gravatar Rob UNITED KINGDOM Says: Reply to this comment

      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…

      Posted using Safari Safari on Mac OS Mac OS X
    10. Gravatar Luke UNITED STATES Says: Reply to this comment

      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. )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.2 on Ubuntu Linux Ubuntu Linux
    11. Gravatar Rob UNITED KINGDOM Says: Reply to this comment

      Luke said:

      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.

      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.

      Luke said:

      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. )

      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.

      Posted using Safari Safari on Mac OS Mac OS X
    12. Gravatar Luke UNITED STATES Says: Reply to this comment

      Rob said:

      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.

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

      Rob said:

      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!

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

      Rob said:

      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.

      LOL.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.2 on Ubuntu Linux Ubuntu Linux
    13. Gravatar naum UNITED STATES Says: Reply to this comment

      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)…

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Mac OS Mac OS X
    14. Gravatar naum UNITED STATES Says: Reply to this comment

      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…

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Mac OS Mac OS X
    15. Gravatar naum UNITED STATES Says: Reply to this comment
      #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
      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Mac OS Mac OS X
    16. Gravatar Travis McCrea UNITED STATES Says: Reply to this comment

      (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…

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    17. Gravatar Rob UNITED KINGDOM Says: Reply to this comment

      (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.

      Posted using Safari Safari on Mac OS Mac OS X
    18. Gravatar Cocoa Crusty UNITED STATES Says: Reply to this comment

      @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

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Mac OS Mac OS X
    19. Gravatar Luke UNITED STATES Says: Reply to this comment

      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.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    20. Gravatar Luke UNITED STATES Says: Reply to this comment

      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.

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    21. Gravatar Fr3d UNITED KINGDOM Says: Reply to this comment

      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();
      }
      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows Vista
    22. Gravatar Luke UNITED STATES Says: Reply to this comment

      Cocoa Crusty said:

      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.

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

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    23. Gravatar Starhawk UNITED STATES Says: Reply to this comment

      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

      Posted using Mozilla Mozilla 1.8.1.3 on Ubuntu Linux Ubuntu Linux
    24. Gravatar Luke UNITED STATES Says: Reply to this comment

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

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    25. Gravatar Luke UNITED STATES Says: Reply to this comment

      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. )

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Windows Windows XP
    26. Gravatar Mirko GERMANY Says: Reply to this comment

      @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?

      Posted using Mozilla Firefox Mozilla Firefox 2.0.0.4 on Ubuntu Linux Ubuntu Linux

    Leave a Reply

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre lang=""> <em> <i> <strike> <strong>

    [Quote selected]