Death to the Space Infidels!

April 13, 2009

Ah, spring. What a wonderful time of year. A time when young programmers' minds turn to thoughts of ... neverending last-man-standing filibuster arguments about code formatting.

Naturally.

And there is no argument more evergreen than the timeless debate between tabs and spaces.

On defaultly-configured Unix systems, and on ancient dumb terminals and teletypes, the tradition has been for the TAB character to mean move to the right until the current column is a multiple of 8. This is also the default in the two most popular Unix editors, Emacs and vi.

In many Windows and Mac editors, the default interpretation is the same, except that multiples of 4 are used instead of multiples of 8.

A third interpretation is for the ASCII TAB character to mean indent to the next tab stop, where the tab stops are set arbitrarily: they might not necessarily be equally distanced from each other. Most word processors can do this; Emacs can do this. I don't think vi can do this, but I'm not sure.

With these three interpretations, the ASCII TAB character is essentially being used as a compression mechanism, to make sequences of SPACE-characters take up less room in the file.

So, then, the question: should code* be indented with spaces..

visual-studio-space-indent

or with tabs?

visual-studio-tabs-indent

According to Cyrus, there's a third option: an unholy melding of both tabs and spaces. Apparently you can use tab for primary indentation alignment and then spaces on top of that for detail alignment. Like so:

visual-studio-space-and-tab-indent.png

This way, in theory at least, the level of indent can be adjusted dynamically without destroying alignment. But I'm more inclined to think of it as combining all the complexity and pitfalls of both approaches, myself.

OK, so maybe you're an enlightened coder. You've moved beyond mere earthbound issues like tabs vs. spaces on your personal path to code nirvana. Perhaps you have some kind of fancy auto-formatter that runs on every checkin. Or, maybe you're using a next-next-generation editor that treats code as "data" and the layout (including whitespace) as a "view", making all these concerns largely irrelevant.

But there's a deeper issue here to consider. The only programming project with no disagreement whatsoever on code formatting is the one you work on alone. Wherever there are two programmers working on the same project, there are invariably disagreements about how the code should be formatted. Sometimes serious disagreements. The more programmers you add, the more divisive those disagreements get. And handling those disagreements can be .. tricky. Take this email I received from Philip Leitch:

The place where I work currently has a developer (who is also the head of the development department), who will "clean up" the code of others.

That is -- reformat it, normally without changing what the code does, just changing the variable names, function names, but mainly moving things around to the way they like it.

It is a little perplexing Ö and I'm interested to see what responses people have on this issue.

One of absolute worst, worst methods of teamicide for software developers is to engage in these kinds of passive-aggressive formatting wars. I know because I've been there. They destroy peer relationships, and depending on the type of formatting, can also damage your ability to effectively compare revisions in source control, which is really scary. I can't even imagine how bad it would get if the lead was guilty of this behavior. That's leading by example, all right. Bad example.

The depressing thing about all this is that code formatting matters more than you think. Perhaps even enough to justify the endless religious wars that are fought over it. Consider the 1984 study by Soloway and Ehrlich cited in Code Complete:

Our studies support the claim that knowledge of programming plans and rules of programming discourse can have a significant impact on program comprehension. In their book called The Elements of Programming Style, Kernighan and Plauger also identify what we would call discourse rules. Our empirical results put teeth into these rules: It is not merely a matter of aesthetics that programs should be written in a particular style. Rather there is a psychological basis for writing programs in a conventional manner: programmers have strong expectations that other programmers will follow these discourse rules. If the rules are violated, then the utility afforded by the expectations that programmers have built up over time is effectively nullified. The results from the experiments with novice and advanced student programmers and with professional programmers described in this paper provide clear support for these claims.

There's actual data from honest-to-goodness experiments to support the hypothesis that consistent code formatting is worth fighting for. And there are dozens of studies backing it up, too, as Steve McConnell notes:

In their classic paper Perception in Chess, Chase and Simon reported on a study that compared the abilities of experts and novices to remember the positions of pieces in chess. When pieces were arranged on the board as they might be during a game, the experts' memories were far superior to the novices'. When the pieces were arranged randomly, there was little difference between the memories of the experts and the novices. The traditional interpretation of this result is that an expert's memory is not inherently better than a novice's but that the expert has a knowledge structure that helps him or her remember particular kinds of information. When new information corresponds to the knowledge structure -- in this case, the sensible placement of chess pieces -- the expert can remember it easily. When new information doesn't correspond to a knowledge structure -- the chess pieces are randomly positioned -- the expert can't remember it any better than the novice.

A few years later, Ben Shneiderman duplicated Chase and Simon's results in the computer-programming arena and reported his results in a paper called Exploratory Experiments in Programmer Behavior. Shneiderman found that when program statements were arranged in a sensible order, experts were able to remember them better than novices. When statements were shuffled, the experts' superiority was reduced. Shneiderman's results have been confirmed in other studies. The basic concept has also been confirmed in the games Go and bridge and in electronics, music, and physics.

So yes, absurd as it may sound, fighting over whitespace characters and other seemingly trivial issues of code layout is actually justified. Within reason of course -- when done openly, in a fair and concensus building way, and without stabbing your teammates in the face along the way.

Choose tabs, choose spaces, choose whatever layout conventions make sense to you and your team. It doesn't actually matter which coding styles you pick. What does matter is that you, and everyone else on your team, sticks with those conventions and uses them consistently.

That said, only a moron would use tabs to format their code.

* unless you happen to be programming in whitespace or Python.

Posted by Jeff Atwood
275 Comments

@Chris Noe: It's a total non-issue on the command line. That's what god invented tr for.

Rachel Blum on April 13, 2009 2:03 AM

A response:

