44

Are there objective reasons for using spaces instead of tabs for indenting files as per PSR-2 standard, can someone provide:

  • facts,
  • references,
  • specific expertise

on which PSR-2 standard is based?

Authors of PSR-2 standard had in mind something more than "look and feel", something more than just opinion based thing, and lots of people have trouble understanding why spaces are better during teamwork.

Explanation on accepted answer:

According to Farsides' answer: repositories thing may be an exact case of why spaces are in PSR-2 explained as indentation tool. PSR-2 is standard developed to assist teamwork. Single accidental spaces at the beginning of line - when using tabs - may not be visible in the IDE and can sneak out to repository. If a couple of people work on same file it is highly possible to generate unnecessary conflicts. Using spaces instead of tabs makes it possible to easily catch such an accidental space on eyeball and this is probably a reason, why using them become a standard.

Community
  • 1
  • 1
yergo
  • 4,761
  • 2
  • 19
  • 41
  • 1
    @deceze, no, you are not right. Find my answer below, there are specific reasons behind this. – Farside Feb 26 '16 at 11:02
  • 1
    @Farside Yes, there are reasons for it. And the fans of tabs have their reasons to argue in favour of tabs. Neither side is "right", both sides have their reasons for why they decided on one thing or the other. (Note: I favour spaces as well for the same reasons you give. But you'll have to give concrete evidence that this is the reason spaces are favoured in the PSR spec for it to be a real answer; any meeting minutes you can link to...?) – deceze Feb 26 '16 at 11:05
  • We are in middle of same discussion at work. Old projects have tabs indent and there is some friction against changing our IDE configuration to expand tabs as spaces. You can set up how your tab looks like, but hitting backspace few times more frequentrly is not handy. Just looking for heavy arguments against tabs :( – yergo Feb 26 '16 at 11:24
  • 2
    Perhaps you could reformulate your question to: *Objective reasons for using spaces instead of tabs for indenting files?* Since this is what you apparently really want to know, – deceze Feb 26 '16 at 11:35
  • I edited the question, to meet the requirements and best practices of StackOverflow, so it's based on facts, rather than on opinion. @deceze, *greg-449*, *Ctx*, *Raidri*, *Alex Tartan* , please re-vote. Thank you. – Farside Mar 31 '16 at 12:43

4 Answers4

24

Facts:

1. GIT and other version controls systems treat white-space differently

Based on my experience, we faced on our projects: GIT and other version controls systems treat invisible spaces + TABS differently, and it leads to changes in lines, which actually haven't been affected. It's easy not to notice, when there will accidentally added one space + TAB = indent looks the same in IDE, but GIT will make the difference when merging. It damages your ability to effectively compare revisions in source control, which is really scary. It never going to happen when you are having spaces only.

2. Neutralize difference in collaborator's environment (Editor, OS, preferences, etc.)

The tab width (in spaces) depends on your environment (text editor, OS, preferences, etc.), but the space width is the same everywhere. IDEs are smart enough to treat white spaces up to your personal taste, but the output generated for collaboration should be up to standards. As PSR-2 states, using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations. The use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment.

3. Developers who use spaces make more money than those who use tabs

Using spaces instead of tabs is associated with an 8.6% higher salary. Using spaces instead of tabs is associated with as high a salary difference as an extra 2.4 years of experience. (source: Stack Overflow 2017 Developer Survey).

4. Numerous studies on coding style importance

If every collaborator on your project would keep the same standards on coding - it will be good in the long run, collaboration is more efficient and professional, the same indent when you refactor or develop. Studies regarding that:

  1. For example, Ben Shneiderman confirmed this in Exploratory experiments in programmer behavior:

    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.

  2. An old 1984 study by Soloway and Ehrlich cited in Code Complete, and supported studies from The Elements of Programming Style:

    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.

Farside
  • 9,923
  • 4
  • 47
  • 60
  • 1
    Yep, this is exactly the reason. – Garry Welding Feb 26 '16 at 10:59
  • 32
    But it is case of environment specific "look", not what it actually is. Single tab is still a single tab, it is not magically changing to 4 or 2 spaces. If I want my IDE to show tab as 120px wide block, I can do this. And I can't change width of my space.. – yergo Feb 26 '16 at 11:09
  • 6
    @yergo Again: please don't reheat that argument. There are no winners in it. – deceze Feb 26 '16 at 11:10
  • 1
    Just searching for good answer for my question. I assume that some intelligent people decided it gonna be a good standard so "look" argument does not satisfy me here. There MUST be something else.. – yergo Feb 26 '16 at 11:12
  • 3
    @yergo Enough people on the PSR committee were favouring spaces over tabs. Boom. There's as much a reason as anything else. If you want to have a discussion about it, you're in the wrong place. A standard just needs to be a standard so everyone does the same thing. – deceze Feb 26 '16 at 11:14
  • @yergo, there is the concept of "smart tabs", you IDE does it transparent, and treats spaces and tabs the same way, without any difference for you. For code interpreters or compilers - there is no difference as well. The biggest benefit is when you use trivial code editor alike *vim*, *nano*, then the code indent with spaces looks everywhere the same way. – Farside Feb 26 '16 at 11:23
  • @Farside any tut on setting this up in NetBeans? I have it expanding tab to spaces, but deleting forces me to use shortcuts or couple of backspace hits.. It could cut discussion on "tabs are better because backspace" argument. – yergo Feb 26 '16 at 11:27
  • 1
    wow @Farside, version control is one of those STRONG arguments. Thanks! – yergo Feb 26 '16 at 11:31
  • 17
    I think this answer addresses a different question ("why set a coding standard"). Also, isn't the "Neutralize difference in collaborator's environment" point actually a spaces drawback? It's like arguing that not being able to change font size is an advantage. – Álvaro González Feb 11 '17 at 16:02
  • @ÁlvaroGonzález, no, it's exactly the opposite. Read carefully, what I wrote in #2. But consider also the context #1 which makes it even worse scenario, as white space/indent is not visible by default in any of IDE. I don't think there's need to repeat it one more time. – Farside Feb 14 '17 at 22:38
  • @MdAdil, you are right, especially when doing it by the means of a regular ruler and a pen straight on a paper/whiteboard... or you meant something more valuable? – Farside Oct 16 '17 at 11:51
  • 1
    Good points. Apparently you make more money with spaces too. Stack Overflow's model showed that [using spaces instead of tabs is associated with as high a salary difference as an extra 2.4 years of experience](https://stackoverflow.blog/2017/06/15/developers-use-spaces-make-money-use-tabs/) !?! – sgr12 Nov 06 '17 at 10:36
  • @sgr12, haha, that makes a LOT more sense now! going to expand the answer with this, if you don't mind, great input! – Farside Nov 06 '17 at 16:43
  • 1
    @deceze It's not unreasonable to use @ yergo's argument. There can be a winner in that argument, and @ yergo was just stating fact relevant to the question. But arguing about the choice of the PSR committee is weak. PSR sucks, because they have ruined the indentation of countless projects and have been causing new developers in the web space to use improper indentation habitually. It's largely their fault -- PSR sucks for this reason. Their choice is not gospel, nor is it correct. – groovenectar Jun 18 '19 at 21:06
  • 1
    [*"The use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment"*](https://www.php-fig.org/psr/psr-2/#24-indenting). I can see this point; I feel it stronger than it sounds. – Kamafeather Sep 12 '19 at 21:02
  • The ["Line Length Recognition" is probably among strongest arguments](http://paul-m-jones.com/post/2012/03/15/on-preferring-spaces-over-tabs-in-php/), since the concerns for those coding recommendations are mostly about visual readability. That argument is also strong in which can easily lead to some paradox among devs. – Kamafeather Sep 12 '19 at 21:20
  • However, for the record: [*"A super-majority of surveyed member projects use spaces, so that's the origin of the rule. If the majority had used tabs, it would be tabs" (pmjones)*](https://github.com/php-fig/fig-standards/pull/35#issuecomment-6375039). – Kamafeather Sep 12 '19 at 21:21
  • 45
    Great news, I'll start using spaces today and inform management of my pay rise – kemika Nov 19 '19 at 10:18
  • 22
    The first bullet point doesn't provide a convincing rationale for spaces. It makes a point about the importance of *consistent* indentation, and that's generally accepted. There's just nothing that explains why *"always use spaces"* were superior to *"always use tabs"*. Likewise, that final bullet point doesn't provide any factual evidence, why spaces were superior to tabs. And the third bullet point is really just an observation of a correlation, without a statement of causality. – IInspectable Jul 20 '20 at 18:58
  • @sgr12 The findings of that survey are interesting. I wonder if it's because touch-typists can double-tap `space` faster and more comfortably than reaching their pinky finger out to `tab`. In other words, it's not that using that *character* made them better programmers so much as that they are already in the top percentile of programmers, and touch-typing speed is a significant factor. Would a different keyboard layout have changed history? To the space-using touch-typists: how much would using `tab` slow you down? – Mentalist Feb 02 '22 at 07:01
  • 1
    @Mentalist what do you mean? in every modern IDE or not so much, a tab and several spaces would behave the same way - depending on the settings would insert spaces/tabs. It is a seamless UIX for every customer nowadays. Even Sublime text works amazing. – Farside Feb 03 '22 at 00:09
  • 1
    2nd point - neutralize the difference (if I changed the appearance, it's because I like it that way and it makes me more productive). so there's no point in neutralizing the environment. I'm just going to ignore the last 2 points. they're not technical reasons. so I think only the first point makes sense but you can't make a rule around the fact that somebody someday will "accidentally" put space+tab as indent. bear the pain of spaces only to ignore the chance of merge conflict which can be solved easily anyways? except in languages like python. but it doesn't matter in other languages. – Aniket Kariya Feb 16 '22 at 12:15
  • @AniketKariya personal coding preferences should not have precedence over an agreed upon coding style in a team. the fact is, most code you write, will not be maintained by you forever and the more predictable the readability and style, the easier it is for fresh eyes inheriting your project to maintain it. if the team has decided to use tabs instead of spaces, use tabs. or have everyone use the same linter – rolling_codes Feb 20 '22 at 12:28
  • 1
    @NoodleOfDeath I'm not objecting here anything. if working on an existing project of course we'll have to follow the existing structure. And I'm not advocating personal preference either. I'm essentially only saying that using tabs we can change the tab width in IDE and it will only change it for me, not for the whole team. so everyone can set it to their preference while maintaining consistency. – Aniket Kariya Feb 20 '22 at 15:57
  • Forcing a fixed number of spaces over all devs is a dictatorship. If you use tabs, then each dev can configure their environment for indentation to take as much spaces as they want. If your environment is incapable of managing indentation automatically then that's the problem, not tabs. Use a better, more modern environment. And that thing about mixing spaces with tabs accidentally, never happens, not with a good IDE, linter and formatting tool. – Petruza Jul 27 '22 at 11:41
  • @Petruza you contradict yourself. See, you mention formatting tools and code-linters yourself. That's precisely the case of the subject, this already means you are looking for unification and trying to shape up (unify) the difference in coding styles of collaborators, neutralizing the environment/personal preferences. Spaces/tabs are no exception here. – Farside Jul 27 '22 at 22:22
  • @Farside of course that you need unified coding standards, you can't be neutral on, E.G., _whether there should be spaces inside parentheses or not_, this rule too will suit some devs better than others, but there's nothing you can do, if they use different conventions and use automatic linters to correct the formatting, you'll start getting commit wars that go from one code standard to the other indefinitely. Still, you could have an editor, maybe through a plugin, that shows you the parentheses spacing the way you want regardless of the source code, that's totally up to you [...] – Petruza Jul 31 '22 at 12:23
  • @Farside [...] the same happens with tab caracters, your editor can give you the illusion that the indentation is as wide as how many characters you prefer and that is kept in your local configuration, no other dev even has to know about it. I actually tried plugins for vscode that recognize space based indentation and show it to you with a differen width (E.G. there are 2 space characters per indent, but the editor shows you 3) they worked horribly. It seems it's no so easy to go from spaces to tabs, but it is super easy to go the other way around. – Petruza Jul 31 '22 at 12:27
  • 3
    I believe that point 3 (making more money) should be removed from this answer. It is misleading, not objective, and not technical. Also, many reasons have been discussed about this result: developers using spaces could simply be older and have old habits, some very young developers could have answered that they use Tabs because they press the Tab key instead of the Space key, and more (see comments below the StackOverflow post). – Zwyx Aug 26 '22 at 05:04
  • 1
    I'm a "spacer", but #3 is irrelevant regarding it being "objectively" better. A lot of senior developers make a lot of mistakes for assuming things they believe they understand when they don't. For all you know, senior developers might be using spaces because "back in their times" the IDE wouldn't render tabs in tidy columns and always have size 4 and just kept using it out of muscle memory. Also, senior developers probably have more experience with stuff like SQL that doesn't align well with tabs. Some query "indentation" methods would require weird 2 or 3 spaces alignments in the same query – Guilherme Taffarel Bergamin Feb 15 '23 at 17:36
  • 1
    none of these facts matter if everyone would consistently use tabs where appropriate for indentation instead of spaces. – JDPeckham Mar 12 '23 at 19:49
  • 1
    tabs take up less data. – JDPeckham Mar 12 '23 at 19:49
8

This thread is old but still shows up on search results, and not only for PHP queries. I believe it lacks modern thoughts about accessibility.

The facts in the accepted answer are clear: for consistently looking code, spaces are best.

However, does one also has consistency among the people they work with?

It might not be the case: some people might have impaired vision.

On an open source project, one might not even know how "consistent" are the people working with them.

Some require such big font sizes, that being able to set the tab width to 1 is a big deal. (I am short-sighted, and although I don't have special needs other than wearing glasses, I can understand how useful it can be for others).

After working years on projects using spaces, and years on projects using tabs, what's apparent to me is that for most developers, tabs or spaces don't change anything. We adapt easily to one choice or the other.

The only persons for whom it matters, are people with special needs. And for them, tabs are better. Shouldn't this be a done deal?

This is even more true these days, as many languages now have great tools to autoformat our code. If an autoformatter is available for a language, then using it should be a priority. It is SO great to not have ever to think about indentation or formatting.


With tabs, the code will not consistently look the same on everyone's screen anymore, but another thing will become consistent: a good experience for everyone.

This is for this exact reason that the web has introduced media queries like prefers-color-scheme and prefers-contrast. We want to improve accessibility of websites; source codes deserve the same.


So, my recommendations is to set the project settings to fix the differences between operating systems that developers shouldn't have to deal with, and set some preferences like trimming trailing whitespaces.

That's it. Do not set the tab width, it is a user setting.

Forcing the tab width would be like forcing a bright high contrast theme for everyone in the project.


So for example, here's an .editorconfig file:

# https://editorconfig.org

[*]
charset = utf-8
end_of_line = lf
indent_style = "tab"
trim_trailing_whitespace = true
insert_final_newline = true

And a .vscode/settings.json file:

{
    "files.encoding": "utf8",
    "files.eol": "\n",
    "files.trimTrailingWhitespace": true,
    "files.insertFinalNewline": true,
    "files.trimFinalNewlines": true,
    "editor.insertSpaces": false,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
}

(Also, point 3 in the accepted answer — "Making more money" — might be misleading. Developers using spaces could simply be making more money because they're older (so have old habits). Young developers (paid less) could have answered that they use tabs because they press the Tab key when indenting. And there's more, see the comments below the original post.)


TL;DR: I recommend to use tabs and to not force their width (and to use an automatic formatter for everything else if possible). Of cours, this doesn't apply if the project/language you work with doesn't allow it for technical reasons.

Zwyx
  • 349
  • 4
  • 7
  • 1
    Thank you Zwyx on such an elaborate answer. Really appreciate the editorconfig file and the approach to elaborate wider, than only on PHP. I agree with the metaphore of adjusting contrasts etc. for yourself, yet it is important to point out, that your teammates might have sometimes hard time reading your code when at your screen trying to help you. But this might be rather rare case against. Thank you for refreshing thread – yergo Jan 05 '23 at 23:20
  • 1
    Yep. For me it look like a good moment to change the accepted answer to this one. – Jonatas Amaral Feb 01 '23 at 18:28
  • 1
    I used to use tabs only when I was working only with backend development. Now as a fullstack dev, I see 2 spaces as being the norm. Default linting settings will even complain about the use of tabs. I agree with you though, the accepted answer's #3 doesn't mean anything "objectively". My case for using spaces is that that is already the default for the main IDE used in my team (but eventually somebody will come up with a different setting, bringing tabs to the codebase) – Guilherme Taffarel Bergamin Feb 15 '23 at 21:05
  • What do you exactly mean by "consistently looking code"? people will still have different IDEs, themes, fonts, text color and syntax highlighting. What's the value in forcing everyone to use someone's arbitrary preference for indentation? Any modern IDE can show tabs at the width the user chooses, why pin it down to a specific amount of spaces? Who's looking over other dev's shoulders that needs to see all indent exactly with his 2 space fetish? – Petruza Jul 24 '23 at 00:30
  • I think you haven't read my answer @Petruza — I advocate for using tabs and not enforcing their width. – Zwyx Jul 25 '23 at 01:13
  • @Zwyx Oh yes, I've read it, and agree with you mostly. But I still challenge the idea of "consistently looking code" as something that someone should even care about. – Petruza Jul 26 '23 at 18:01
2

With modern day IDEs there is no good reason for using spaces over tabs for indentation.
By far the most given reasons for spaces are:

  • Code consistency across different computers and devs.
    Who wants this? why is this important or desirable?
    Nobody seems to know the answer. I don't mind whether I see other dev's screen and they like to indent with a 2, 3 or 4 space width (and less so with the ever growing remote work). Modern IDEs can show tabs whatever width the user prefers, why force them? each dev knows how to be productive and comfortable.
    We don't force people's IDEs, themes, fonts, text color or syntax highlighting schemes, then why should indentation be different?
    A single Tab character means increment indentation level by 1, easy, elegant, simple.

  • Mixing tabs and spaces is bad.
    Couldn't agree more. Don't mix. Tabs are great for indentation. On the other hand, tabs are terrible for code alignment (if that's your thing) while spaces are perfect for that.

  • Someone could accidentally leave a stray space mixed up with tabs and not notice it
    There are no excuses in 2023 to not be using code linters, git hooks, and any other tools that prevent us from screwing up accidentally and pushing bad formatted code to a shared codebase.

Petruza
  • 11,744
  • 25
  • 84
  • 136
-1

Additional fact:

Regex search expressions in project which uses spaces are different than the in projects which uses tabs or mix tabs and spaces

Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93
  • 2
    Not sure what exactly you mean, but in RegEx `\s` will be treated by most engines as a “whitespace character”: space, tab, newline, carriage return, vertical tab... so it doesn't make any sense. – Farside Feb 16 '22 at 14:22