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.
For 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 12:12 PMIn 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 12:21 PMAs 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 12:34 PMOf 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 12:36 PMI 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 12:36 PMIf 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 12:36 PMMeh, 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 12:37 PMAnyone 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.
@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 12:41 PMI 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 12:44 PMUse a combination of two tabs and two spaces for every indentation and everyone is happy.
Herman on April 13, 2009 12:44 PM@herman..
then why isn't everyone happy?
UNKNOWN on April 13, 2009 12: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 12:50 PMYou don't know the true joy of format wars until you use a graphical programming language...
Underflow on April 13, 2009 12:53 PMBack 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 1: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 1: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 1: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 1: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 1: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 1: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 1: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 1:47 PMWow, 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 2:17 AMholy 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 2: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 2:20 AMThis reminded me of the Real Programmers comic for some reason:
http://xkcd.com/378/
This 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 2:32 AM1. 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 2:37 AMNot 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 2:42 AMVim....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 2:45 AMI 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 2:50 AMThis reminds me of the never ending debate over curly braces {}...
The KR 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 2:53 AMIf 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 3:07 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 3: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 3:27 AMThat said, only a moron would use tabs to format their code.
Unsubscribed!
Arielr on April 14, 2009 3: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 Hvrneanu on April 14, 2009 3: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=stylesektion=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 4: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.
We'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 4:38 AMThat 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?
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 5: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 5:36 AMwhen 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).
Using 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 5:50 AMIt 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 5:50 AMToo much white space is a problem for graphical language programmers as well.
PaulG on April 14, 2009 6: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 6:15 AMHere 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
Jeff:
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 6: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 6:46 AMI can see a new set of adverts - maybe with Vin Diesel and Keifer Sutherland:
I'm a TAB
.
.
.
I'm a space
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 7: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 7: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 7:36 AMGah, just look at the amount of comments in this blog post... Color of the bikeshed?
Nicolas on April 14, 2009 7:58 AM'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 7:59 AMThat 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 8:28 AM2. 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 8:32 AMThe chinese spammer makes more sense than Atwood.
Meh on April 14, 2009 8: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 8: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 8:52 AMHey AftWood Every rule of KR 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 8: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 9:02 AM@John W: Can I work for you?
Steve-O on April 14, 2009 9:15 AMorange you glad I didn't say banana?
David on April 14, 2009 9: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 9: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 9: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 10: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 10: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 11:00 AMI 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 11:03 AMIf 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 11:32 AMPython 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 12:23 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 1:18 PMguys, 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
Back 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 1:40 PMI 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 1:41 PMhttp://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.
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 2: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 4:06 AMI 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).
I think nano/pico have always done elastic tabs, a feature I like a lot.
Dev Null on April 15, 2009 5: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 6:43 AMThe comments to this entry are closed.
|
|
Traffic Stats |