http://peterbraden.co.uk/article/space-infidel

Peter on April 13, 2009 2:12 AM

Quoting from the article, ... depending on the type of formatting, can also damage your ability to effectively compare revisions in source control, which is really scary. ...

In answer to that problem, why isn't there a syntax/semantics sensitive compare utility?

What I mean is, I would like a version compare utility that knew what was significant and what was insignificant. It would have classes of changes to be checked for that could be controlled independently.

The most restrictive level would flag every mismatch of whitespace, tabs, newlines, comment text, and everything above that. A somewhat more lenient level would ignore semantically meaningless differences in whitespace, tabs, newlines, etc (but not in strings, presumably), but would flag other changes.

The most lenient level would NOT flag anything but semantically meaningful differences.

For instance, and assuming all references were also changed consistently, renames inside a function of arguments and local variables would not be flagged as changes.

Also, renames of private functions would not be flagged as changes.

This would solve the problem of code reformatting and code cleanup making it difficult to compare revisions. With the current compare technology, a simple reformatting of the code can make the revision compare system flag practically every statement in the source file, making it difficult to find the real changes.

Does anything like this exist?

Sleazey on April 13, 2009 2:27 AM

Theoretically, tabs have a semantic distinction that spaces don't. But in the real world, neither is used in the semantic sense -- they are used to present the code in a visually appealing and understandable way. Even in python, it's about the semantic value of alignment, not the semantic value of a tabstop.

The only tool I can remember with TAB as a semantic value is Make, and that was an quite obviously horrible mistake.

And, again, in real practical experience, tabs are almost *never* consistent from person to person for large projects -- even if they are using the same editor. Spaces are *always* consistent, and editors for over 25 years now have done the proper thing with spaces when you press the TAB key, so those who think the difference between 5 characters typed and one character typed is actually significant need to upgrade their editors. :-)

TABs are, frankly, a relic.

E.S. on April 13, 2009 2:29 AM

@Jeremy: didn't try using Ctrl+F before posting, did you? :D

I favour three spaces and work at a place that uses four, which isn't so bad. I autoconvert tabs to spaces.

In my ideal world we'd all use stickytabs which aligns to logical boundaries defines by the syntax of the line above rather than to arbitrary column widths, but most editors don't do this and if they did, I doubt it would be terribly consistent.

Tabs are easier to press and spaces guarantee consistency across all views without any configuration, so my call is for some number of spaces (certainly no more than 8, and preferably no more than 4). Also, I am the sort of person who tends to align assignments and declarations and so forth, since I find it is far easier to read down one column that way.

The one style I have a hard time with is KR style braces. I far, far prefer Allman style. I can see the point of a few others, but I'm used to Allman. I don't agree with the argument that the new whitespace necessarily makes it clear because when I'm looking down the left hand side of the current code context, a sudden blank could mean an indent or it could mean somebody pressed enter twice to separate logical sequential code blocks, so I have to look over to the right to determine which it is, or else read the previous line to see if it's a continued block statement. For similar reasons, I prefer putting the braces down even on one-line statements. KR just increases horizontal eye movement. The case where a block is so large that the vertical space matters on a modern monitor should be rare, kind of like the case where the open brace would get cut off horizontally in KR should be rare.

Ens on April 13, 2009 2:32 AM

That guy Cyrus you mentioned has it exactly right: tabs for indentation, spaces for alignment. Then people can adjust the indent level to be whatever they want (I happen to like 3) and everything still aligns correctly. I wrote some indentation code for emacs to properly indent according to the tabs for indentation, spaces for alignment concept. Works great.

goof on April 13, 2009 2:46 AM

If I'm working on my own code only, I prefer tabs, because I hate it when editors make me hit backspace four times to clear out to the start of the line. It also makes changing the formatting much easier - want a 2-space tab instead of 4? Just click a setting.

But for anything that anyone else will ever see I use spaces, just because I have seen so many idiotic settings make code completely unreadable in many editors when using tabs.

It's like giving your files lower case names without spaces and with an extension on a mac (mycat.jpg instead of Picture of my Cat) - on your own system, you don't need to do that crap. But when you work with other people you have to go to what works with the lowest common denominator.

Mike on April 13, 2009 2:50 AM

1. The single largest source of bugs in the Python code at my last company came from the (accidental) use of tabs.
... which leads to ...
2. I've never seen a tab-based codebase that did not have a mixture of tabs and spaces. This works great until the one day you need a tool that chokes on the mixture.

3. In my experience, tabs tend to be preferred by programmers who spend most of their time in Microsoft Visual Studio style IDEs.

As others have said before, a space is a space and there is no ambiguity.

Harvey on April 13, 2009 2:51 AM

I can tell novices and just plain bad programmers by how they indent (or not) their code. I can tolerate most anything except code that isn't indented correctly.

People that use spaces to indent are forcing their view of the code on others. If you use tabs I can switch the code from your view to my view just by editing the file.

Remember it's called the Art of programming. Make your code look beautiful to everyone. And yes, surface beauty (how the code looks) counts.

ray on April 13, 2009 2:58 AM

This is a dumb argument.
Who cares!

Donny V on April 13, 2009 3:19 AM

That said, only a moron would use tabs to format their code.

Then call me a moron, because I can't stand spaces.

(stupid rationalization)Besides, you save so much disk space by using a single tab character instead of four space characters. Ergo, tabs are better. QED.(/stupid rationalization)

Adam V on April 13, 2009 3:26 AM

Always use spaces. As has been pointed out, tabs are handled inconsistently, while spaces are always handled the same. It doesn't cost extra time either, any real editor or IDE can be configured to output spaces in the place of a tab.

My current employer has relatively strict guidelines on code formatting, and I'm glad it does. In fact I still sometimes spend time reformatting other people's code to make it more legible.

