Why you should Indent with Spaces

I avoid tabs in all code I write. That’s why you can read my code in your browser with the exact same formatting as it had in my IDE – no matter what browser or device you are using: Nuclex Framework sources in TRAC. Yet from time to time, I encounter people evangelizing tabs.

While I am fine with working on projects that use tab characters and I neither argue about the decision to use tabs nor intentionally divert from their style, I do have an opinion and it is that you should avoid tabs wherever you can.

Even the one, lonely, supposed advantage of tabs – users being able to choose their preferred indentation level – is a drawback in disguise because you no longer can set a safe limit for line lengths (see below).

  • Tabs are inconsistent even on their own!

    One editor will interpret them as "insert 8 spaces here" another as "go to the next multiple of 8".

    Spaces, in contrast, always have the same effect in every place, editor and environment.

    But rejoice, efforts are underway to add yet another possible behavior for tabs: elastic tab stops which automatically change their width depending on context!

  • Correct use of tabs requires OCD!

    If you use tabs for indentation, you still have to use spaces for aligning. So to make code look consistent across different tab widths, you have to do weird things like fill a line with tabs up to the current indentation level, then fill the rest with spaces:

    Tabs for Indentation, Spaces for Alignment? No thanks.

    Of couurse everyone will remember this rule when they need to align their code and consistently mix tabs and spaces in just the right way.

  • Your Editor Butchers your Code!

    Wait, did I just say mix tabs and spaces? I’ve used a lot of text editors and some helpfully ask me:

    Do you want to destroy formatting or destroy formatting?

    Well, any choice other than Cancel will destroy your carefully arranged contraption of tabs and spaces from the previous section!

  • Browsers will Indent like Crazy!

    When you view tab-indented code in a web browser, it will be indented by a ridiculous amount of space.

    Better hope your CSS works for Visitors preferring 16-space wide Tabs!

    Yeah, a handful of browsers have or are about to introduce an obscure expert setting you can use to tweak tab width.

    And Suure, all your visitors will use such a browser, be aware of that setting and will have it tweaked to their favorite tab width. Those visitors reading your blog/forum/publication on a tablet or smartphone with limited screen space will most assuredly have tweaked their browser settings.

  • The Magical NoS-Injected Cursor

    Tabs become really nasty when you select things or delete code because, after leisurely advancing through your columns and lulling you into estimating the time when you will release the key, your cursor will suddenly speed up two- or four-fold and come crashing into the next line.

    I like my keyboard repeat rate set to max and I don’t know how often I accidentally killed a chunk of code because suddenly a tab-indented line hid somewhere in the code.

  • No Safe Screen Size to Target!

    When you use spaces, you can set a hard limit for how long your code lines should be. Popular choices are 100 or 120 characters. That’s pretty damn useful because you can say:

    If your arrange your editor panes to display this many characters, you will never, ever have your coding disrupted by the need to horizontal-scroll.

    Now here come the tabs. Here are the rules tab-users would have to follow. Enjoy!

    1. For ensuring no horizontal scrolling at a maximum of 4 spaces per tab, at an indentation of 1, limit your line to 97 characters.
    2. For ensuring no horizontal scrolling at a maximum of 8 spaces per tab, at an indentation of 1, limit your line to 93 characters.
    3. For ensuring no horizontal scrolling at a maximum of 4 spaces per tab, at an indentation of 2, limit your line to 94 characters.
    4. For ensuring no horizontal scrolling at a maximum of 8 spaces per tab, at an indentation of 2, limit your line to 86 characters.
    5. For ensuring no horizontal scrolling at a maximum of 4 spaces per tab, at an indentation of 3, limit your line to 91 characters.
    6. For ensuring no horizontal scrolling at a maximum of 8 spaces per tab, at an indentation of 3, limit your line to 79 characters.
    7. For ensuring no horizontal scrolling at a maximum of 4 spaces per tab, at an indentation of 4, limit your line to 88 characters.
    8. For ensuring no horizontal scrolling at a maximum of 8 spaces per tab, at an indentation of 4, limit your line to 72 characters.
  • Tab users have Three cursor coordinates

    We can thank the tab character for the existence of this ugly wart:

    Where is my Cursor? Oh, Column 12. No wait, Character 8!

    Where is my cursor? Oh, column 12. No wait, it’s at character 8! ’nuff said.

  • Indentation-Delimited Languages Love Tabs! </sarcasm>

    There are languages that delimit blocks not by the famous sequences like {/} or BEGIN/END, but by whitespace alone. Python for example: Python PEP 8 Style Guide for Python:

    class Rectangle(Blob):
    
        def __init__(self, width, height,
                     color='black', emphasis=None, highlight=0):
    
        if (width == 0 and height == 0 and
            color == 'red' and emphasis == 'strong' or
            highlight > 100):
            raise ValueError("sorry, you lose")
    
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
    
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)
        

    So Python programmers can just forget about aligning things?

