Code indentation and alignment
In this post I try to summarize the different points of view on the tabs versus spaces war.
Decomposition of the problem
Firstly, you need to understand the difference between the tab key and the tab character. What your text editor does when you press the tab key is a matter of configuration and has nothing to do with the problem discussed here.
Secondly, we need to distinguish indentation and alignment, this is explained in TABs vs Spaces. The end of the debate. and shows why the historical rendering of tabs is not fit for alignment.
Use only spaces
This is the solution proposed by many and is notably exposed in Tabs versus Spaces: An Eternal Holy War.
The obvious solution when dynamic doesn't work is to fall back to static. Using only spaces does indeed work for both indentation and aligning and you can configure most text editors to make it as easy as using tabs. So, what's wrong with it ? Here's a list :
- you can't use proportional fonts
- you can't easily change the indentation width
- your files are larger
The two first points are all about freedom, maybe you don't like proportional fonts to code, but some people do.
As to the third point, people usually reject it by saying that it doesn't matter nowadays because of disks capacity, network speed and compression. Still, I wanted to make a quick and dirty measure of the impact of the 4 spaces policy on python 2.6 on my system as of June 2010 ( done in zsh ) :
# cd /usr/lib/python2.6 # for f in **/*(/); do mkdir -p "../python2.6.spaces/$f" "../python2.6.tabs/$f"; done; # for f in **/*.py; do cp "$f" "../python2.6.spaces/$f"; cp "$f" "../python2.6.tabs/$f"; done; # du -h --max-depth=0 python2.6.* 43M python2.6.spaces 43M python2.6.tabs # cd ../python2.6.tabs # sed 's/^\(\t*\) /\1\t/' -i **/*.py # du -h --max-depth=0 ../python2.6.tabs 41M ../python2.6.tabs # sed 's/^\(\t*\) /\1\t/' -i **/*.py # du -h --max-depth=0 ../python2.6.tabs 39M ../python2.6.tabs ... I did it two more times but the rounded number stayed 39M
The result is that using 4 spaces instead of tabs makes files about 10% bigger. If you get a different result or tested something else than python 2.6 I invite you to post a comment.
Use spaces for alignment
Since the problem with tabs is alignment, some people argue that you can use whatever you want for indentation as long as you use spaces for alignment. If you choose to use tabs, the indentation width is no longer an issue and most of the space waste goes away, but you still can't use proportional fonts.
This solution solves all the issues listed here and makes alignment easier. How ? By redefining the way the tab character is displayed. It's all explained in Elastic tabstops - a better way to indent and align code. The downside is that text editors have to be modified.
I use tabs for indentation, spaces for alignment and I wish elastic tabstops were more widely known, implemented and used.