Toby J on April 13, 2009 3:50 AM

I find it difficult to believe so much effort is wasted on this crap.

I've never had any form of discussion with co-workers on whether to use scheme X vs Y. Either our workplace is amazingly like-minded (hah) or more likely we have much better things to do with our time.


Solution: Pick an editor or IDE which does this worrying for you. Or if you're particularly insistant: has a preference to layout your code in the way you want.

Now go solve some other more pressing problem -- like world peace. Or perhaps just making sure your code actually works (How's your test coverage?)

Will on April 13, 2009 3:53 AM

I'm partial to tabs, myself, simply because they're more flexible. Spaces are fine if it's my own code, but I'd much rather use tabs and be able to set my own width if I'm on a team where someone likes it wider/narrower than myself.

pudds on April 13, 2009 4:01 AM

That said, only a moron would use tabs to format their code.

sarcasmI'm glad to see your subtlety was not lost on this group.../sarcasm.

Brian on April 13, 2009 4:05 AM

Atwood spends several hundreds of words on nothing, really:

0) There is a religous war centered around formatting code.
1) Pick a formatting standard that works for you and your team. If no team member is truly happy with all the elements of your standard, you probably have the right one.
2) Set up a checkin hook to enforce/fix the formatting issues.
3) Move on

I know I have commented on various topics on SO related to this. sigh. So many posts from jeff lately must mean that there is nothing to work on over at SO these days...

Mike J on April 13, 2009 4:05 AM

Problems at Stackoverflow code base or is it just from another situation?

Andrei Rinea on April 13, 2009 4:08 AM

I never cared much about spaces vs tabs. What I do care a lot is:

int main() {
return 0;
}

versus

int main()
{
return 0;
}

Spaces vs. tabs is a minor skirmish in the formatting wars. This is the issue over which blood is truly spilt.

Zorro on April 13, 2009 4:09 AM

I work on a project where the convention is 3 spaces for indenting. I spent a few minutes googling up the necessary vim magic that makes vim understand this, and then I can type exactly as I'm used to, using tabs, as it were, yet get the 3-spaces format. even lt;lt; works correctly.

Only morons use tabs? Them's fighting words.

Here's a suitable arena: http://wordwarvi.sourceforge.net

SteveC on April 13, 2009 4:26 AM

ok, let's settle this. I created a (Survey Monkey) survey to quantify people's preferences: a href=http://www.surveymonkey.com/s.aspx?sm=CuOCMx8ZkrpzKrEsWp0YpQ_3d_3dsurvey: tabs vs spaces?/a

Apparently Survey Monkey does not share the survey results with people taking the survey, but I promise to post the results here after a day or two.

chipset on April 13, 2009 4:36 AM

fixed link:
http://www.surveymonkey.com/s.aspx?sm=CuOCMx8ZkrpzKrEsWp0YpQ_3d_3d

chipset on April 13, 2009 4:37 AM

When dealing with javascript or CSS or HTML, if you use spaces instead of tabs, wouldn't that significantly increase the size of your response? The byte-count of the codefiles and markup files are bigger, which means that there's just that many more wasted bytes that have to be transmitted. I'm sure HTTP compression can help, but even with it, I'd bet that there is a performance benefit to using tabs (or removing basically all whitespace, but that's a bit extreme). It's probably not a huge deal, but if you're ultra-concerned about performance, every millisecond helps.

And if you're going to use tabs in your HTML, javascript, and CSS, why not the rest of your codefiles?

I'm not completely opposed to using spaces instead of tabs, but if you're going to do it, I'd absolutely agree that you have to define a standard (I'd say 4 spaces) and stick with it across your company, with no exceptions for any reason.

Joe Enos on April 13, 2009 4:48 AM

@Joe Enos
Most people minify ( http://en.wikipedia.org/wiki/Minification_(programming) ) their html/javascript/css code.

Hoffmann on April 13, 2009 4:55 AM

I rather dislike my tabs becoming spaces, though now that I'm in Visual Studio most of the time, I just let it do it's magic.

One point, however, vim can totally fake tab stops using a plugin: http://www.vim.org/scripts/script.php?script_id=785

Kearns on April 13, 2009 5:03 AM

I prefer tabs over spaces and let them be two spaces wide, so I don't waste to much space and have the opportunity to spaghetti my code up!

I also do this (JavaScript):

function getSomething(){
/* Very much code. */
return 'something';}

Code looks very much like Python then!

God's Boss on April 13, 2009 5:08 AM

@Hoffmann:
I'm sure a lot of people do minify their stuff, but try doing a view source on a dozen random web apps out there, and also view their javascript and css files - I'd bet more than half don't do any minification, and several more do only a little bit. It's a nice concept in theory to minify all your stuff, but it's a little more challenging in practice - otherwise I'm sure everyone would do it.

Joe Enos on April 13, 2009 5:10 AM

Hey, anyone remember make? Just make sure that tab is a tab, not a bunch of space, hehe :)

Oldster on April 13, 2009 5:10 AM

Tabs. Then you can dynamically adjust how deep your indentation is. There's just no excuse to use spaces.

Spaces also don't work if you use a variable-length font.

Bill on April 13, 2009 5:26 AM

@Bill:
Variable-width font in code? You'd have to be smoking some serious stuff if you're using that.

Joe Enos on April 13, 2009 5:35 AM

Apparently my 2008 IDE isn't modern enough when it comes to shielding me from the tab/space impedance mismatch.

I want # Tabs == # Backspaces.

I want # Tabs == # arrow key presses (for navigation and text selection).

For these reasons, tabs currently give me the best editing experience. We all know that editing code consumes more of our time than writing greenfield code, so I would argue that tabs result in greater productivity than spaces.

