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..
or with tabs?
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:
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.
Another time first :D
The third option will be interesting, as it enables me to see the break line clearer, sometimes it's confusing.
And then there is the editors that simply convert a tab keystroke into 4 spaces. Voila, argument avoided.
klietus on April 13, 2009 9: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 9:28 AMI 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.
"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 9:33 AMI 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 9:34 AMA 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 9:34 AMI think spacing/tabbing should be controlled by the IDE. I couldn't live without the "Correct Indentation" function in Eclipse.
This way it doesn't matter which how to format your code. Just make sure to hit Ctrl-I before checking in :)
Jayson P on April 13, 2009 9:35 AMI 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 9:36 AMIdon'tlikeusingwhitespace.It'sawasteofcomputermemory.
Joseph on April 13, 2009 9:38 AM@Jayson P: What if you use an editor and not an IDE? :-)
Anthony Cuozzo on April 13, 2009 9:39 AMIf 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 9:41 AM@Anthony: Then I guess youíre out of luck, but thereís always the option of popping your code in an ìauto-indentî aware IDE or editor.
Some of us are just too attached to console editorsÖ
The best of both worlds:
http://nickgravgaard.com/elastictabstops/
Now we just need product support...
Jonathan on April 13, 2009 9:47 AMWe 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 9:51 AM@fschwiet: captcha has always been "orange"
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 9:51 AMI 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 9:52 AMhowever, using spaces is a dumb waste of time
Eber Irigoyen on April 13, 2009 9:52 AMJust wait until your code gets double-spaced because revision control is configured incorrectly...
asdf on April 13, 2009 9:53 AMAs 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 9:54 AMSeriously. 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 9:57 AMI 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 9: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 9:58 AMIf you have a standard formatting method for when code gets checked in, can't you automagicaly transform from your preferred method to 'team compliant' and of course from team compliant to your preferred?
Don't IDE's do this for you already?
Spoon on April 13, 2009 9:59 AMYou 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 10:02 AMI 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 AT&T 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 10:05 AM1. 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 10: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 10:09 AM>> That said, only a moron would use tabs to format their code.
Thank you! Long live spaces! ;)
Matthew Morgan on April 13, 2009 10:14 AMHow 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 10: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 10:19 AMI 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 10:21 AMDeath to space-indentation!
Long live tabs!
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 10:26 AMEven 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 10:28 AMMake sure everyone on the team has the same tab/space settings in the IDEs, otherwise version control and code reviews are full of nonsense "changes."
Also makes it easy to change your mind later if you use a tool that can auto-format. Personally I don't like auto-format but I have to admit it increases overall project readability and reduces changes in version control.
Jason Cohen on April 13, 2009 10:29 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 10:29 AMOh, and if your IDE's whitespace (and other formatting) isn't sophisticated enough to do what you need and share with team members...
...invest in a real IDE. Notepad is not a code editor. :-)
Jason Cohen on April 13, 2009 10:30 AMok,
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!!!!!
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 10:32 AMI'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 10:39 AMTo 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 10:44 AMI do religiously format other people's code. But not to *my* style preference, but to a specific coding standard [0]. This lead developer *is* leading by example. He's making an effort to increase the overall readability and maintainability of the code. The way the paragraph is quoted makes it seem like the lead developer was merely changing things on his own accord and preference -- which would make for an excellent TDWTF -- but something tells me he wasn't.
[0] The real problem with style standards is that most programming languages don't have a single, authoritative oracle. And, naturally, everyone has an opinion. Fortunately, in C#, such a standard exists and its enforced by StyleCop. I spent a lot of time pushing for people to write style compliant code. And any great developer immediately sees the value in having a CONSISTENT codebase.
Consistency trumps personal preference (even my own) when I write code. This is what ought to be taught. Not just tabs vs. spaces.
Navid Azimi on April 13, 2009 10:44 AMI 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 10:47 AMI 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 10:47 AMa 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 10:47 AMLet 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 10:53 AMI 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 10: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.
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 10:58 AMColor 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 11:00 AMThis 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 11:01 AM> 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.
I don't feel like paying the $34 required to find out for sure, but it doesn't sound like that study has anything to do with code formatting. It seems to be describing statement reordering. Or is the snippet misleading? Because if it's about reordering lines of code it doesn't support your thesis at all.
Gordon Barber on April 13, 2009 11:11 AMFor all of my programming I personally use tabs. For projects at a corporation where I work we also use tabs.
Spaces just complicate the matter, my text editor is smart enough to recognise 4 spaces as a single tab if I have set 4 spaces as my tab size (generally set to 8, that way I know a code block is too big if the lines are longer than the default width of my editor.
Using spaces just seems absolutely wrong, yes there is less issues about code formatting being displayed on someone elses computer and or IDE, but at the same time it is forcing them to accept the fact that you want 4 spaces for indents, what if they prefer 8? Tabs can be given any markup. spaces already have one pre-assigned that can't be changed without drastically altering the way the rest of the code looks and lives.
Bert JW Regeer on April 13, 2009 11:12 AMIn my team we have agreed to use TABS with indent size equal to 4. I'm really like double spaces, but we decided to use default IDE settings for C++ code. We have to use 26" FULL HD displays since then and everyone seems to be happy.
There is no difference between using TABS and Spaces until every developer use the same indent size.
There are some files (YAML for example) that require space-indenting. As far as I know there are none that require tab-indenting.
Space-indenting is absolute. Tab-indenting is relative to the editor.
For these two reasons, which can be combined to one - consistency - I prefer spaces.
BTW a good editor can convert tabs to spaces for those addicted to the tab key.
Demi on April 13, 2009 11:21 AMAs said multiple times above: the tab character is a welcome bit of indirection.
IMHO, I like the third style (mixed spaces and tabs), although I try to avoid instances where that becomes necessary.
The ONLY space where indentation width matters is when trying to align multiple columns together such as in a convoluted if (...) test with a dozen conditions and subconditions. There, spaces make a lot of sense, because they make that essentially fixed-width. Although, I'd hasten to add that if you don't use a monospaced font (ah, that *other* religious war ...) tabs make more sense here again.
IMHO, though, tabs could still be used every time. Yes, convoluted if statements end up looking ugly when you go from one tab size to another, but in keeping with the last post and numerous others, bad code should *look* like bad code. I'd rather see the semantic cohesion which had been applied with whitespace instead affixed in the code; break up the multi-line if statements into multiple tests, and change the signature of your library method from requiring 27 parameters to taking a couple data objects.
Primary arguments for tabs:
1. Fewer characters to type on every line / indentation. Most editors auto-indent for us, and some properly auto-unindent, but if you care about most of the arguments for using spaces, this is just as viable.
2. Impossible for alignment to be lost. I have a few developers on my team who use 4 spaces instead of tabs, and nary a week goes by when I don't find a block of code that got indented by 3 tabs or 5 tabs instead of 4. Granted, if you are using the IDE for indentation (use the tab/shift-tab indent/unindent instead of space/backspace multiple times) you don't hit this issue. But, I find it incredibly rare to find space-loving developers who do this.
3. Reformatting for print or other viewport sizes is easy and built in to any decent text editor. I routinely compress/expand my indentation when getting a better look at code or printing it out. On my laptop's screen horizontal real estate is far too precious to be wasted on indentation; on my dual-screen desktop nice wide indentation settings keep code scannable.
57 comments and nobody has mentioned ... drum roll ...
StyleCop.
-- J
Jeremy on April 13, 2009 11:34 AMOf course, the real issue here is that the visual representation is inextricably tied to the actual code. If editors operated on ASTs, we wouldn't be having this discussion...
Yes, you can't edit it with emacs anymore. I'll cry for you. Heck, I'll even throw in an XML version for free - go edit that.
Actually, now I'm seriously wondering if you can format code using nothing but XHTML and CSS... ;)
Rachel Blum on April 13, 2009 11:36 AMI have my own preferred style (2-space indents, opening braces on same line) but when working on a file with a majority different format I always simply adapt my code changes to that format. Not a big deal and it maintains consistency *at least per-file*.
dtr on April 13, 2009 11:36 AMIf a team specifies spaces then they must also specify and enforce the standard number of spaces or nothing will line up after multiple edits from other devs or it quickly becomes the mess you sought to avoid.
If a team specifies tab then anyone can, in almost every modern editor, specify their own 'tab size' and 'indent size' and it will not only appear consistant but in the preferred format of the viewer.
While you believe that anyone who thinks using tabs is a moron, IMHO I believe anyone who prefers spaces is a noob.
Pete on April 13, 2009 11:36 AMMeh, and to think I once respected you as a programmer Jeff. By using spaces you violate two important ideas:
1) Tabs are designed to indent. That is their function.
2) Using spaces instead of tabs is the same as embedding CSS in HTML. You're forcing markup into places it shouldn't be. If you like 2 spaces, then set your IDE to show tabs as 2 spaces. Don't force your preferred indentation on others who might prefer 3 or 4 spaces.
Tabs vs Spaces has been a non-argument for the last 10 years. We're not programming over teletype anymore.
Nick on April 13, 2009 11:37 AMAnyone who says "tabs are sufficient" has not understood the problem as shown in the "third option" example above. Had that example been done with tabs only, the "string s" would not correctly align for people who used a different set of tab stops. Think about it.
No matter which side you're on, clearly sometimes spaces are needed. But I agree with Jeff, there's never a need for a tab.
Anyone who says "I hate pressing space multiple times" does not understand that nobody does that--we all press tab and the editor inserts spaces.
Yes, every IDE lets you set your tab stop to whatever you want. But do you always use your IDE? I read more code than I write: I use three different tools that do diffs for me: the p4 diff, the Code Reviewer diff, and Beyond Compare. I bring up code in notepad++ sometimes, I email code sometimes, I format code in a wiki sometimes, and I print code sometimes. Even if it's possible, I don't want to set my custom tab stops in all of these tools. Spaces are consistent.
I don't get it. Modern IDEs (at least mine does) enable you to specify the "correct" formating of spaces, braces and other mission critical formating rules. So each developer can in fact see a different view of the same code. Provided you use tabs and spaces for their intended purposes...
Why is this still an issue?
I'm a big fan of editors that convert tabs to spaces. Also, absurd though it sounds, I was quite impressed with the idea of combining tabs and spaces to properly align the code independently of indentation, that was a neat idea.
I guess the hardest part about all of this is not so much choosing a style as it is keeping that style consistent among your teammates. I actually have less issues with the tabs vs spaces issue, that I can fix. I find the most disagreement over where the opening and closing brackets should go. I always do this*:
if (condition)
{
statements;
}
but a lot of people like to do this*:
if (condition) {
statements;
}
which I find a lot harder to read. This is where I've found that auto-formatters are *great* for reading other people's code. I could care less what the variables and things are named, but an auto-formatter at least gets it somewhat into a structural form that I would use myself, which makes it a lot easier to read. I would recommend one to anyone who does a lot of code review, because once you have it tailored to your own style it really is a godsend.
*there should be a tab or 4 spaces in front of the "statements" but I'm not sure they're going to keep when I post this.
Nicholas Flynt on April 13, 2009 11:44 AMYou don't know the true joy of format wars until you use a graphical programming language...
Underflow on April 13, 2009 11:53 AM>One of absolute worst, worst methods of teamicide for software
>developers is to engage in these kinds of passive-aggressive
>formatting wars.
It's hard to say from this little anecdote what's going on here, but in my experience, this sort of thing is almost always about more than just spaces/tabs/conventions. Unfortunately, to the less-experienced coder (and original author), changes to his code often just look like useless "cleaning." But I'd bet that senior guy called it "refactoring."
Yes, I'm one of those senior people who sometimes refactors someone else's code, so call me evil. But once the code goes into the project for which I'm responsible, it's officialy "our" code. And as "that guy," let me say that if a piece of code works reliably and exposes a sane API, I'm certainly not going to waste my time wading through it to pick nits with internal variable names or spacing.
No, the only times I've come in and "cleaned" code, it has always started by pulling on a thread: a bug, an API problem, a namespace collision, something. Once inside, sometimes the only way comprehend the issue is to engage in a little refactoring to expose the code's structure: making functions orthogonal, giving variables sane names, and yes, even whitespacing the code according to standards. All this lets the senior guy understand the code, isolate the issues, and fix them. And when he checks in the code, it's just a little better than he found it, like a Boy Scout on a trail.
Unfortunately, sometimes the less-experienced guy doesn't see the merit, and that can cause painful ego-collisions. The good folks eventually figure out how to disassociate themselves from the code and learn from the changes. The not-so-good folks are often bent on protecting a code castle. (Perhaps having their code understandable and accessible by other team members works against their job security.)
In fact, anybody having email exchanges with Mr. Atwood is probably not one of those job security folks. Maybe the senior guy in this story just has a bad case of OCD and really does go around randomly whitewashing perfectly good code for pleasure. But I wouldn't assert that "code cleaning" is always "face stabbing." If the code is genuinely better for it, isn't that a good thing?
Back in the old days, a common freshman FORTRAN programming error was to use the TAB character. The code looked fine on the screen, but the compiler had all kinds of fits. My pals and I were confounded as to why retyping the offending line "exactly" as we had the first time--or by having someone else retype it--allowed the compiler to accept the code. It wasn't until a few years later, in the compiler design course, I could look back and understand what was going on.
Daniel 'Dang' Griffith on April 13, 2009 12:20 PMThe "rational" way to format, I think, is to use tabs. Then people who like 2-space indents can set tabs to 2 spaces, I can set them to 4 spaces, etc.
The problem is that every stinking editor out there has its own way of handling tabs and its own commands for setting them up, as Jeff pointed out. Invariably someone (possibly me) will mess up the formatting without really trying. So now I generally use spaces (4 for most indents). Still, it's kind of a shame.
A. L. Flanagan on April 13, 2009 12:21 PMAll right, I'm a dreadful code-cleaner. I'm constantly being confronted with hideously complex 100-line procedures, and I have to rewrite them just to understand the stupid things. My mind doesn't work in spaghetti logic.
In my defense, I usually get these projects after the original culprit is long gone (possibly fired). And I leave behind clean, comprehensible, documented code. But I've learned to force myself to ask "is this really worth it"?
A. L. Flanagan on April 13, 2009 12:24 PM@Goran: It's still an issue partly because a lot of shops don't use modern IDEs. The job I just left, a lot of code was written with vi. An old version of vi. Also if different people use different IDEs, things can get messy.
A. L. Flanagan on April 13, 2009 12:26 PMI prefer tabs, with a width of 4. I don't like a tab being replaced with spaces either, because when I accidentally tab once too many, I have to hit backspace 4 times to clear the spaces.
As for braces, I prefer
void main()
{
return 0;
}
It's all academic anyway really, whenever I get someone elses code and I don't like how it's formatted, I simply hit CTRL-A, CTRL-K, CTRL-F to have visual studio reformat the code according to my preferences.
Boingle on April 13, 2009 12:30 PMThe universal assumption in all the discussion about tabs vs spaces seems to be that your text is always viewed in an editor where you can configure your tab width preference. But what about command line output, like more, grep, etc. This happens to be a predominant use case for me on any project, and tabs cause all kinds of chaos for that. Long live spaces!
Chris Noe on April 13, 2009 12:35 PMI would just like to point out the contradiction between the name of this post and the comments at the end. Is it that you can't make up your mind yourself or just got so confused in what you were writing that you couldn't pick a side?
G on April 13, 2009 12:47 PMI'd like to be all nice and liberal and say that it doesn't matter. However, I work on a team where everybody uses a different editor (either the one they worked on before they joined up, or the one their assigned buddy taught them). The fact is that not all editors support the basic indentation rules, be they tabs of 4 or 8 spaces, or just plain spaces. Some people customize their tabstops, others don't.
I set my editor to indent with spaces, which makes my code easy for anybody else to read, but when I read other peoples' code the indentation is impossible to read because they use different tabs to get the indentation right on their editor. Sometimes I just break down and reformat the whole file because otherwise it sucks too much.
To those who don't want to hit the space bar many times, with any decent editor (vim in my case) should indent your code for you as you type, so there's no need to hit the tab key or press the space bar 4 or 8 times per indent level. That's a non-issue .
Nathan Fellman on April 13, 2009 12:47 PM@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 1:03 PMQuoting 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 1:27 PMTheoretically, 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 1:29 PM@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 K&R 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. K&R 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 K&R should be rare.
Ens on April 13, 2009 1:32 PMThat 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 1:46 PMIf 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 1:50 PM1. 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 1:51 PMI 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 1:58 PMIf I try to analyse your post as a formal, logical argument
(http://en.wikipedia.org/wiki/Logical_argument), I get the following:
Premise 1: The tab character can be expanded differently in different editors.
Premise 2: Formatting code uniformly is very important for program comprehension.
Conclusion: You should not use tab.
Right? As quite common in logical arguments, there are some missing
premises. The conclusion is in no way valid without also including
the following:
Premise 3: Using tab will make the code display un-uniformly.
As you discuss in your post, indentation can be handled in three
different ways,
a) indentation is X spaces
b) tab is X spaces
c) indentation is tab (expanded to whatever number of spaces you prefer), alignment is space
where premise 3 is true for a) and b) but false for c). Since premise
3 is not always true, this means also that the above conclusion is not
always true.
Discussing premise 1 and 2 is almost like kicking in open doors;
there is no controversy with those. The controversy occurs when someone
decides "we shall have such and such indentation behaviour" and that
conflicts with the preferred display preference of some of the developers.
Specifying this as premises gives:
Premise 4: People have different preferences on what the optimal width of indentation is.
Premise 5: Reading code with a different indentation width than your preferred makes the code harder to read.
and the the complete "argument" then becomes
Premise 1: The tab character can be expanded differently in different editors.
Premise 2: Formatting code uniformly is very important for program comprehension.
Premise 4: People have different preferences on what the optimal width of indentation is.
Premise 5: Reading code with a different indentation width than your preferred makes the code harder to read.
Decision 1: Mr/Mrs/Miss/Group X decides that indentation is X spaces.
or Decision 2: Mr/Mrs/Miss/Group X decides that tab is X spaces.
Result: The code becomes uniformly formatted, but is harder to read than optimal for some of the developers.
I put argument in quotes and use result instead of conclusion since the
decisions are based on taste/personal opinion and this is not a proper
logical argument any longer.
In some cases this might be a fair enough strategy; it might be impossible to
make everyone happy. This consistent with what you write in your paragraph:
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.
However, in some way this also signals "screw those developers that have
a different indentation width preferences", and as the observant reader
have noticed there is a third possible decision which will make everyone
happy with regards to reading the code (although possibly not for writing
(but this is irrelevant)).
Consider the relation between reading and writing code. Code is written
in the range of 1-10 times by one person (including some editing and
possibly pair programming). It can however possibly be read by tens (or
hundreds/thousands) of other people, several (maybe hundreds of) times.
This gives that having code that is easy to read is several orders
of magnitude more important than code that is easy to write. I.e. how
simple or complex some issue is to write is is irrelevant if it increases
readability.
The overall goal of any formatting discussion is to increase readability.
In fact that is the only important factor, to let the code be readable.
As written in the preface to the first edition of SICP: "Thus, programs
must be written for people to read, and only incidentally for machines
to execute.".
The best result is therefore to write the code so that everyone can
use their own preferred indentation display width without forcing this
upon others.
Premise 1: The tab character can be expanded differently in different editors.
Premise 2: Formatting code uniformly is very important for program comprehension.
Premise 4: People have different preferences on what the optimal width of indentation is.
Premise 5: Reading code with a different indentation width than your preferred makes the code harder to read.
Decision 3: Mr/Mrs/Miss/Group X decides that indentation is tab, alignment is space.
Premise 6: Decision 3 makes the source code tab expansion width agnostic
and allow everyone to display the source code with their own preferred
indentation width.
Result: The code becomes uniformly formatted and optimal for everyone to read.
Side argument:
Premise 7: Easy to read is several orders of magnitude more important than easy to write.
Premise 8: Some people will feel that decision 3 makes the code difficult to write.
Conclusion: Premise 8 significantly less important than readability improvements and can be ignored.
Premises 1, 2, 4, 5, 6, 7 and 8 are always true. Always. Please verify,
try to think of some situation where it could be false (and should you
think you found one by all means let me know). Then verify my conclusions,
it could be that I have made some mistakes? However the only way I can
see that you should be able to reach some other conclusions is if I have
Ignored some premises. What should that be?
This is a dumb argument.
Who cares!
>> 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 2:26 PMAlways 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 2:50 PMI 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 2:53 PMI'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 3:01 PM>> That said, only a moron would use tabs to format their code.
<sarcasm>I'm glad to see your subtlety was not lost on this group...</sarcasm>.
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...
Problems at Stackoverflow code base or is it just from another situation?
Andrei Rinea on April 13, 2009 3:08 PM> 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 3:09 PMI 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 << works correctly.
Only morons use tabs? Them's fighting words.
Here's a suitable arena: http://wordwarvi.sourceforge.net
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_3d">survey: 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 3:36 PMfixed link:
http://www.surveymonkey.com/s.aspx?sm=CuOCMx8ZkrpzKrEsWp0YpQ_3d_3d
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 3:48 PM@Joe Enos
Most people minify ( http://en.wikipedia.org/wiki/Minification_(programming) ) their html/javascript/css code.
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 4:03 PMI 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 4:08 PM@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.
Hey, anyone remember make? Just make sure that tab is a tab, not a bunch of space, hehe :)
Oldster on April 13, 2009 4:10 PMTabs. 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 4:26 PM@Bill:
Variable-width font in code? You'd have to be smoking some serious stuff if you're using that.
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 4:42 PMI 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.
"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 4:47 PMHere'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 4:55 PM*[...] or MUMPS. (BTDT).
trurl on April 13, 2009 5:02 PMWho 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 5:07 PMI 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 5:39 PMIf 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 5:45 PMHow 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 6:02 PMThere'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 6:27 PMTabs. I'm going to try the Tabs + Spaces example.
Zoasterboy on April 13, 2009 6:28 PMHaven'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 6:52 PMI 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;
}
(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 7:13 PMIn Eclipse,
ctrl+alt+space (tabs -> spaces)
or
ctrl+alt+tab (spaces -> tabs)
Walla!
zefi on April 13, 2009 7:16 PMSince 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 K&R 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)
spaces < tabs
Mainly, why press a button 4 times when you can press it once?
reg4c on April 13, 2009 7:44 PMTab 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 8:06 PMAs 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 8:20 PM@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.
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 8:43 PMEven 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 10:10 PMWow!
This is still an issue for lots of people. However, I gave up reading what everyone else said after the first 20 comments or so. Too much!
I am a team leader with a penchant for performing reformatting of non-compliant code. I only do this when I am trying to understand the code in question. We have a style guide which is ignored by one individual in particular. He doesn't think its important since the "computer doesn't run source code, does it".
This used to bug the hell out of me a year ago but I have matured now.
These days, I no longer inspect his code more than others. I still do reformat checkins if I find non-compliant code when I am trying to understand something that needs changing.
I am 45. I believe that tabs are the right way but WTF do I really know. After all, I've only been doing this for 20 years. I stick to the org's coding policy even if it is insane.
FWIW, my definition of insanity is:
* only use spaces
* 2 space indents
* 8 space indents
I prefer 4 space indents have this is what we have at my current place of employment.
We also have a 2 blank lines between methods rule which helps separate things out a bit. We like it. Other orgs might not.
Now, if you *really* want to get me going we should have a chat about how equals signs in blocks of code handling alignment should be handled.
:-)
Gordon J Milne on April 13, 2009 10:18 PMOops! Typo time.
What I meant to say was:
Now, if you *really* want to get me going we should have a chat about how equals signs in blocks of code handling *assignment* should be handled.
:-)
Gordon J Milne on April 13, 2009 10:20 PMUse a "format nazi" tool like StyleCop and don't allow check-ins unless code passes all its rules. ;)
Joe Chung on April 13, 2009 10:54 PM@jake
absoulutely..rite...
i think those who use spaces are morons...
So it shud be said like this by jeff
That said, only a moron would use spaces to format their code.
UNKNOWN on April 13, 2009 11:41 PMUse a combination of two tabs and two spaces for every indentation and everyone is happy.
Herman on April 13, 2009 11:44 PM@herman..
then why isn't everyone happy?
UNKNOWN on April 13, 2009 11:47 PMTabs are better because they don't take as much space. Plus there is the possibility that you commit only tabs, and then in IDE you can adjust how many spaces long you want a tab to be. That way if I like 2 long tabs, then fine, I use that. If you like 3 long tabs, then fine, you use that. But in version control it is just a tab.
Anyways I think there should be a one coding standard, and if it is not as good as I want, I want to change it, of course. If there is some lead developer who can say what kind the standard is, then I say my objections or change job, but that's it. Having a fight over it isn't worth it.
Silvercode on April 13, 2009 11:50 PMI indent my code with spaces, but I'm lazy so I wrote a macro that automatically inserts spaces when I press the TAB key.
chipset on April 14, 2009 12:18 AMguys, guys guys,
look at the title of this post. then look at how he closes.
this is clearly a guy who is at conflict with himself and
only posting flame-bait :-) thanks @jeff.
there was a time when jeff actually educated you or was insightful
(as opposed to "inciteful")now, lately, he just writes cleverly
worded stuff to provoke debate.
@jeff,
insert picture of self with pinky to chin pose
or any other graphic that shows you for your true
evil genius
@jeff,
insert picture of self with pinky to chin pose
or any other graphic that shows you for your true
evil genius
@jeff,
insert picture of self with pinky to chin pose
or any other graphic that shows you for your true
evil genius
I actually don't understand the reason for using spaces. One of the points of contention between different programmers is how far they want to indent their code. Some programmers prefer large indents, some programmers prefer small indents. Using spaces, nobody will end up happy, but using tabs, everyone can set their own indent size. And for the places where you want to use spaces because you're not indenting scopes but characters, you still can.
What is the reason for wanting to use spaces? Can anyone explain?
LKM on April 14, 2009 12:41 AMhttp://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Formatting
"Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone's code easily."
Wow, lot of comments, as expected on such topic (that, and placement of braces...).
About the third option: there was (I hope the past is right here!) a choice of using tabs to indent by multiples of 8 positions, then use 4 spaces to fine adjust at the end. The worst of two world, IMHO.
There is also people forgetting to adjust properly their settings, so you end up with lines indented with spaces and others with tabs.
Personally I use tabs in my personal projects, and whatever the current convention is on the projects I work on.
I prefer tabs because they are compact, flexible (as LKM above points out), because I use mostly editors allowing me to adjust the width of tab (so that's a non-issue), because some dumb editors force me to hit backspace or left arrow n times to un-indent or go back of one level. Of course, my editor is smart enough to do what I tell it, to insert (or remove) tabs (of right size) or correct amount of spaces when I indent or un-indent.
I admit when I paste code in a Web page, I replace my tabs with two spaces (small amount to avoid horizontal scrolling, awful in a Web page, particularly with lot of lines) but it is quick and painless, without risk of mistake, the reverse is harder! And output on terminal is terrible too.
About savage code formatting: I admit I guilty. But that's always to make code conforming to in-house rules, to fix above mentioned mix of tabs and spaces (or bad indenting because of dumb auto-merge), follow our rules of naming (or fix typos / bad English sometime), etc.
As you point out, when a portion of code is unexpectedly formatted, it is a distraction: we see more the clunky formatting than the intended logic!
@Sleazey: BeyondCompare (shareware, Windows) lets you create sets of rules that specify what changes are important (marked red), less important (yellow) and non-important (not shown). You can then set it to use that particular set of rules to apply to certain file extensions (i.e. whitespace is important in my templates, but not in my code)
Jeff, you're an absolute noob, you know that? Yeah, let's all stop using tabs for indentation, because there are broken editors which support it poorly. Dumbass.
Then again, what to expect of people who write stuff like:
RidiculouslyDescriptiveClassName foo = new RidiculouslyDescriptiveClassName;
...and like it?
Pies on April 14, 2009 1:17 AMWe all have these superior compile-while-you-edit (i.e. intellisense) style IDEs and editors in languages like Java and C#.
So why are we still storing code in text form? Why can't we compile the damn thing into a code DOM and store the DOM tree as-is??
I means.... we don't have "bold" or "italics" or "embedded excel table" in code files, right? And then we can have all variable renames and extract method actions and whatnot as something recordable in source control.
And when we have that... naming consistency becomes easier to enforce/check.
I know it's not gonna be that easy... but we have had the ability to compile into byte code or an intermediate form in lightning speed (think classic VB) since... years?
chakrit on April 14, 2009 1:20 AMThis reminded me of the "Real Programmers" comic for some reason:
http://xkcd.com/378/
Not only an interesting post, but also a great title for a 1950s sci-fi short story!
Unfortunately anyone using spaces to format their code self-evidently has an important part of their brain missing so I can't read this blog any more...
Breakfast on April 14, 2009 1:42 AM'Anyone who uses 8-character-wide tabs is a madman'
Not if you program in 68030 assembly language on the Amiga (which is one of my hobbies). 68000 family instructions vary in length, and some are seven characters long, so eight character wide tabs are needed. It's a bit much for higher level languages, of course.
As has been said before, use editors which handle the whole tabs/spaces issue for you, and concentrate on writing code rather than formatting.
David on April 14, 2009 2:13 AMWhen working with other people, I use whatever convention there's already in place. At my work, we have rules (tabs of width 4, space after keywords, camlCase, whatever) and I abide. If I want to work on an open source project, I will write in whatever style is in use. I don't personnaly care for specifics as long as it's easily legible ! I do have a personnal preference for a certain formating (which I use on my personnal projects when I write *alone*), but I adapt to the environment. The main point here is : uniformity ! Most coders are able to read most conventions as long as they're sensible, but it's easier for your brain (or what's left of it) to have only one syntax to parse throughout a single project.
Then, I believe that most code editors can enforce a good deal of presentation rules (I might be wrong, I only work with Visual Studio), so people should use them ! Sure, it might be a pain in the ass to switch settings between project, but I think it's for the greater good !
Dongorath on April 14, 2009 2:27 AM> That said, only a moron would use tabs to format their code.
Unsubscribed!
Arielr on April 14, 2009 2:28 AMTabs for indentation, spaces for formatting. A very simple rule.
Tabs are 8 spaces. Fortunately, this simple rule makes easy to deal with heretics that set their editors to display tabs in less their 8 spaces. Unfortunately, ridiculous as it sounds, this simple rule is very hard to understand by most people. There was a flame on the vim mailing list about implementing "native" support for this in vim, but people found it hard to understand exactly what was it about and failed to see the advantages.
Aram Hăvărneanu on April 14, 2009 2:30 AMSo Jeff uses 'spaces' ... that speaks volumes
As for indent width, all kernel stuff I've worked on (*BSD, Linux, Mac OS X) uses 8 space tabs, so meh...
http://www.openbsd.org/cgi-bin/man.cgi?query=style&sektion=9
USE TABS FOR INDENTION!
Why? Jeff likes indention of 2 spaces, I personally prefer 4, some prefer 8. Indention is a matter of personal *taste*. Why would you force your personal taste upon other programmers? *That* is moronic. Especially in a wold of open source projects with hundreds of programmers, why would a couple of people decide upon a style and force it upon so many other coders, no matter how much this style will hurt their eyes?
When using tabs, every not completely useless code editor allows you to configure how "large" tabs are on screen. You can make it everything from 1 to 16 spaces, whatever you like. The same piece of code, indented with tabs, can make a 2, 4 and 8 space indention fan happy, since it will have exactly that many indention within his/her favorite editor.
Also a space is just a space. When programming, you never know what "meaning" a space has in this file. A tab, when exclusively used for indention, has a meaning though. It means "indent once" and two tabs mean "indent twice" and so on.
I agree with Aram, though. If you must "format" (layout) something, use spaces. Why? Because you must not rely upon the fact that a tab is equally "width" for everyone in the world as it is for you. And an alignment that works nicely when tabs are 4 spaces breaks terribly when they are 2 or 8 spaces!
I always and exclusively code according to Cyrus's 3rd option. I indent with tabs, that way everyone reading my code can have indention as big or small as pleases his/her eye. Nobody needs to like my style, change the config of your editor and have my code be presented in you favorite style. However, when I must align something, I cannot use tabs, so I use spaces. If you look at the Cyrus code sample in the post above... copy this to a file (and make tabs real tabs). Now change indention to 2 spaces, change it to 4, change it to 8. Indention changes each time, but the string is always nicely aligned below the int, isn't it? If you make this example all spaces, you cannot change indention (you must read it, no matter how "bad" it looks to you). If you make it all tabs, changing indention width breaks the alignment and "string" won't be aligned with "int" any longer. Using both does not give you the "problems" of both worlds as Jeff wrote, it gives you the BENEFITS of both worlds:
1) Have indention your way, whatever pleases your eyes
2) Have aligned text aligned, no matter how indention width changes.
Mecki on April 14, 2009 3:12 AMIs the code legible?
If yes, then stop willy waving about tabs vs spaces, and get on with something productive.
If no, then you probably have bigger problems to worry about than tabs vs spaces.
I use tabs to allow people to specify what size they prefer the indentation at in their editor. Also tabs are less typing and quicker to work with. Spaces are for morons!
Kale Kold on April 14, 2009 4:18 AMPhilip 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 remembers me of a joke:
The radio-broadcast says there is one "Geisterfahrer" on my Autobahn. But that's wrong, there are hundreds!
If the head of dev-department cleans up your code, you should worry, if you have not read the coding-guidelines. Or the head should instruct the clerks how to format right the first time.
It's of no good use, if everyone uses its own style for formatting, a bad standard is even better than dozens of different good standards ...
ì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.î
Couldnít agree more. This really should not be a matter of debate, and letting it become so implies the team lacks the leadership or discipline necessary to ever complete a project.
Personally, whilst I can see the principle of using tabs for their flexibility, I really suspect that spaces are the best pragmatic option. Itís just so much easier to enforce a no tab standard.
Hasn't anybody heard of Ockham's Razor?
"Pluralities ought not be posited without necessity."
This space/tab plurality exists because some programmer thought it would be a good idea to write code using tab characters instead of spaces. The compiler, ignoring whitespace characters, was able to compile the code, and the programmer was none the wiser.
Then along came office productivity software which allowed text to be indented with the tab key, to mimic the typewriter. But rather than inserting four spaces, the tab key inserted a tab character into the document. And a host of other ASCII characters were created--the vertical tab, the tab stop, the carriage return, the line feed, the escape character, the delete character--some of which have given programmers much grief.
And so I say, to HEX with your ASCII character set. Programming is not letter-writing. If my IDE would edit documents as if every set of four spaces were a tab character, and if it would insert four spaces when I hit the tab key, I would use spaces rather than tabs in my code.
Dan on April 14, 2009 4:36 AMUsing spaces to format code is like using opening Word and hitting the space bar a bunch of times to "center" something.
Craig on April 14, 2009 4:50 AMToo much white space is a problem for graphical language programmers as well.
PaulG on April 14, 2009 5:13 AMJeff argueing spaces over tabs is kind of a dumb thing to do, even worse than emacs vs vim.
I dont think the issue is only coding related. It was a dumb design decission in the early days.
"Lets make the computers have an extra space thats bigger than the regular space of about 8 characters but implementation can decide on the final length. And lets make it have a smaller key and call it tab so it looks like a whole new feature"
Tim on April 14, 2009 5:15 AMJeff:
Considering your past posts on efficiency in coding and space savings and "normalization," I'm surprised that you didn't consider the size difference of a file programmed.
Example: I recently took a small, ASP "filewatcher" program that used spaces, and entered tabs.. Result: 1.38kb for spaces, 1.22kb for tabs...12% savings in file size. It's not a big deal when you're talking "bytes" but in enterprise software, it could make a difference.
SammyB on April 14, 2009 5:41 AMwow, only 3 eclipse references.
why is auto-formatting (a next-next-generation editor?) such a big deal for the unwashed jeffs and followers?
I now know what Geisterfahrer means. :-)
Geisterfahrer on April 14, 2009 5:46 AMI can see a new set of adverts - maybe with Vin Diesel and Keifer Sutherland:
"I'm a TAB"
.
.
.
"I'm a space"
@Nicolas: captcha should probably change once or twice... it seems the Chinese spammers have discovered the secret power of orange...
Simon Wright on April 14, 2009 5:48 AM"captcha should probably change once or twice... it seems the Chinese spammers have discovered the secret power of orange..."
But the best way to train them not to do it, is to ignore their bad behavior.
Steve W on April 14, 2009 6:04 AMI think Jeff ought to include more a second version of each post that has mostly pictures and very few words so some of the readers can keep up.
I wonder if the spammers have figured out the "secret" of the capcha, of if they've just got some human typing it in each time.
AndyL on April 14, 2009 6:35 AMThose who say it doesn't matter as long as it's consistent are dead on. I have my opinions, of course, but the fact is that my eyes will adjust to whatever the coding standard ends up being. That said...
I'm really surprised by how many tab supporters there are here. I don't think I've ever run across another programmer who prefers tabs over spaces. I guess I can sort of see the appeal, but there's not a lot of consistency between editors on how tabs are implemented and I think you're just asking for trouble. With spaces, you always know how things are going to turn out. A space is a space. A tab is...well, whatever your editor decides it is.
Plus, in my experience, even if tabs are mandated you'll still end up with spaces in your files. Why? The tab key is configurable in most decent editors, but the space key never is because you wouldn't want it to be. You can make the tab key give you spaces, but you can't make the space bar give you tabs, so stray spaces will always find their way in. (Unless maybe there's an option to convert x spaces to tabs? This feature probably exists in some editors.)
Chickencha on April 14, 2009 6:36 AMGah, just look at the amount of comments in this blog post... Color of the bikeshed?
Nicolas on April 14, 2009 6:58 AM"That said, only a moron would use tabs to format their code."
tut tut! :)
I work as a sub contractor and thus with several different clients. Each client has there own way of formatting its code, you can imagine my problems....
thanks for all the code!!!
FortRandallCasino on April 14, 2009 7:28 AMThe chinese spammer makes more sense than Atwood.
Meh on April 14, 2009 7:36 AMThe really frustrating thing is when the *IDE* starts reformatting your code. Especially when it gets it wrong. I don't know how many times I have had an IDE try to find tabs and starts creating weird tabs at 3 and 5 spaces. And it's actually creating spaces! Argh. Just put it under the block above! Can't you see the code? Why is your "smart" tabbing so stupid! Stop trying to reformat my code!
I get frustrated just thinking about it.
Stupid smart formatting ;)
Practicality on April 14, 2009 7:41 AMA small experiment to see which is better.
Spaces:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(func, initial) {
var current = initial;
for (var i = 0; i < this.length; i++) {
current = func(current, this[i]);
}
return current;
};
}
Tabs:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(func, initial) {
var current = initial;
for (var i = 0; i < this.length; i++) {
current = func(current, this[i]);
}
return current;
};
}
It seems, that there is absolutely no difference :)
Rene Saarsoo on April 14, 2009 7:52 AMHey AftWood "Every rule of K&R nazi code writing guideline is there to make You Keep It Simple" stupid - Greatest Man In The World (me of course)
hribek on April 14, 2009 7:53 AMI've been guilty in the past of 'cleaning up' other's code, but mostly only so when I'm amending it/updating it I can actually tell what the hell is going on, our production programmers use vi in Linux to write code and whitespace use along with everything else is extremely inconsistent.
Dale on April 14, 2009 8:02 AM@John W: Can I work for you?
Steve-O on April 14, 2009 8:15 AMorange you glad I didn't say banana?
David on April 14, 2009 8:19 AMClean, well formatted code is essential. I think we can all agree to that. :)
I work on a system that uses an old VBScript 4.0 implementation for scripting things the software can't perform and to do data validation in particular instances. This system, due to its architecture, is limited to 60k characters per script with the ability to "include" other scripts.
To keep simpler scripts to one file we settled on keeping blank lines to a minimum, using comments sparingly once the script was applied, and tabs instead of spaces to keep the file size down.
I too have been guilty of cleaning up code I had to maintain just to make it easier to work with.
Formatting, down to the the type of characters used for whitespace formatting, is important and will vary by the environment.
Tim Malloroy on April 14, 2009 8:20 AMSomething cool about tab idents is that you can make your code "breath" as you want according to your screen size. Eg: If you have a wide screen, it will be easier to read code with tabs set at 8 chars width. With normal screen you could prefer 4 chars, or 2 chars on a small screen or terminal. All recent editors allows you to change the tab width.
Personally I like to choose the font I use for coding, why couldn't I also decide the width of the code identation ?
Meghazi Fabien on April 14, 2009 8:34 AMOne other issue that combines with this one is: do you have a maximum line length?
It's been established that when text is below a certain width, your eyes can take in the entire text of a line without moving horizontally; conversely, if the text exceeds that width, your eyes have to track horizontally to get the entire content of the line. This horizontal tracking slows reading considerably. The exact width varies from person to person, but is greater than 80 characters for most people.
This can impinge on tabs-v-spaces arguments. If you think that a line should be no more than 80 characters wide, the representation of a tab becomes important, because line with a 3-character tab might not exceed the 80-character limit while a 4-character tab will.
An alternative is to consider only the non-tab space for the purposes of determining maximum width. (Your eye is still taking in the entire line at once so long as the width from the end of indentation to the end of the line is not exceeding the limit.) The problem then is quickly determining when you've exceeded the 80-character limit. (This is easily done when not ignoring text by simply making sure your editor opens with an 80-character width.)
DLJessup on April 14, 2009 9:44 AMAs my friend Matt is fond of pointing out, if we were to store source files tokenized rather than as text files, then this entire debate would disappear. You could then display source files according to your preferences, and I could display them according to mine. But alas, 60 years of accumulated history has weighed us down with the notion that code must be stored in text files. Why? Historical reasons!
By the way, a good working defintion for any process that is done for "Historical Reasons" (synonym: Tradition) is that no one remembers why it is done that way; it has just always been that way.
Thus we, the most intelligent people on the planet, are fighting over how to format our "language", even though it has long been in our power to make the issue irrelevant.
Excuse me while I go reformat my coworkers code...
Zorro on April 14, 2009 9:56 AM@those arguing that code is easier to read - given a wide enough screen - with tabs that are 8 spaces wide, you must use Java.
Having to scroll your eyes horizontally to read code that's across different lines doesn't make it easier to read. Not all code has really long lines...
That said, I learned a long time ago that 3 spaces is an amazing in-between for the conciseness of 2 spaces and the verboseness of 4 spaces. I have VIM configured to insert 1, 2, or 3 spaces to reach the tabwidth of 3.
Izkata on April 14, 2009 10:00 AMBack in college I worked with one guy who insisted on using Hungarian Notation for variable names, even though no one else on the team had heard of it except me. We almost got into a fistfight over it... and the ensuing rift hurt our grade too because we hadn't properly managed to work together. :(
Still better than using Hungarian Notation though. ;)
Really though, arguments or not you should use whatever is standardized by the company. (Our school's coding standards were NOT to use Hungarian Notation, of course.)
Telos on April 14, 2009 12:40 PMholy crap, you mean to tell me the tab key does more than change the input focus on forms? wow! people use this key when writing code? i've never heard of such a crazy thing.
cowgod on April 14, 2009 1:17 PMThis reminds me of the never ending debate over curly braces {}...
I'm one of those:
Curly braces should be on a separate line as God intended..."
type of programmers.
Tabs well, they are easier to deal with than spaces...
Mac on April 14, 2009 1:32 PM1. In Visual Studio, this is a complete non-issue. Wherever I work, if the style of the code is bugging me then I just hit Ctrl-K Ctrl-D. Done! Both the tabbing/spacing and the braces are all lined up the way I like. If someone else likes a different style, they can just do the same to get it their way.
2. What's wrong with a proportional font? Code (and everything) is so much easier to read that way. Plus, more fits on the screen horizontally. And because of #1, it's completely irrelevant anyway. I mean, if you are still lining stuff up for dot matrix reports or something, then that's one thing, but in a modern Windows environment printing on laser printers why would you continue to use hard-to-read Courier?
PRMan on April 14, 2009 1:37 PMVim....freaks!
LOL
Ya know, it's amazing the source control programs are not smart enough to detect formatting when comparing files...
G-Man
Geoffrey on April 14, 2009 1:45 PM"I actually don't understand the reason for using spaces."
Because many programmers are not smart enough to reconfigure their editors! Really.
"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."
Yes, but one of your coworkers sets it to 2 and another sets it to 3, etc, and you end up with a scrambled mess. Real tabs would give you exactly the same thing. And, tabs would let each of your coworkers do whatever they want.
5 spaces is actually pretty goofy. And gives a good reason to use real tabs!
======
No one cares (anymore) that tabs save space.
======
You can avoid religious wars by mandating running a pretty-printer (code formatter) on all code.
njkayaker on April 14, 2009 1:50 PM"This reminds me of the never ending debate over curly braces {}..."
The K&R brace-at-line-end formatting was done to save -paper- when publishing books. It wasn't necessarily intended as a formatting-commandment. I find it hard to scan code for blocks with the braces at the end of lines.
njkayaker on April 14, 2009 1:53 PMIf spaces are the same as tabs, why not just use tabs?
The real effect of using spaces is to -force- people do deal with one's own goofy preferences for no reason. It's pure pettiness!
Tabs let everybody use their own preferences without stepping on other people's preferences.
njkayaker on April 14, 2009 2:07 PMWe're a team of 20 and I can't recall any argument about spaces or tabs in the last 10 years.
Those arguments were in 1990s. Back then, many people were trying to use tabs=3. Then people fought because the defaults in editors were 4, and people still printed code, or looked at it at the command line where tabs=8. (I seem to recall that tabs=2 at Corel?)
Then Visual C++ took over the world, with tabs=4 and progressively everyone gave up.
Tabs=4 is the standard. It also makes it awesome fast to navigate the code with the arrow keys, which jump from tabs-to-tabs. You can tell right away when something's been turned to spaces by mistake
Now code indentation is another matter. The one glitch we have is some people settling on what Visual Assist produces instead of the company standard.
ulric on April 14, 2009 3:38 PM"That said, only a moron would use tabs to format their code.
* unless you happen to be programming in whitespace or Python. "
maybe the python folks wanted to start a flamewar?
or force everyone to use whitespace in a particular way to avoid a war?
when I print something out, I cannot see a tab vs a space.
I use 'expand' to convert tabs into spaces before I tinker with someone elses code (and I usually run it thru a pretty printer too).
"It doesn't actually matter which coding styles you pick [as long as your team agrees]"
No.
Just forcing tabs (4 space width) on everybody would solve this problem forever. There hasn't been any reason whatsoever to use spaces for 30 years. We have *computers* people. *They* can handle crap like formatting.
Mo on April 14, 2009 4:50 PMHere are the results (with 28 votes) from my Survey Monkey survey [1]. Unsurprisingly, there was no clear winner! <:)
29% = indent 2 with spaces
29% = indent 4 with spaces
3% = indent 8 with tabs
29% = indent 4 with tabs
3% = indent 8 with tabs
7% = indent 4 with tabs, then align with spaces
3% = other (?!)
[1] http://www.surveymonkey.com/s.aspx?sm=CuOCMx8ZkrpzKrEsWp0YpQ_3d_3d
'What is the reason for wanting to use spaces? Can anyone explain?'
1. You can't get by without spaces.
2. a mixture of tabs and spaces will inevitably lead to misaligned, hard-to-read code.
3. you can get by without tabs: in fact, everything they do is really much better done by other means.
If you want to configurably reformat code to your personal preferences, it is much easier to set up _one_ configurable reformating tool than the dozen or so different tools that will end up displaying code at some point. And that tool will handle not just indent level, but bracket placement, line length, and so on.
Repository code should be space-only, simply because it can't be tab-only.
soru on April 14, 2009 6:59 PM"2. a mixture of tabs and spaces will inevitably lead to misaligned, hard-to-read code."
If tabs are used for indentation and spaces for non-indent alignment, that isn't true. But what you're really saying is that using tabs isn't viable just because it's a style decision. In which case, choosing a certain number of spaces for indent carries the exact same caveat.
The people arguing for tabs make explicit the benefit of editor display configuration. Personally, I've seen no text editor that can handle syntax highlighting and not something as simple as tab widths or space substitutions.
The people arguing for spaces make implicit the obstacle of a lack of editor display configuration. They should stop arguing about the benefits of spaces, which are none on the terms they're talking, and discuss what tools they're actually using and why.
The only thing more tiring than people talking over each other wrt tabs v. spaces is dealing with space-indented code.
Anonymous on April 14, 2009 7:32 PMI used 2 space characters, no tab (well, tab = 2 space characters).
Tabs are like hidden bombs, they're not predictable. If I press backspace one time will I jump back one character or <number of characters per tab> characters? There's no telling, unless you turn on some kind of UI helper, which is distracting. It's like playing minesweeper with your code :)
Peter on April 14, 2009 10:03 PM"If I press backspace one time will I jump back one character or <number of characters per tab> characters?"
Complain that the shovel handle is broken, not that the ground is so far away that you have to bend halfway down to scoop it up.
Anonymous on April 14, 2009 10:32 PMPython solves this by not allowing either the semi-colon or tab issue affect developers. Python code is some of the cleanest, minimal, and correctly formatted code that is all the same. Refreshing...
ryan on April 14, 2009 11:23 PMThe important is to have a program running, whether you use Space or Tabs.
But considering that people are going to look at your code after you, for maintenance or new development reasons, then no doubt it should look esthetically good.
For this, I personally prefer to use Space as it is more strict and more precise. Space gives you more control on how you want your code to look like.
Omar Abid over the last 5 days has been literally been SITTING on that F5 button to get that pureile 'First' statement in there.
Personally, when formatting my code, I conform to what the lead dev. or dept. tells me to do... Which is normally NOTHING :(
Tab in Emacs indents the current line depending upon the language settings you've set up, always has. It's one of the things you need to understand when you start using it. You can choose tabs or spaces. Ruby uses 2 spaces by convention so that's what I use. I think I'd prefer tabs sometimes so I could see how far something's indented but that's not the standard.
If you're running one of the code completion engines and are at the end of a line then it will do that instead.
Emacs also has an "indent-region" command that applies the conventions of the language you're using to a selected region. These conventions are entirely user-configurable.
I'm curious: why are people pressing the tab key at all? If you've got auto indent on it will indent when it detects a "block" being opened, not just Emacs but nearly every decent editor (including Vim). Also, as many others have said, just run a code beautifier on it as part of the check-in process (not hard).
I was amused by the idea of editing some kind of artefact instead of code - how would you version control it? Text works and is really easy.
NB not prettifying is one of the things you should do in OSS, because it makes the check-ins huge and hides the *real* changes you made.
Francis Fish on April 15, 2009 1:35 AMThe other good thing about spaces is that it means 3 to 7 extra keystrokes so you look that bit busier...
The office where I work uses Visual Studio 2005 which has its own ideas about coding conventions. I worked with someone (who has now left) who didn't believe in them. I think he spent more time reformatting code than actually writing it.
Paul Herzberg on April 15, 2009 3:06 AMI think nano/pico have always done elastic tabs, a feature I like a lot.
Dev Null on April 15, 2009 4:54 AMWhy can't it just store the code in xml and render it on-screen according to the whim of each user?
Everyone is happy!
Bob Ama on April 15, 2009 5:43 AMI'm a tab guy. It's just more efficient.
Dan Holtz on April 15, 2009 6:39 AMOnly us programming dorks would have this argument gleefully for the eleventy billionth time.
I use TABS, spaces are for old farts that use vi and emacs.
Give me my tabs and pretty colors in my fancy IDE all day long. Weeeeeeeee!
chrisb on April 15, 2009 6:51 AMthanks for the code, very useful!!!
FourQueensLasVegas on April 15, 2009 8:38 AMThis is really a simple argument.
Any of the options will work properly if all developers follow the same standard.
Any of the options will fail miserably if some developers follow the same standard, but others don't.
Only the third option, tabs for indentation plus spaces for alignment, will allow developers to change the number of spaces per indent to their personal preference without screwing up the code. A guy who likes 2-space tabs can set his personal view to be two spaces, while a guy who likes 8-space tabs can do the same. The code will still be perfectly indented either way, and using tabs+spaces even multi-line function calls will still line up no matter what your tabstop value is.
If you just use tabs, you still get the same benefit of not imposing one man's personal tabstop value preference on all, but multi-line function calls will no longer be aligned for non-standard tabstop values.
If you just use spaces, you are forced to impose one man's will on the crowd, like a new web developer who doesn't understand CSS.
This is all in the theoretical world where people follow the coding standard. In that world, tabs+spaces is the clear winner. In the real world, where people always forget about the standard and screw up, tabs + spaces is just too darn complicated for some people to understand, increasing the likelyhood of nonstandard code. Spaces-only goes from being the worst option to a potential winner because you can at least override a non-standard tabs-user by automatically converting tabs to spaces on checkin. However, you could convert spaces-at-the-start-of-a-line to tabs just as easily, so there's really no case where spaces are the winner.
Tabs are always going to win the day due to allowing fussy developers to view code in their own personal tabstop preference. Spaces just can't do that. Spaces are great if you believe your personal viewing preferences are The One True Way, though, and you'd like to force everyone else to follow them.
BBT on April 15, 2009 9:15 AMTAB. End of discussion.
EthR on April 15, 2009 9:24 AMHow do you shift multiple lines of text around if its indented with spaces? Does anyone really use spaces anymore?
joe on April 15, 2009 9:35 AMI've never heard one good argumnent for spaces and I still haven't today after reading this article and most of the comments.
Tabs provide the same readability, allow custom indentation levels at a per-programmer level, and stop people from wasting time doing worthless custom formatting with spaces to make arguments line up, etc.
People that use spaces to indent their SQL should be shot.
JohnOpincar on April 15, 2009 9:54 AMTo clarify "worthless custom formatting," imagine somone that uses spaces to make their formal and actual parameter lists line up with the open paren. If you change the name of the method, you have to manually change the formatting of the method definition and every call to the method. People that use spaces are usually noobs or don't have enough real work to do and should be laid off :)
JohnOpincar on April 15, 2009 10:00 AMWhy not have version control that normalizes source code before check-in, then apply a user's formatting choice on check-out? If all somebody does is muck with the whitespace, nothing actually gets checked in.
Sure, it wouldn't be perfect - e.g. how do you handle long single line comments - but it would be better than listening to everybody belly-aching about spaces, tabs and bracket placement...
PangMao on April 15, 2009 10:01 AMSpaces are: absolute, predictable, necessary, reliable, standard, WYSIWYG.
Tabs are neither of the above.
In an ideal world tabs might provide "I see it as I like it, you see it as you like it" effect and may also spare some typing.
In the real world tabs are used inconsistently by the humans and interpreted inconsistently by the tools most of the time.
There is still chance to get tab usage right if only one person (you) and one tool (your editor) are involved. Unfortunately, that's not always possible. We work in teams, deal with third-party code, use multiple editors AND other tools.
On the other hand, it is absolutely trivial to get space usage right.
So at the end it is a matter of priorities. If you value consistency and reliability more than your personal convenience, you inevitably chose spaces. Otherwise (and I don't criticize anyone about it) you might stick with tabs AND spaces.
BTW I always LOL when "the amount of typing" is used as argument related to programming. We are *not* typists -- so it doesn't matter that much. On average a programmer produces about 100 lines of code per day, or about 0.2 character per second. Compare that to 50 words per minute (5 char/sec?) that an average typist achieves.
THE AMOUNT OF TYPING IS NOT IMPORTANT.
I'm surprised no one mentioned an old classic:
<a href="http://www.jwz.org/doc/tabs-vs-spaces.html">http://www.jwz.org/doc/tabs-vs-spaces.html</a>
Most programming editors allow YOU to define the number of spaces to display in a tab. Therefore one tab can equal 2 spaces, or 4 spaces or 20 spaces if you want to get pervy.
It annoys me when people use spaces, as I'm then stuck to seeing it their way. USE A TAB YOU MORON!
Tab once and save space!
bloop on April 15, 2009 11:06 AMLet's play: what's the smallest, stupidest thing that can incite controversy in nerds? This topic could very well win!
chris on April 15, 2009 11:36 AM"The universal assumption in all the discussion about tabs vs spaces seems to be that your text is always viewed in an editor where you can configure your tab width preference. But what about command line output, like more, grep, etc. This happens to be a predominant use case for me on any project, and tabs cause all kinds of chaos for that. Long live spaces!"
Do 'man tabs'. On a Unixy system with a good gnu foundation you'll see that 'tabs -4' will adjust your terminal tab setting to every 4 characters.
Also, see 'expand' and 'unexpand' for automagically expanding tab characters to the matching number of spaces (or vice-versa) via piping.
If you can't remember any of the above, try "apropos tabs", which will give you the list of the handful of utilities on your machine directly aimed at dealing with differing tabstop settings.
Having to set up tabs in multiple applications may be a "chore", but the tab width if used properly (ie, tabs for indentation, not alignment, see above) won't mess up the representation of anything in your diff program if indeed you are too lazy to find the option to change it. The *worst* outcome is that you have to scroll more horizontally. As I said above, even if using tabs for alignment instead of spaces: if you are relying on alignment for semantic cohesion, you are already leaving a maintenance nightmare and timebomb in your code; it's not necessarily a bug that your source code control diff program makes that kind of thing look ugly!
All that having been said, I find it very amusing how many space-zombies above rationalize their choice by saying it makes their code consistent, and yet vehemently disagree over how much indentation should be provided at each "tab" stop. Tabs directly fix that disagreement by allowing each developer to define their own preference. "Inconsistency" is a feature, not a bug! Does it also bother you that your fellow developers might be looking at your code in Inconsolata or Monaco or even *gasp* Verdana instead of the Courier New font you wrote it in?
Tom Dibble on April 15, 2009 12:08 PMI swear by Tabs and whoever disagrees offends me and my religion, and should expect a programmers' Jihad.
We, the People's front of Tabspacing have only one enemy, the "spacers". Oh, and Tabspacian people's front too.
We will not rest until all editors disallow more than one consecutive spaces. Our struggle is also know as "Der tabspace kampf".
It seems like a lot of space fans seem unable to tell the difference between writing code formatted the way the reader wants it to look and code formatted the way the writer wants it to look.
Tabs do both, spaces only do the latter. Hopefully readers here are smart enough to realize that you should want the former.
BBT on April 15, 2009 12:28 PMI have a huge suspicion that almost all of the above preachers have a random mix of indent tabs and sections of indent spaces plus the occasional evil non-indent tab thrown in too, in their code. To be absolutely consistent, you have turn on whitespace visibility in your editor. If you're a tab guy, you have to actually look at your code at different tab sizes (both very big and very small) to make sure you don't get magic tab size syndrome (where your code is only readable at the magic undocumented tab size). Space guys need to a run a tab detection program over their source every now and then.
It's really easy to get bits of contrary formatted code into your source, just a copy and paste from the net or some editing on a new editor.
Both sides suck. Tab guys need to know a huge amount of theory about how tabs fall apart. Space guys need find a sophisticated editor that does backspace unindents and they have to dig into the preferences to set it to spaces on every new install (as tabs are normally the default); it should also have a tab char alarm bell and a convert between different sized indent amounts (but you won't find these functions anywhere).
Ah... the joys of whitespace. I'm currently doing my project for college on an AS400. Newer versions of RPG have whitespace but the version installed on the college machine doesn't. In some ways it's actually easier but then you've forgotten an endif somewhere and it takes about ten minutes to track it down in a nested if statement...
I personally feel that tabs are quicker. I can't imagine hitting spacebar three times everytime I wish to indent. Just hit tab once and you've got your indent.
Doesn't hitting spacebar all the time give you a headache?
patrick on April 16, 2009 12:48 AM@patrick:
"Spacers" don't hit the spacebar, they rely on their smart IDEs for converting tabs to spaces when you write them. Then again, they also preach using spaces arguing it's to help those using dumb IDEs, or even notepad :)
The only valid use of spaces is to vertical align stuff (e.g. method parameters). I can surely live without that, but some people are religious about it, so more power to them.
I'll probably be a Tabber as long as my IDE does not jump 4 spaces at once on arrow keys and hitting backspace deletes only one space instead of 4. Or 3? Or better 2? But only in the context where I did want to indent, of course (good luck at guessing that)...
I guess I'll be a moron for life.
Dan C. on April 16, 2009 2:54 AMI'm a moron too xD. Tabbing has always been the way to go for me. I have never even considered using spaces, and my hand does it automatically.
David Siaw on April 16, 2009 5:20 AMIt seems to me that the difference between 2, 4 and 8 space tabbing is akin to asking experts and novices to memorize chess pieces on a black and white tiled board versus a red and green tiled board. I agree a team should have standards so you don't get into a check-in format war at that trivial of a level but the study looks like it was more about memory relating to rationally ordered statements versus random randomly ordered statements. I just feel that comparing that to whitespace preference is a false analogy.
<Soapbox>If you don't use an intelligent IDE of some form then you don't care about productivity...and "notepad.exe" is not an IDE.</Soapbox>
Matt Poland on April 16, 2009 8:12 AM
"1. You can't get by without spaces."
Silly. You can't get by without the letter "A". That doesn't mean you should use the letter "A" everywhere.
"2. a mixture of tabs and spaces will inevitably lead to misaligned, hard-to-read code."
Silly. It's misaligned because people indent with different numbers of spaces. If people didn't use spaces, there would be no alignment issues!
"3. you can get by without tabs: in fact, everything they do is really much better done by other means."
EXCEPT indentation because everybody wants to impose their own goofy number of spaces on other people!
"convert between different sized indent amounts (but you won't find these functions anywhere)"
Any this would mean spurious differences in source contro.
"Spaces are: absolute, predictable, necessary, reliable, standard, WYSIWYG."
Except, it's 2, 3, 4, 5 spaces => not absolute, not necessary (for indentation), not predictable, and not reliable, and not standard!
"Tabs are neither of the above."
Tabs are -one- thing.
WYSIWYG is not an accurate description for spaces.
WYSIWTS (What You See Is What They See) is what is meant here. Then the question just becomes what on earth would possess you to want to force others to see things according to your formatting preferences instead of their own?
BBT on April 16, 2009 12:19 PMUsing tab characters does indeed allow others to see things according to their preferences, but it's only a small step in the right direction. There are many more aspects of preference that need solving. The goal should be for editors to reformat the code to your preferences on load, and reformat the code to a standard format on save. (In the event that the editor can't parse the code, it can simply skip the reformatting step.)
The interaction between automatic reformatting and manual alignment should be interesting -- perhaps Nick Gravgaard's elastic tabstops would provide a solution.
Mr.'; Drop Database -- on April 16, 2009 8:31 PMThere *are* decent editors who will unindent the proper amount when you hit backspace on a space-indented line.
vim on April 19, 2009 6:39 AManother moron, another tab lover :xD
avar on April 19, 2009 8:44 AMHi.
I'm the guy that made the statements about a developer changing code of others (all others in the department).
RE:
"This guy seems to be complaining about a lot less trivial changes than tabs, spaces and the location of curly brackets."
No - quite definately this is about trivial changes, locations of spaces, tabs as well as Variable and Function names. This is nothing about cleaning code, but entirely about reformatting. And that is what has me scratching my head.
I take no offence to this - my code is being altered to the way the person wants and they are a boss. I get paid a good wage and they can litterally do with my code whatever they like (sell it, delete it, alter it, etc.) I'm not so arrogant to get offended that my code is changed, after I write it. I'm proud of the work I have accomplished but then it then belongs to the company.
I just thought it very strange that this person would spend the time to do reformatting just for the sake of reformatting. Is it putting their stamp on the code? Is it them trying to understand the code? Is it just that they find it easier to read?
The greatest impact is on code revision checking, because things that "look" like changes to the code are merely changes in white space or function names. But again, I don't relaly care too much about that.
But I'm just left puzzled as to why it even happens.
Philip on April 19, 2009 4:25 PMI'm a first year engineering student and recently had to complete my first major group programming project. One annoyance we ran into was different programs using different tab spaces. So code that looked perfectly tabbed in one editor was completely misaligned in another. So maybe spaces is a better solution. I personally do prefer tabs though since I'd rather hit backspace once rather than four times or hit tab once rather than the space bar four times.
Ian on April 19, 2009 10:02 PMchoosing spaces will increase your source code size if you've converted tab to spaces according to your editor setting the source code will be replaced with 4-8 tabs(whichever you specified). while tab can be represented with single character.
Anyway as you said it's upon the policy of team, group or organization to stick with particular style.
Sarath on April 20, 2009 6:35 AMCould you help me. You can have it all. You just can't have it all at once.
I am from Jordan and learning to write in English, give true I wrote the following sentence: "Airline carry on restrictions liquids."
Thank you so much for your future answers :p. Horus.
Horus on April 20, 2009 11:39 AMIt should read: "I'm a spammer and identity theif."
Philip on April 20, 2009 11:18 PMwow, it's interesting to see that an article about blank characters generates about double the comments then one about the meaning of open source in job interviews ;)
maybe it's because you insulted our beloved TABs...
i, personally, like tabs because it prevents me from curser-arrowing myself to death when debugging nested structures. plus, with the stroke of one key, i'm exactly at the next code level, no mistake possible. also, when you space your code, different preferences can get VERY dangerous, especially, when one guy likes two, the other likes 4 spaces - with tabs, thats a simple config setting. plus, space indented code tends to get really messy after a few revisions when people are careless. so i see use of tabs vs. spaces a bit like OOP vs. procedural languages: a good developer can get the same results with both, but OOP helps to protect us from the slobs out there (and most snobbish programmers despise non-OOP langs using mainly that argument).
and on "correcting" others code: to rename other peoples vars or functions should be a definitive no-no (except when sombody uses varnames like a1-z99 - that person has simpy forfit the right to touch code)! but i must confess, when i have to debug very complex strange code, i simply must reformat white spaces (bracket positions and such) or i would have a serious loss of overview and efficiency.
bradbury on April 21, 2009 4:22 AMSorry for coming in so late, I was in another universe for awhile. However, to jump right in, I feel two spaces leads to not enough of an indent and four spaces uses to much room, so I prefer 3 spaces I know its an odd number but what the hay. Really it appears to be the perfect spacing for code indents. If you really can't deal with the odd number, four spaces is definitely better than two as a good programming practice if you are indenting too much then you should be breaking that code up some.
BTW, for most of those tab-freaks your editor should have a keyboard shortcut to the beginning of a line or the first character in a line. In Unix/Emacs it is crtl-a once to beginning of line and twice to get to first char. In Windows it is the home key. IF other editors don't have it and it's open source add the functionality in.
Anyway the point is tabs are usually not the way to go in multiple environments / multiple developers. IMHO.
Last point to tab-freaks, I was a self-proclaimed TAB-FREAK for many, many, many years. Reviewing code from multiple environments / multiple developers will crush your desire to see a single tab in code ever again!!!
Follow up post. Several modern editors will you to highlight/block off one or more lines of code such that when you press tab or shift-tab the editor will indent/un-indent that code with spaces not tabs unless of course you are still using tabs (see previous post).
Jim on April 21, 2009 6:50 AMThe "Tab" button is short for "Tabulate". Therefore it should be reserved for those situations where you would like to format your code into specific columns of indentation.
e.g. classes to the far left, one tab in for functions, another tab for initial code in those functions.
That was always the intention of Tab.
But the point everyone is missing is that Jeff wasn't serious about the moron bit. We REALLY need a "sarcastic" font so intention is obvious.
Philip on April 21, 2009 3:30 PMSomebody probably already said this above, but lots of modern code editors have an option to make the tab button add spaces to your code. It functions like the tab button, but it's actually adding space characters. This is important if your code is going to be appearing in different editors. Everything reads space characters the same, but not tabs.
Devin on April 21, 2009 6:15 PMSpaces *always* work. Tabs often don't.
Phil on April 21, 2009 6:43 PM"No - quite definately this is about trivial changes, locations of spaces, tabs as well as Variable and Function names. This is nothing about cleaning code, but entirely about reformatting. And that is what has me scratching my head."
If you think variable or function names are trivial, as in unimportant, well then I could hardly disagree more. They are the essence of readable code. The well named variable will usually eliminate the need for a comment, and the well named function will make code understandable in a way no amount of commenting will allow. And readable code is the heart of maintaining a large source base.
If your team lead is removing contractions and adding specificity to your variables and function names, then he is showing that he has been burnt by these things in the past and is trying to save both of you long term pain. You would be wise to learn from this.
Glenn Howes on April 21, 2009 11:19 PMI've always been a fan of both.
Personally I use tabs for html and markup languages, while I use spaces for other languages.
Tabs have a strategic advantage in html. If you don't have the plus of using gzip compression a tab is equal to that of 4 spaces. Meaning you can indent in less characters. I recall several years ago "optimizing" an awful table based page by simply converting spaces to tabs. Saved several Kb, which over a dial up connection made a difference.
For things that are compiled, server side, or file size doesn't matter, I prefer spaces (4 to be exact) since that seems the easiest on the eyes and the most consistent across platforms.
Robert Accettura on April 23, 2009 12:49 PMWhen the team that reports to me switched from a waterfall development method to extreme programming, we decided we would actively try the "shared code ownership" practice. One of the recommendations of that practice was consistent formatting. We didn't have long battles, but we had dissent in the team that could not be resolved.
We were coding in Java, so we decided we would adopt Sun's Java coding standard. We were then delighted to find the open source version of "jalopy" which was able to format the code to enforce that coding standard.
We made that switch in 2003, and the team adapted very comfortably to having the code formatting "fixed" each time they compiled the code. The formatting step was an integral part of the build process, and was supported by a nightly automated task which checked out all the Java code, formatted, and checked in anything that was changed by the formatting.
That was over 5 years ago, and that code base is still being developed, still being actively formatted to a single consistent style, and I believe the developers on the project are glad for the consistent formatting. Comparing file versions is easy, and no time needs to be given to making formatting consistent. It will be made consistent by the tool.
I believe the program "astyle" can do the same thing for other languages, as can "indent" for C.
The details of the standard seem to have been less valuable to us than the fact that there was a standard and it was automatically enforced.
Mark Waite on April 23, 2009 7:27 PMThe tab argument is tempting, but it doesn't actually abstract spaces away. Because of tab stops. Tab stops, or "spaces multiple of 8" functionality mean that everyone will see tabs differently.
Spaces, if you aren't brain dead, will at least look sane on all editors. Tabs can make code look ridiculous, especially if one person uses tab stops or multiples of 8 and another interprets tabs as spaces.
Unless you refuse to use a fixed-width font, in which case there's no help for you and you've probably given up looking at code in any sensible fashion anyway.
Rick Scott on April 24, 2009 10:11 AMI don't agree with the "don't use Tab" argument. Every code editor I've used in my career, from multi-edit to SQL Query Analyser has the ability to customise font, colours and Tabs. In fact, if you are in an environment where Tabs can't be adjusted - perhaps you should consider changing IDE.
I think one thing missing from this debate is the fact that different developers frequently develop with different visual settings.
I find standard black on white letters a bit hard to see and after some experimenting I've found "Comic Sans MS" in 12 font to be used. Another developer here prefers a black screen with light coloured fonts. Yet others go defaults all the way.
But spaces look different under different fonts, but tabs don't (at least not on our environments. But I agree with Mark Waite above - automatic re-formatting makes sense.
Philip on April 26, 2009 5:43 PMThe third style makes most sense, and allows you to adjust code indentation for clarity.
It is increasingly important to use the most flexible method of indentation when dealing with multiple authors since it's not reasonable to assume that everyone else wants to read your code using the same indentation length.
The discussion should never be tabs vs. spaces, it's about correctly representing the indentation you want to achieve.
Just because your editor sucks, doesn't mean you should make others suffer while reading your code. (write once, read many times, remember?)
Why anyone prefers spaces over tabs is beyond me, it's like saying we only need a single datatype when we are representing fundamentally different things.
I don't think there is anything wrong with tabs for indenting flow control and such. If there is a problem it's far easier to convert tabs to spaces than spaces to tabs. Either way no matter what you do there will be a point where the kludge is as inescapable as it is laughable.
However there is one thing I must point out. Do not always rely on an IDE to apply white spaces. At least, don't rely on it entirely and blindly.
Of course as mentioned if you can use a tool with some parsing ability (so it knows what is a literal string, comment and so on) to clean up your code. Again as mentioned, use a constant width font.
If the option is presented to you, always turn show white space characters on. I've seen some coding horrors where the use of spaces and tabs is completely inconsistent (even on the same line OMG). Worse still due to the way tabs work and auto align I've seen spaces in a column (at least a column where tabs are concerned) that are totally useless. A particular problem I've also noticed with IDE's in particular but can generally occur in any case where white space is actually plain white is whitespace at the end of lines.
It makes my blood boil.
Joey on April 28, 2009 4:28 AM@Jonathan: That's awesome. Elastic tabstops. It addresses both problems, and ends up promoting a standard that most people use tabs / spaces to do manually anyway. With a bit of tweaking, it could even reformat code, and handle anyone's preferences quite simply.
I like.
I wonder how hard it would be to hack into Xcode and/or TextMate.
Groxx on April 28, 2009 10:14 AMwhat's amazing about this discussion is how every criticism of tabs seems to be based on the idea that it's a bad thing to let the reader view code according to their personal preferences. That sure seems like a positive thing to me!
Everyone keeps saying things that amount to "But if someone else chooses to view it with different preferences than mine, they won't see it with my preferences!". Yes, that's correct. Isn't that good? If they want to view things with your preferences, they can use your preferences.
BBT on April 29, 2009 10:25 AM50 pages of comments in a few days over spaces vs tabs....
Lolz on May 1, 2009 2:15 PMThe point I'm trying to make is that tabs alone do not allow the source code to be read according to your own preferences.
The elastic-tab convention is currently the _only_ real solution to this problem.
If everyone in a project adheres to it, then everyone can read the source code in the way they see fit, and therefore avoid useless commits or other nonsense.
Tabs should only be used as the special indent character they are supposed to be and spaces for representing any kind of manual deviation from ordinary indentation.
Emacs supports the third option:
http://www.emacswiki.org/IntelligentTabs
Marius Andersen on May 24, 2009 9:41 AMthis is so cool. i think you should mix the tabs and spaces together.
Ahahaha, what a wonderful post. It just never ends.
Practicality on June 4, 2009 2:19 PMWhat kind of insanity has emacs done!?
Practicality on June 4, 2009 2:21 PMVim has it too, now:
http://www.vim.org/scripts/script.php?script_id=231
Marius Andersen on June 5, 2009 4:46 AMYes, it never ends.
Now I throw the question to all the no-tabbers. What does it matter if one editor interprets a tab as 4 or 8 or 2 or what ever width of characters. IMHO, that is what is so good about tabs. If a coder whats to see the code with 2 character wide intends, he is free to do so. If another wants to see it as 8, just set it like that. No big deal. One tab per one level of indentation. I don't understand what is so difficult about this. I can't stand some of these editors that insert spaces instead of tabs. If they'd also backspace the same about of spaces that would be fine. But no. I hit tab and then have to backspace 4 spaces. WTF? I'm lazy. ;) Oh and tab stops should not exist in a real text editor. OK? WTF is that? Tab stops? Something from a damned word processor. Yawn...
sims on June 29, 2009 5:22 PMI actually prefer to use neither. Indentation tends to push the code too far off to the side. If you don't indent anything, all of the code will be neatly lined up on the left margin.
I wrote a small script a few years back that strips any whitespace from the beginning of each line. It works great and keeps code looking nice.
Phil on July 5, 2009 9:00 PMnick said it correctly: "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."
The key here, which people who still use Notepad don't understand, is that a good editor *displays* a tab as a number of spaces, and that number is configurable (in good editors, of which Komodo is one). The source code file remains unchanged, and everybody can be happy. Separation of data and presentation has gotten into this area as well. People simply need to stop using Notepad as a software development editor (it's designed to write notes, not programs).
Roman on July 8, 2009 2:16 PMIn all of this I have yet to see the main argument that caused me to abandon hard tabs in code nearly 20 years ago: documentation. Try taking a piece of code written using hard tabs and paste it into MS Word (where tabs stops are in inches or centimeters) or an e-mail or a web page. The results vary from marginally usable to unreadable.
I can’t image how horrible the code from an “elastic tabstop” editor would look when viewed in any other application. Once you start using something like that your code stops being a plain text file and becomes non-standard. Even though it is still a text file so it can be viewed in other applications you lose the intended formatting. It takes the problems with hard tabs and amplifies them.
Assuming that the code will only be viewed or edited in a particular program or group of programs is rather short sighted. You yourself may be in a situation where you have to view or edit a file in notepad or Word or an ancient version of vi. I know I have. Using all spaces may mean that you have to type and delete multiple spaces, but, the code will appear as intended in the word processor or old text editor and if you make changes you won’t have to go back later and fix the formatting.
I currently work as a contractor and follow whatever coding standards my client prescribes, but I feel fortunate that in the last 5 years I haven’t come across a single shop that used hard tabs.
Tim on July 15, 2009 12:31 PMI think the third option -- tabs for indentation, spaces for alignment -- has an advantage when it comes to documentation. When coding on my widescreen, I prefer a large tab size for maximum legibility: four or eight columns per indentation level. However, that's way too much for paper, so I use LaTeX's listings package to set the tab size to two (\lstset{tabwidth=2}). The code will then display as if it was indented with two spaces per indentation level.
This way the original line numbers are retained as well, since I can just include the necessary lines from the source files themselves without reformatting it first.
Marius Andersen on July 19, 2009 5:10 AM| Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved. |