:set noexpandtab

Google recently published a C++ style guide, containing all the rules that Google code adheres to. Many of the style tips are quite sensible, and well accepted by many developers out there. However, I was surprised to find the following rule:

Spaces vs. Tabs: Use only spaces, and indent 2 spaces at a time. We use spaces for indentation. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key.

I never really understood why so many people have such a hatred towards tabs. Is it just because they have seen code where some editor has mixed tabs with spaces (which of course results in a horrible mess)? Or do they have valid counter-arguments, even when tabs are used consistently?

Why would you force presentation of your code upon someone if you don’t need to? If you use tabs, you don’t need rules like ‘indent 2 spaces at a time’: I can choose whether I want 2 spaces, 4, or whatever indentation I feel most comfortable with when reading code. 

After some discussion, the pro-space people typically come up with the following piece of code, where they have their parameter names aligned:

void SomeClass::someMethodName(int parameterA,
                               unsigned int parameterB,
                               std::string parameterC)

No, you can’t do that with tabs, that’s true. But why would you do that in the first place (unless you’re using an editor which does such annoying auto-formating automatically)? When your method name gets too long, it won’t fit on your screen anyway. Why don’t you indent 2 tabs for your parameter names instead:

void SomeClassWithALongName::someMethodName(
        unsigned int parameterA,
        int parameterB,
        std::string parameterC)

Another popular argument is aligning member declarations:

FooClass foo_;
Bar      bar_;

Same remark: why would you do this? Does it really make your code more readable? Besides, it doesn’t scale: whenever someone comes along and has to add a VeryLongClassName member, your alignment  will be messed up, and you will have to change every member again.

My opinion: let the person who reads your code decide how he/she wants to see it, and lay out your code in a way it is flexible to be seen with different view settings. This avoids lengthy discussions about whether tabs should be 2, 3, 4, or 13 spaces wide. Besides, people have been preaching the separation of presentation and content for ages for HTML and CSS, why would this be any different for code?

Published by

Remko Tronçon

Software Engineer · Hobby musician · BookWidgets