Oran on April 13, 2009 5:42 AM

I only hit the tab button to get me x spaces indented, and usually with reformatting GUI's I don't even have to hit tab all that often.

I don't care about tabs, and I don't care about spaces, but I do care about the reduced comprehension when reading oddly formatted code.

But there is a bigger problem, and it's 10 different people skinning the cat in 10 different ways, and indentation is but a small part of it.

I like how Agile treats it. Code is common and belongs to everybody. It's not your own pet project, so express your individuality not in code, but in clothing or decorating your office. Get a perm. You should not be able to distinguish who wrote the code, ever. When your team can achieve this, all members of your team will benefit by not suffering cognitive dissonance when reading unfamiliar code.

spaceace on April 13, 2009 5:45 AM

program statements were arranged in a sensible order, experts were able to remember them better than novices. When statements were shuffled, the experts' superiority was reduced

My browser must have missed a couple paragraphs in the download. How do you get from this to tabs/spaces? I can see how putting things in the *wrong order* makes it harder, but I don't see how that applies to what character code you use for pushing your statements to the right. With the right editor settings, you can't even tell the difference just by looking.

Surely, even if I admit that one's memorization skills are affected by their order (which I think is reasonable), I don't see any reason to jump to the conclusion that they're affected by something which is, by definition, *invisible*.

Do you also think it is harder to remember things about some source code if it uses different linefeed characters, or a different Unicode encoding, or is stored on a different filesystem? Because these things sound exactly as relevant to me.

Ken on April 13, 2009 5:47 AM

Here's my take...

There is a fundamental tension between wanting to reformat the code and wanting to avoid reformatting the code. We want to reformat so we can read and understand. We want to avoid reformatting because it pisses off our coworkers and interferes with source control history.

We can break this tension by breaking the link between how the code is stored and how it is displayed. It is a classic model-view-controller problem. Editors should have a display pretty but don't change it mode.

The display mode could allow full control of all aesthetic parameters including indent, space around parens, new lines before braces, etc.

When saving, the editor would make a few changes as possible. Opening white space would be preserved on existing or changed lines. Opening white space would follow the convention of near by code for new lines.

I think this would make everyone happy.

Joe Biegelsen on April 13, 2009 5:55 AM

*[...] or MUMPS. (BTDT).

trurl on April 13, 2009 6:02 AM

Who writes code with variable length fonts? That's just heresy.

The problem I have with tabs is that it will inevitably lead to Jeff's third case at some point. I'll want to align something across two rows and with tabs you could end up with mismatching alignment as soon as someone with different spacing settings opens it up. Spaces solve this.

Most IDE's (and even things like Vim) have smart intending anyway, so I rarely have to manually tab or space for anything.

Alex on April 13, 2009 6:07 AM

I like the way InType handles it: you can set it to either use spaces or tabs, and you can set how far a tab length is. By default it's 4; you can change it to 2, 8, whatever.

NH on April 13, 2009 6:39 AM

If there was a backtab key, then I could live with space insertion on pressing the Tab key. But there is not, and few things annoy me more than having to backspace my way through 5 or 6 tabs in the middle of a line.

Tab is a dedicated key on a keyboard. It has a use. On typewriters it moves to the next tab stop, there's NO REASON to overload this.

And... I have to say, 2 spaces is NOT sufficient for indented code legibility.

I also note that if you use VS200X's Format Document, you get TABS out of the box, not spaces, and they are 4 spaces long. When in doubt, use what you're given as the convention.

Rick Cabral on April 13, 2009 6:45 AM

How about we stop using text format for code or have smarter tools. Instead of the current line based approach, have diff tools that can indicate that methods have been moved, changed signature etc. Changes in formatting are not important in terms of change management.

Anonymous on April 13, 2009 7:02 AM

There's another variant out there that's got some traction: The standard FSF/GCC programming style.

In this style, subsequent indentations are in multiples of four spaces. And then any sequences of eight spaces are replaced by tabs. Thus, what you get is:

....for (foo) {
- bar;
- for (baz) {
- ....froboz;
- }
....}

where - is a tab and .... is four spaces.

Brooks Moses on April 13, 2009 7:27 AM

Tabs. I'm going to try the Tabs + Spaces example.

Zoasterboy on April 13, 2009 7:28 AM

Haven't you folks heard of the old fashioned pretty printer? Google it...or code beautifier, which seems to be the new fangled term for it.

Once you have a pretty printer that works for the language you're using, just configure it and make it part of your source get process. Stop wasting time arguing about tabs vs. spaces and start using your time productively...arguing about variable names or method names.

Jimbo on April 13, 2009 7:52 AM

I use Textmate, and have it set to 5 spaces per tab. But I feel as though I am in tab mode, it just lays down spaces. I can still arrow through code, and it jumps 5 spaces at a time, if you were to watch, you would swear I had tabs on, but in the end, they are spaces.

This allows formatting that does not shift around, which I like. Some SQL statements can get ugly, and I like them to line up for readability, spaces are the only way I know to do that.

Does anyone know in TextMate how to go from one cuddle format to the other? I like the first, but often times I get code in the second. These are my personal projects, and I am swiping examples off the web, and want the brackets on one line.

int main() {
return 0;
}

versus

int main()
{
return 0;
}

Anony on April 13, 2009 7:54 AM

(Almost) everyone is talking like it's the 80s. Computers aren't scarce resources and one of the key philosophies now is NEVER DO SOMETHING THE COMPUTER CAN DO.

Don't use a code formatter because it lets you keep coding styles consistent among the team.