That’s my opinion on tabs. I’m aware that this post could possibly attract some heated arguments from those programmers who prefer tabs, but I needed to write this after working in a large, tab-using codebase for the past few days. I won’t bully anyone into using this or that style, but as to what’s superior – that matter looks pretty black and white to me.

7 thoughts to “Why you should Indent with Spaces”

  1. I always use tabs, at least wherever possible, and never have the magnitude of the problems you are describing here.

    First, most editors these days provide an option to set the tab size. I always set mine to four.

    Changing mixed tabs and spaces is usually simple using the tools that editors provide, as you describe.

    The browser problem. Fair enough. But Web browsers aren’t meant for viewing code. Use an editor like Notepad++ or TextMate. Sites like Stackoverflow also seem to work properly with mixed tabs and spaces too, as long as the lines are indented properly.

    The alignment side of things? Well, I dont tend to right align code as you have in the example. I used to make sure everything lined up, but these days I just make sure indentation is working and forget about alignment inside the line.

    I haven’t heard of elastic tabs, but I can’t say I’d use them since normal tabs just work so well! ;-)

  2. Whatever floats your boat ;)

    Yep, nearly all the editors allow you to change the tab size, which is the reason tabs are such a big problem when working with a hard limit on line length.

    Indeed, changing mixed tabs and spaces is really simple using the tools I describe, except that it can make things even worse — not only if the code aligns stuff, but also if the programmer who mixed spaces and tabs had his tab width set to 2, and yours is set to 4. It will cement all the resulting formatting errors into the code…

    On the browser issue, I do think browsers are meant to view code. Like browsing through sources in TRAC, Jira or a site like Github, auditing changesets with said tools, submitting patches to a mailing list, posting code snippets in forums, adding example code to your documentation, …or running a programming blog ;)

    But I think it’s a good choice that you don’t align things in code :D – It’s something a good style (imho) avoids as much as possible. However, I’d argue that it still increases readability when initializing arrays of numbers (like the matrix above) or drawing ASCII figures in comments to illustrate things.

  3. Heh, Although I use tabs because they’re quick I have set my IDE up so it automatically converts them into 4 space characters (Anything less causes too little indentation and anything more causes too much)

    Now for the idea on maximum line length, I never thought of that(!)
    I just continue with the line going merrily off into infinity (Not an actual problem until I review my code, then I normally split lines up into maybe 85 character long sequences and let the rest of the line build up like a cancerous blob below ^^”)

  4. Hi,
    Thanks for your post. I prefer tabs and searched the internet for while because i wondered why one would use spaces. Nice to see some real arguments, not just flaming.
    But you could not convince me ;-)

  5. @WB: That article was more or less the reason why I wrote this post :P

    I found every single argument in that article to be insignificant or outright wrong, eg.

    • Tabs take up less space – Narf. On the project I’m working on, it would save me less than 3.5% in theoretical disk space (and zilch in actual disk space because of fs block size). Nothing saved in Subversion, git or .tar.gz/.zip distribution due to compression.
    • Tabs can be personalized – The only one with some merit, though this creates the problem of making it impossible to define a safe maximum line length for code editors which find much more troublesome. If I have to sidescroll, I can’t read the code properly.
    • Tabs can be personalized – Same statement as above under another title
    • Tabs are easy to select – Very far fetched, imho. In 20 years of programming I haven’t seen anybody do a search & replace on tabs. You use your editors add/remove leading whitespace / identation feature
    • Code indented with tabs is easier to copy & paste – Also very far-fetched. Copy & paste is not something you should do in code, and if you do it during refactoring, you’re very likely to move code inside the same codebase (= same formatting) or will have to adjust regardless of tab/space because of different indentation levels.
    • Are spaces always evil? – I even have to disagree on the one thing where that post’s author thinks spaces are good for. Don’t align. Never ever. Coding styles that require lining things up are hard to maintain and if you do this in a tabified code base, see my paragraph "Correct use of tabs requires OCD!"

    I can relate to the "Tabs can be personalized" claim (though its disadvantages outweigh the advantages imho – and you still have to adjust to the rest of the project’s coding conventions), but so far I haven’t seen any convincing argument for tabs yet.

Leave a Reply

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

Please copy the string fW5NKO to the field below:

This site uses Akismet to reduce spam. Learn how your comment data is processed.