Use the code formatter because it's one less thing that you, the very expensive hairless monkey sitting at the keyboard, has to do. At least do it at the end of each 'sprint', along with running static code analyzers (e.g., 'findbugs') and the like.

BTW I'm old school Unix, although not quite as old school as a former coworker who still used 'ed'. But today I use proportional fonts (verdana) instead of courier. It may be due to language since Java has far longer method names than C's function names.

Chris on April 13, 2009 8:13 AM

In Eclipse,

ctrl+alt+space (tabs - spaces)

or

ctrl+alt+tab (spaces - tabs)

Walla!

zefi on April 13, 2009 8:16 AM

Since everyone just *has* to weigh in on this...

There are several issues that have been raised in the comments here that I feel like addressing.

One is the amount to indent, which isn't really about tabs vs. spaces, except people have said, more-or-less, if you use tabs you can see it whichever way you want.
Good old KR C promoted indenting by 1 tab, where a tab is equivalent to (up to) 8 spaces. That's too wide! you say, What if I need to print it? you say. The argument was that if it was too wide to print -- that is, indented too far -- then your code needed restructuring anyway. You were doing too much in-line to end up with an indent that wide and you should refactor some of that into functions.
Now indents of 4 are so common now that I stick with that myself, but I'd still apply the argument to people who say they need an indent of 2. If things are getting too wide with an indent of 4 so you need to use 2 then something is more fundamentally wrong with your code than the way you use whitespace.

This easily leads to the tabs vs. spaces debate; again people have said you can see it how you personally prefer it if you use tabs -- see it as 2 or 4 or 13 if you like. Except -- I use multiple tools on a source code file; the IDE, sometimes a plain editor, VIM, other non-editing tools. Somewhere along the way, like, maybe =printing=, __WILL__ treat your tabs as 8 space tabstops, and now your code is indented deeper than you thought. Also, somewhere along the way, someone _will_ have indented or added extra indentation using spaces (as Harvey pointed out). Those don't line up anymore because they assume a tab stop of X (where X 8)

My take is -- it doesn't matter what you _want_ tabs to be, they _are_ 8.
Even if you make your whole system consistent so that tabs always cause an indent of 4 (or 2 or 13), some fool will open your file on their system and all bets will be off. The only 100% safe way is to use spaces

BTW, what some people were wishing for -- have the editor just present it the way _you_ like it, even maybe including variable and function names -- is called Source Code In Database (SCID) and there have been / are systems that do it.

So it comes down to, for me
- indent levels are 4
- tabs are 8
- pressing the tab key gives you 1 indent level
- which is 4 spaces (never tabs)

No extra keystrokes just because I'm using spaces. Shift Indent Level left or right commands are in the IDE/editor so no crying about I have to delete N spaces instead of just one tab
Indenting is _always_ the same no matter who's looking at it on what machine using which tool.

That's what I do, with the reasoning behind it.

Stephen P.

(and Adam V -- not picking or anything, but do you also trim trailing whitespace and use only Unix style LF, not CRLF pairs, for line endings, all to save disk space? I personally loathe the way IDEs leave trailing whitespace on lines and leave lines that include whitespace-only because you hit enter-enter to get a blank line. Doesn't matter much for code or plentiful disk space but when you end up with HTML that's 30% bigger due to that crud it does affect your bandwidth)

Stephen P. on April 13, 2009 8:44 AM

spaces tabs

Mainly, why press a button 4 times when you can press it once?

reg4c on April 13, 2009 8:44 AM

Tab key, but use an editor that converts tabs to spaces.

Nobody I've met in person disagrees with this logic.

Anyone who uses 8-character-wide tabs is a madman and anyone who uses 2-character-wide indenting is a lunatic.

Using 4-character-wide indentation means that you are alright and don't need to be beaten about the head.

TM on April 13, 2009 9:06 AM

As an ASCII conservationist, clearly the only ecologically sound solution is to use tabs. The third-option arguments about alignment are suprious distraction - such superflous alignment is utterly unnecessary and wasteful.

P.S. Congratulations on generating 5000 comments with a tabs vs spaces blog post. If only people cared as much about serious things...like CamelCase vs bsHungarian!

irrelevant on April 13, 2009 9:20 AM

@TM
Anyone who uses 8-character-wide tabs is a madman and anyone who uses 2-character-wide indenting is a lunatic.

Thank you for sharing your empathic and well reasoned thoughts. It must be very nice to live in a world where your personal preference always is just perfect.

Sarcasm on April 13, 2009 9:23 AM

I always set my editors to view space/tab characters, so it does get on my nerves at times, but I've learned to keep my mouth shut and wait until project standards converge.

Robert on April 13, 2009 9:43 AM

Another time first :D
The third option will be interesting, as it enables me to see the break line clearer, sometimes it's confusing.

Omar Abid on April 13, 2009 10:20 AM

And then there is the editors that simply convert a tab keystroke into 4 spaces. Voila, argument avoided.

klietus on April 13, 2009 10:22 AM

editors that simply convert a tab keystroke into 4 spaces. Voila, argument avoided.

Yeah, but I like 2 spaces. 4 is just stupidly wide. So I'll reformat and check in... ok? :)

Jeff Atwood on April 13, 2009 10:28 AM

I get furious when I see 4 spaces used instead of a tab. But I'm not sure why. It's not something to get emotional over, but I do.

David on April 13, 2009 10:32 AM

That is -- reformat it, normally without changing what the code does, just changing the variable names, function names, but mainly moving things around to the way they like it.

This guy seems to be complaining about a lot less trivial changes than tabs, spaces and the location of curly brackets. He's complaining about someone cleaning his code, which if done properly, leads to much more readable code. After reading Clean Code recently, I've taken to following the Boy Scout Rule and look for any bit of code in need of cleaning in any source file I happen to have otherwise checked out.

As the person doing the cleaning has the authority to do so and is presumably senior to the complainer, the complainer should take the opportunity to learn if his code can be improved.

Glenn Howes on April 13, 2009 10:33 AM

I agree with using the spaces instead of tabs otherwise you get wild variations with the tabs depending on code editor. That said, I still use tabs instead of spaces. Can't drop the habit. Worse... I put the first curly bracket after the method name on the same line. Geez, I better quit while I can!

Johnny on April 13, 2009 10:34 AM

A fourth option may be: Let everyone format things however they choose to format them, but insist that they run a code-beautifier on the code before submitting it. I believe that this would yield some good results...would it not?

Anthony Cuozzo on April 13, 2009 10:34 AM

I personally prefer tabs. If I want some whitespace, I'd rather hit one key rather than the mashing space a few times. I also like the spacing of tabs. I don't find it to be too wide or too narrow. I think a single or double space is not enough though. It makes it harder to distinguish formatting with larger chunks of code.

Everett on April 13, 2009 10:36 AM

Idon'tlikeusingwhitespace.It'sawasteofcomputermemory.

Joseph on April 13, 2009 10:38 AM

@Jayson P: What if you use an editor and not an IDE? :-)

Anthony Cuozzo on April 13, 2009 10:39 AM

If you find yourself in a disagreement about coding standards, its time to rewatch the oracle scene from The Matrix again. See how the spoon bends.

(btw captcha is still orange)

fschwiet on April 13, 2009 10:41 AM

The best of both worlds:

http://nickgravgaard.com/elastictabstops/

Now we just need product support...

Jonathan on April 13, 2009 10:47 AM

We just went through this where I work last week, but our discussion was more around some people not using indention at all! Very hard to read their code. So I would be happy as along as it was indented in some way shape or form.

Jacob on April 13, 2009 10:51 AM

@fschwiet: captcha has always been orange

Nicolas on April 13, 2009 10:51 AM

today's IDEs take care of this problem, and you can't tell the difference between tabs or spaces anyway

Eber Irigoyen on April 13, 2009 10:51 AM

I personally like Spaces... but over the years I've gone from 3 spaces (which I was instructed to use by a professor) to 4 space since I thought it looked cleaner, to 2 spaces (since 4 spaces makes it hard to print code sometimes).... the problem is now I have code with a mix of the three... hence now, I'm moving to TABS. TABS work great in that most popular editors have preference settings related to how many spaces to use when representing a TAB, this way if one developer likes to look at it with 2 spaces and another with 4... the TAB is displayed to the developers liking. Yes this makes my VIM screen a bit hard to use at times... but that is only since I haven't taken the time to set my preferences there yet.

nick on April 13, 2009 10:52 AM

however, using spaces is a dumb waste of time

Eber Irigoyen on April 13, 2009 10:52 AM

Just wait until your code gets double-spaced because revision control is configured incorrectly...

asdf on April 13, 2009 10:53 AM

As I started reading this article, I was amazed at the huge gulf between the insignificance of this issue compared to the huge significance of the ethical standards in this codinghorror post: http://www.codinghorror.com/blog/archives/001253.html

Then I finished reading the article. Now I think this issue is important. I'm so confused. *sniff*

On the bright side, its nice to have had my perspective changed about something so early on a Monday morning. What a great way to start the week.

Knowist on April 13, 2009 10:54 AM

Seriously. If you use spaces, you're telling everyone else in your team how they should see the code. If you use tabs, they can decide, with their editor of choice, how to see the code.

Personally I like a 2 char wide indent. I realize that isn't enough for some people. Tabs solve that problem!

Using spaces is like hard coding syntax highlighting directly into the document. Evil!

Of course I only have a preference with the initial indentation. If you're trying to make comments line up at the end of several lines of code you're doing it wrong.

Ryan on April 13, 2009 10:57 AM

I really wish the IDE would just abstract out the formatting so it looks to me like i want and to you like you want. (For langs where whitespace doesnt matter that is). Hell, that concept could even be moved to variable names.

brad on April 13, 2009 10:57 AM

The only programming project with no disagreement whatsoever on code formatting is the one you work on alone.

Unless you work alone on the same project for several years. Then you'll be cursing the idiot who wrote this poorly formatted crap several years ago. And have only yourself to blame.

Will Shaver on April 13, 2009 10:58 AM

You can usually control with your IDE the size of a tab, but you cannot adjust the size of 4 spaces. A tab is just an abstraction that says 'indent one level' and leaves it up to you to decide what an indent means.

Spaces are almost like hardcoding values in your code.

Kamsar on April 13, 2009 11:02 AM

I used to use tabs. I still do, but have vi expand them to 4 spaces. Because a guy I was working with liked Emacs, and he was using 4 space tabs too, but my real, saved tabs looked like 8 in Emacs.

Of course if you want to be green (all the rage these days, until the taxes kick in), a tab takes 1 byte, and spaces take as many as you've defined tabs to be, so you're using extra disk space w/o tabs. And when you fill disk, you need another one = more power. When you read file, you have to read more bytes = more CPU, more physical memory, more energy usage. Then again, expanding tabs takes CPU power too...

Oh, woe is me. Nah, really I could care less.

A more fundamental issue is the one of how a function opening should be declared. Old hands will tell you that you put the function return type on one line, and the function name on the next (in column 1). Because that makes it real easy to find the function declaration vs. a mere invocation of the function. But so many people use these fancy programming environments that they don't care. Many of them don't even know how to use a decent text editor. They think nedit is state-of-the-art, when in fact nedit is about as powerful as M$'s notepad.

And they are helpless without the aid of really bad colors showing them what's a string, what's a function, etc.

As a vi aficionado, it irritates me that the latest vim has stupid features to cater to the lowest common denominator. Auto comment continuation is OK, but why make that the default? Colors are OK (not for me), but make that an option they have to turn on if they need that kind of hand-holding. I'm about ready to return to nvi or the original ATT vi to get away from the bloat-ware that vim is becoming.

I have seen young people use they up-arrow key 15 times to find a previous command that was 5 characters in length. Like retyping a command is hard. Or using the search feature inherent in every command line shell (other than anything from M$).

Sigh. I guess I am getting old and cranky.

El Bob on April 13, 2009 11:05 AM

1. The Tab key is a quick way to enter a specific number of spaces. Most 'decent' editors will substitute the spaces for you, so your document doesn't actually contain any tab characters. (If you like tab chars stored in your programs, print a big C program that has tabs in it.

2. Jeff's professor was right, 3 is the correct indent size. Two ain't enough, and four's too many. Besides, 3 fits exactly under
If xxxx.

Dan on April 13, 2009 11:06 AM

As a senior software lead, I can personally attest to spending many hours doing nothing but code cleanup...out of self-defense!

Why do I say self-defense? Because I know damn well that I'm responsible for getting the product out the door. And when it's 2:30 in the morning on the deadline day, the LAST thing I need is to discover a crash bug in a piece of code that:
1) wasn't written to the company's coding standard.
2) was written with variables like a and f everywhere.
3) mixes tabs and spaces to such a degree that it's simply not possible to line up anything at all.
4) has been hacked upon by so many other engineers who were simply too afraid of pissing off everyone else to take a few minutes to reformat the damn code so I, at 2:30 am, could make sense of it.

While I enjoy the friendship of my fellow workers, I have to remind everyone that when you work for a company, you're not there to make friends and be sensitive to other co-worker's feelings. If the company has a coding standard, and you're not adhering to it 100%, you'll get no sympathy from me when your code gets mercilessly reformatted to adhere to the coding standard. And don't cry about it; Learn from it and be thankful that your senior software lead didn't come down on you like a ton of bricks.

I know this makes me seem like a heartless draconian beast, but I promise you that you too will side with me the first time you are forced to pull a 36+ hour stint wading through horribly formatted code while hunting for that last crash bug.

Oh, and as for tabs vs spaces, I really couldn't care less as long as the company/team has an established coding standard. (Say, 3-space tabs or whatever.)

John W on April 13, 2009 11:09 AM

Even if your editor inserts spaces when you press tab won't you need to press backspace four times to unindent, or is it smart enough to see that?

I don't know because I've always just used tabs, I've never seen a reason to do otherwise. After all, what else would you use the character for?

Bill on April 13, 2009 11:10 AM

That said, only a moron would use tabs to format their code.

Thank you! Long live spaces! ;)

Matthew Morgan on April 13, 2009 11:14 AM

How about this: if your code repository lives on a Unix-y system, every check-in is automatically run through the indent(1) utility with the appropriate options for the project's coding style:

http://en.wikipedia.org/wiki/Indent_(Unix)
http://www.freebsd.org/cgi/man.cgi?query=indent

Most larger projects also have a style guide as well:

http://www.freebsd.org/cgi/man.cgi?query=style.Makefile
http://www.freebsd.org/cgi/man.cgi?query=style

http://lxr.linux.no/linux/Documentation/CodingStyle
http://kernelnewbies.org/FAQ/CodingStyle

http://developer.gnome.org/doc/guides/programming-guidelines/code-style.html

There should be sample configuration settings for a variety of editors that are being used by the team ((X)Emacs, vi(m), etc.).

David Magda on April 13, 2009 11:16 AM

That said, only a moron would use tabs to format their code.

* unless you happen to be programming in whitespace or Python.


The python style guide PEP 8 actually says to prefer 4 spaces per indentation level; however, the python code base doesn't follow these rules very carefully.

I've worked at exactly one organization that had a style guide they stuck to religiously. Other places *have* style guides, but:
1. No one actually reads them.
2. No one takes the time to convert legacy code to the new style, even if it's just a change in indenting that could be automated.

Personally, I *did* find that a uniform style guide made me more productive at the one place that used it. I didn't agree with all elements of the guide, but when I could count on everything being in a specific format, I could read other people's code much more easily. It also helped that comment formating was standardized and that function contracts were required.

I think that the real solution is that language designers come up with a style guide that just comes with the language and is used by all standard libraries. Java does this, and people are much more likely to follow the java style guide than they are to follow a coherent style in a language like C++ where there is no standard style.

Brendan Miller on April 13, 2009 11:19 AM

I don't understand the footnote-- in Python you still have the option of tabs or spaces. Code just needs to be indented consistently.

It it, however, recommended to use 4 spaces per indentation level.

Peter Beardsley on April 13, 2009 11:21 AM

Death to space-indentation!
Long live tabs!

Ethan on April 13, 2009 11:23 AM

But seriously, tab *means* indent. It has a semantic value. Space is a word separator... hence why you need an ugly hack like a bunch of them in a row to approximate an indentation.

With tabs, there's no half-indentation. It's simply impossible. With spaces, when you're coding in a hurry it's easy to get some off-by-one issues that aren't quite noticeable but get irritating.

Just use tabs: saves bytes, saves user layout preference, saves time, saves sanity.

Ethan on April 13, 2009 11:26 AM

Even though you *can* use tabs in python, I'd like to point out that PEP 8 declares that spaces are preferable (unless dealing with a legacy project that already uses tabs). PEP #8 is an interesting read in its own right, and is pretty relevant to this topic:

http://www.python.org/dev/peps/pep-0008/

Of course, PEP 8 is just the recommendation for the standard library - you can do whatever you want on your own projects (except for mixing spaces and tabs!). That said, I personally follow PEP 8 when I don't have a compelling reason to do otherwise - I figure I could do a lot worse than emulating Guido!

Jeremy T on April 13, 2009 11:28 AM

...Shneiderman found that when program statements were arranged in a sensible order...

... When statements were shuffled, the experts' superiority was reduced.

From what you've shared, it seems more like the study was on formatted and non-formatted code, not much in the nuances of different formats.

Instead of spending time to convert everyone else to our beliefs, we should try to be as open as possible. The more focused on our own we become, the likelier we are to stop learning, and become stagnant. The more styles we are influenced by, the better we can become at adapting, scrutinizing and imitating.

Bauski on April 13, 2009 11:29 AM

ok,
let me get this straight. DID JEFF ATWOOD JUST CALL ME A MORON?
seriously, a one who grew up on C, (which jeff did/could not)
i found it easier to press the tab key once and continue typing
instead of the two or more times required for the friggin spacebar.

i also found that if one is a meticulous geeky coder that most
of us are, WE TAKE THE TIME TO CUSTOMIZE EACH AND EVER PC WE SIT
AT AT AND CHIEF CUSTOMIZATION IS FIXING THE FRIGGING EDITOR SO THAT
TAB MEANS WHATEVER WE WANT IT TO!!!

that said, i am a moron so i could be wrong. tab is for look, space
is for syntax my dear GWBASIC-programming-none-C-learning-copy-and-paste-programming-so-must-use-spaces-CODE-NAZI!!!!!

jake on April 13, 2009 11:31 AM

Let the team decide. The only rule I have is that once it's decided, it's used consistently. In my group we all set our formatting rules in Visual Studio to the agreed upon settings. Then it's simply a matter of Ctrl-K, Ctrl-D to format the code consistently. I've even added a macro that in addition to reformatting, also updates the copyright header and sorts/organizes using statements (C#).

http://blueonionsoftware.com/blog.aspx?p=e40c1a15-6461-4224-b020-c66101bd07ba

Mike on April 13, 2009 11:32 AM

I'm still waiting for the time when your favorite IDE and SCM will take care of the coding styles, allowing different views for different programmers. This might be possible using metaprogramming frameworks with a model view on your code in the same way as a model view on your diagrams, eg. Janus MPS (as a mostly unrelated example).

This should NOT be an issue a programmer has to worry about.

Moritz on April 13, 2009 11:39 AM

To paraphrase, the solution to almost all problems in computing programming is another layer of indirection. Some people prefer 2 spaces for an indent, some prefer 4, some prefer insert n. Having an indent character is just another layer of indirection that lets the user interpret what indent means. We just so happen to use the the ascii 0x09 as the indent character. There is as much reason to insert a specific number of spaces as your indent as there is to sprinkle your code with magic numbers. Barbaric...

Mr. Simplex on April 13, 2009 11:44 AM

I never cared much about spaces vs tabs. What I do care a lot is:

int main() {
return 0;
}

versus

int main()
{
return 0;
}

I like the first example a lot more than the second. The vertical space saved is good and the clarity of the second is not that much greater since the identation already makes that block more visible.

Hoffmann on April 13, 2009 11:47 AM

I like tabs because I find easiest to move around the code with the keyboard.

If I have to press 8 times the arrow key I get mad and grab the mouse to take the cursor where I want.

Antonio on April 13, 2009 11:47 AM

a coworker says, People that columnize the code like tabs.

Where's the article about the evils of columnizing variable declarations and assignments. I just think its harder to read each line, depending how far the spacing is could map the wrong value to the variable when reading, also requires the regex search instead of the simple myvar = version which is really less of a problem now days with the find all references feature.

CrashCodes on April 13, 2009 11:47 AM

Let me put it in few and simple words: If you are worried about tabs contra spaces, you are using the wrong tool. Stop living in 1988. If your development environment is so ancient that this is a valid point of debate, you ought to give up programming and move into a retirement home.

J. Stoever on April 13, 2009 11:53 AM

I don't care, as long as everyone on the team uses the same.

To avoid a holy war, my team agreed on the default settings of our IDE (Eclipse).

Charles on April 13, 2009 11:54 AM

Use a format nazi tool like StyleCop and don't allow check-ins unless code passes all its rules. ;)

Joe Chung on April 13, 2009 11:54 AM

That said, only a moron would use tabs to format their code.

Yeah, but I like 2 spaces. 4 is just stupidly wide.

If lovin' tabs is wrong, then I don't wanna be right. Please cancel my subscription.

Amorphous Blob on April 13, 2009 11:57 AM

It would be easy enough to automate the formatting rules for a project. Parse tokenize, format, overwrite. You could also fix block formatting, operator spacing, etc. If there is a standard, you can auto-enforce it.

Justin on April 13, 2009 11:58 AM

Color of the bikeshed anyone? It's amazing how we developers like to argue at great length about th most trivial crap. http://en.wikipedia.org/wiki/Color_of_the_bikeshed

CT2 on April 13, 2009 12:00 PM

This feels so wrong to say, but tabs or spaces depends on the project, the language, and the coding environment. All the languages and IDEs I use are tab friendly, so I'm with the folks that think using spaces interferes with other people's preferences in viewing the code.

But on the topic at hand (and not just the flagrant comment baiting) it really doesn't matter what the conventions are as long as they're followed by the team. Automated code style translators are an extra layer of hassle in a project. Do they work? Are they introducing bugs? Who cares. Just agree on a style and get on with your day. With a clear standard to follow nobody should be bitching about having their code cleaned up.

Dave Cobb on April 13, 2009 12:01 PM

More comments»

The comments to this entry are closed.