I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

November 9, 2009

Whitespace: The Silent Killer

Ever have one of those days where everything you check into source control is wrong?

Also, how exactly is that day is different from any other? But seriously.

Code that is visible is code that can be wrong. No surprise there. But did you know that even the code you can't see may be wrong, too?

These are the questions that drive young programmers to madness. Take this perfectly innocent code, for example.

code-whitespace-invisible.png

Looks fine, doesn't it? But hold on. Wait a second. Let's take another, closer look.

code-whitespace-visible.png

OH. MY. GOD!

If you're not a programmer, you may be looking at these two images and wondering what the big deal is. That's fine. But I humbly submit that, well, you're not one of us. You don't appreciate what it's like to spend every freaking minute of every freaking day agonizing over the tiniest details of the programs you write. Not because we want to, you understand, but because the world explodes when we don't.

I mean that literally. Well, almost. If one semicolon is out of place, everything goes sideways. That's how programming works. It's fun! Sometimes! I swear!

We got into this industry because, quite frankly, we are control freaks. It's who we are. It's what we do. Now to imagine, to our dismay, that there's all this stupid, useless whitespace at the ends of our lines. Stuff that's there, but we can't see it. Well, those are the nightmares OCD horror movies are made of. I have a full-body itchiness just talking about it.

Depending on how far down the rabbit-hole you want to go, there's any number of things you could do here:

  • Have a post-build step, perhaps something with a regular expression like \s*?$ in it, that auto-cleans extra spaces checked into source control
  • Execute a local macro which removes whitespace from ends of lines
  • Have a special rule to highlight extra spaces
  • Run your IDE in whitespace-always-visible mode, or toggle it frequently

OK, fine, so maybe the world won't explode if there are a few extra bits of whitespace in my code.

But all the same, I think I'll go back and make extra double plus sure no more of that pesky whitespace has accumulated in my code when I wasn't looking. Just because I can't see it doesn't mean it's not out to get me.

[advertisement] JIRA 4 - Simplify issue tracking for everyone involved. Get started from $10 for 10 users.

Posted by Jeff Atwood    View blog reactions
« Preserving Our Digital Pre-History
Parsing Html The Cthulhu Way »
Comments

Imagine how it is for those of us who spend a lot of time in Python world, where the whitespace isn't just an OCD obsession, but can actually modify the functionality of code!

Rizwan Kassim on November 9, 2009 1:51 AM

The Delphi IDE has a neat setting that automatically throws away trailing spaces.

Angus Glashier on November 9, 2009 1:59 AM

"Run your IDE in whitespace-always-visible mode, or toggle it frequently"

A friend of mine calls it "Pac-man mode". All of a sudden you see all of these little dots that need to be gobbled up...

Paul Gordon on November 9, 2009 2:03 AM

> Python world, where the whitespace isn't just an OCD obsession, but can actually modify the functionality of code!

But isn't EOL whitespace irrelevant to Python as well?

Jeff Atwood on November 9, 2009 2:05 AM

@Rizwan : +1 ! We want code to be space sentitive!

Or at least a "Trim Trailing and save" option in Visual Studio as we have on Notepad++

Laurent on November 9, 2009 2:05 AM

Actually, it should be a feature of the IDE. The solution is just a plugin away :-)

Just like in Vim : http://vim.wikia.com/wiki/Remove_unwanted_spaces (let the holy wars begin...)

Steve Schnepp on November 9, 2009 2:06 AM

eclipse also has a "remove trailing whitespace" option.

Stroboskop on November 9, 2009 2:07 AM

I know exactly what you mean. Carefully crafted source code, nicely tucked away in your repository, and then someone with TextMate comes along and automagically adds random whitespace all over the place. Byebye useful diffs!

Stefan on November 9, 2009 2:09 AM

You seem like the perfect candidate to start using the Whitespace language.

http://compsoc.dur.ac.uk/whitespace/

Andre on November 9, 2009 2:10 AM

Eclipse can format your code and/or remove trailing whitespace on save. I think that's the optimal solution.

thSoft on November 9, 2009 2:14 AM

OMG! Whitespace! Makefiles just popped in front of my eyes. Tabs and all that.

Sam on November 9, 2009 2:17 AM

Diffing for no reason is a mortal sin.

Braden on November 9, 2009 2:18 AM

Aside of looking bad, trailing whitespace (or inconsistent tab/space policies or line endings for that matter) can really screw merges in revision control systems and can turn your "blame" (or how that function is named in your version control system) session into a world of hurt because seemingly identical lines actually aren't.

Since I moved over to git, I got really picky about this as the git workflow makes you merge much more often as creating branches is so easy. Also, git is really picky about whitespace too and warns you very loudly if you screw up.

Philip

Philip Hofstetter on November 9, 2009 2:18 AM

I always highlight bad whitespace in vim.
Search for "RedundantSpaces" here:
http://www.pixelbeat.org/settings/.vimrc

Pádraig Brady on November 9, 2009 2:20 AM

@Jeff:
it is. Only "leading" whitespace has any meaning in Python.
Anyway, I set up my Vim to treat whitespace at EOL as highlight as error. Nice.

zgoda on November 9, 2009 2:20 AM

As soon as I found an editor that trims whitespace at the end of all lines, had a sane autoindent/autocomplete/codecolor. My sanity thanked me.

Ólafur Waage on November 9, 2009 2:21 AM

Back in the days of RCS, we developed code in Windows and Unix environments with their differing conventions of newlines. When Windows guys saved a file, they replaced every Unix newline with Windows newline, and vice versa. It was horrible mess: you could never tell which line actually were modified.

Then me migrated to CVS, and due the problems, we also deprecated use of Windows newlines. There was even a trigger that prevented committing files that contained them. dos2unix was to be used every time before commit.

Everything was fine for a few months, CVS making our lives easier, until one day the commit kept failing even though dos2unix was used conscientously.

It appeared that during the realier years, the newline struggle somehow corrupted the files, and it was unrecoverable. Upon every commit, CVS became confused as to what newlines to use and sometimes it reverted them to the Windows newlines. I don't know why, and I don't bother to know why, but this actually happened.

So, why on earth, newlines do matter in plain textfiles when it comes to revision control? You could still store them in whatever format they are, and get them outthe same, but every comparison related operation could ignore the differences sooooooo easily.

Jani on November 9, 2009 2:22 AM

As Sam alluded to, be glad you're not hacking make files. Putting in four spaces where you meant to put in a tab can ruin your day.

Python is easier to deal with. Just set your editor to always insert spaces and you're fine. What you see is what you get. But make files depend on the distinction between tabs and spaces. Hard to imagine that decades later programmers still put up with this.

John on November 9, 2009 2:23 AM

For Visual Studio, the magic shortcut is Ctrl-K,D (Format document). Note that this will not remove extra whitespace at the end of comments, so you might also wish to do the regular expression replace (find :b+$ and replace with empty string).

lini on November 9, 2009 2:24 AM

Hello, I am not one of you but still I enjoy reading this blog. I am looking at your example code and wondering what the big deal is, since I am not a programmer. May I ask where is the bug in the whitespace? Does it make the browser crash? Or does the program behave differently? I have read the comments and I understand that this whitespace can trigger false positives when comparing two versions of a same file using a source control tool. But what is the effect when running the code?

NotAProgrammer on November 9, 2009 2:39 AM

I actually prefer having trailing whitespace in my lines, for a specific scenario: to maintain indentation level. Consider this:

....for (int i = 0; i != 10; ++i)
....{
........DoSomething();
........
........DoSomethingElse();
....}

I prefer the above to this:

....for (int i = 0; i != 10; ++i)
....{
........DoSomething();

........DoSomethingElse();
....}

Barry Kelly on November 9, 2009 2:43 AM

"- Run your IDE in whitespace-always-visible mode, or toggle it frequently"

Or use an IDE that always displays _trailing_ whitespace (and tabs, if indentation mode is set to spaces).

oliver on November 9, 2009 2:44 AM

Unless the VotingImages and CommentText functions render "" tags, the code has an actual bug.

Josh on November 9, 2009 2:57 AM

Oh no, you don't HTML Encode your comments, just strip the offending strings -- anyways that should be "<TD>"

Josh on November 9, 2009 3:00 AM

@NotAProgrammer: Besides space issues (the output will be a few bytes longer), there's nothing wrong. Except that IT IS *HORRIBLE*. It makes you feel like the person who did it should die an horrible fiery death of a thousand burning suns. Twice. A day.

Martinho Fernandes on November 9, 2009 3:11 AM

And I was just deleting some whitespace from end of my lines today... Damn you, copy and paste! ;-)

Incidentally, has anyone done studies into the levels of OCD within software development? I have a mild form (need to check the house is locked a few times before leaving), and some code foibles.

Mike Kingscott on November 9, 2009 3:46 AM

> "Now to imagine, to our dismay, that there's all this stupid, useless whitespace at the ends of our lines."

There are no(*) whitespace-at-the-end-of-the-line issues in Perl.

(*) Except within literal texts, patterns (e.g. regular expressions) and formats.

Yes I'm very smug about it ;)

More seriously one thing I hate about end-of-line whitespace is this issue:

for my $variable (some_array) {
# many
# lines
# of
# code
}

Frequently in code from other people there will be a whitespace after the opening brace, which makes it impossible to click your mouse at the end of the line and jump to the closing brace - instead I find my cursor stuck in the end of some annoying useless whitespace.

Thankfully I can remove all end-of-line whitespace in my editor with a single command, so it's not such a big issue as you make it out to be. I just have to remember to do it :)

Solidstate on November 9, 2009 4:01 AM

Barry: why not let your IDE insert those spaces for you? It's what it does best, after all. It will also create the spaces for you on a new line.

remmelt on November 9, 2009 4:02 AM

Git treats trailing whitespace as a *bad thing*.

Then, when you try to commit code that was written on Windows (CR/LF) it thinks you've got trailing whitespace.

Then you have to add -n on the end of the commit command, particularly if you're trying to commit someone else's Ruby plugin.

I think Macs add CR/LF or not and don't care.

Francis Fish on November 9, 2009 4:04 AM

The problem here is not the whitespace, it is the fact that there are two different languages weaved together with different rules for whitespace (one of which is C# code and one of which is HTML). In the HTML the whitespace means one thing, in the code it means something else (it is insignificant). The programmer has to deal with two different syntaxes in the same file! If the data and code were expressed in the same syntax, this wouldn't be an issue.

If you were using a web framework where the HTML is expressed as code, this issue wouldn't arise. Consider a table in the seaside web framework or a framework for one of the lisp dialects.

html table:
[html tableRow:
[html tableData: 'cell1'.
html tableData: 'cell2'.
html tableData: 'cell3'].
html tableRow:
[html tableData: 'cellA'.
html tableData: 'cellB'.
html tableData: 'cellC']]

(:table :border 0 :cellpadding 4
(loop for i below 25 by 5
do (htm
(:tr :align "right"
(loop for j from i below (+ i 5)
do (htm
(:td :bgcolor (if (oddp j)
"pink"
"green")
(fmt "~@R" (1+ j)))))))))

In these examples you couldn't have the whitespace issue since it is all expressed as code in a single language (and would have to respect the syntax and whitespace rules for one language). This is much more elegant that the template method of mixing HTML & code.

Martin Wickett on November 9, 2009 4:10 AM

A long time ago I wrote an e-lisp function for Emacs to remove trailing whitespace and I call this when I save. Unfortunately sometimes I have to avoid calling this function when editing a file for checking back into version control.

(defun buffer-whitespace-remove-trailing ()
"Function for removing all trailing whitespace in document"
(interactive)
(save-excursion
(beginning-of-buffer)
(while (re-search-forward "[ ]+$" nil t)
(replace-match "" nil nil)
)
)
)

It doesn't handle tabs, and that's deliberate, because in some languages (like Make) tabs are significant.

I, too, would like to know the issue with the above code; all I see is that a line containing several spaces will be interspersed between blocks. Is this so? Did I miss something?

Anonymous on November 9, 2009 4:22 AM

I'm not alone in my freakness.

Josue Gomes on November 9, 2009 4:25 AM

One doesn't need to highlight whitespaces. It's enough to highlight end-of-line.

Daniel Sobral on November 9, 2009 4:30 AM

More than 30 comments, and nobody's mentioned markdown?

Only Joking on November 9, 2009 4:33 AM

I'm sorry, but if your code is affected by trailing whitespaces, that's a problem with the language. We have processors today that are millions of times faster than the big iron of old where processing every byte during a compile took time.

It is a complete waste of a programmer's time chasing down something as ridiculous as that. Terribly inefficient use of resources.

David on November 9, 2009 4:35 AM

It's funny. Lately at work i have been working a lot with Joomla and VirtueMark, they have all this extra white-space. We are talking whole lines with nothing but 20 spaces on them and it's not to keep things indented. drives me nuts...

Samuel on November 9, 2009 4:43 AM

Or pick it up when you diff it before commiting to source control. Picks up other invisible changes like tabs and BOMs also.

David Wilcock on November 9, 2009 4:43 AM

Or pick it up when you diff it before commiting to source control. Picks up other invisible changes like tabs and BOMs also.

David Wilcock on November 9, 2009 4:44 AM

This is where it is nice to have an IDE that automatically removes EOL whitespace.

TM on November 9, 2009 4:51 AM

You need a vacation. Period. Space.

Mr. Orange on November 9, 2009 4:53 AM

Wow, I was seriously beginning to think that I was the only one who obsessed about this.

David Seng on November 9, 2009 5:07 AM

Could someone explain to me why those extra spaces kill the JavaScript?

I mean, they wouldn't cause a problem in C, and that's got one of the worst syntaxes ever foisted on programmers - apparently.

C Programmer on November 9, 2009 5:07 AM

Could someone explain to me why those extra spaces kill the JavaScript?

I mean, they wouldn't cause a problem in C, and that's got one of the worst syntaxes ever foisted on programmers - apparently.

C Programmer on November 9, 2009 5:07 AM

And you really need to fix this double posting bug.

C Programmer on November 9, 2009 5:09 AM

Actually, that are two issues. First, trailing whitespace is just unclean. Aggressive removal causes spurious merge conflicts. (Nothing compared to windows svn users committing dos mode files, though.) Unfortunately eclipse does either sprinkle trailing whitespaces (ugly) or removes *all* of them, even those that were there previously, causing conflicts. git has the decency to only complain *new* trailing whitespace.

Whitespace in HTML/XML is a completeley different issue. The extra spaces in the example don't matter functionally (AFAICS), but make the resulting HTML look bad. On the other side, HTML/XML indenting is formally a bad idea anyway, exactly because whitespace is significant in XML. Only only wonder once why an XML parser returns lots of document data when the document is if the say-nothing (no apparent marked-up text) X'M'L type.

Andreas Krey on November 9, 2009 5:16 AM

Tabs are nice, but you are never sure are there some spaces or tabs, until you check. Also some tools handle indentation trimming differently than others, which is confusing.

Silvercode on November 9, 2009 5:23 AM

Or... just take a deep breath, a little yoga, and move on with your life. I know, it's not that easy. But readers, please don't mistake an obsession with whitespace with being a good coder (Jeff, I know you aren't making that argument).

I've been coding for years. Wrote a couple of books on the subject. And this has never, ever bothered me. I run the code cleanup plugin in the IDE occasionally and am absolutely fine.

Will on November 9, 2009 5:25 AM

I also dislike terminal whitespaces, but I didn't see the point of saying 'OH MY GOD!' I tried for a long time to see in which way those spaces would break the code. That would be the only thing that would cause such an outrage.

As I said I also dislike them, and I delete them whenever I get the opportunity, but with source control diffs that can ignore whitespace I don't see it like a big problem and have learned to live with it (especially in a bigger team where some are not that concerned about it).

Radu on November 9, 2009 5:28 AM

I think that caring about extra [trailing] whitespace is a little bit OCD-wise. But I'm guilty as charged :P

On the other hand, I find that a little bit contradictory: yes, it's wasted bandwitdth, but so is the one spent on tabbing tags. I suppose the *correct* OCD solution would be to strip *all* of the superfluous whitespace.

Boro on November 9, 2009 5:31 AM

GitX (http://gitx.frim.nl/) highlights end-of-line whitespace, so as long as I'm paying attention, I can catch it before it's committed.

Stephen on November 9, 2009 5:48 AM

At first I honestly did not see what was wrong, but after re-reading and learning of the mistake, I felt dirty, violated and wrong.

Off with the extra spaces.

Patrick on November 9, 2009 5:48 AM

Check out the built in macro in VS Samples->VSEditor->FixLineEnds - might just be what you are looking for!

Brian Schmitt on November 9, 2009 5:50 AM

What's the big deal? It might be a remnant of removed comment.
Completely harmless and irrelevant.

Azarien on November 9, 2009 5:50 AM

I'm just cheering that you indent with spaces rather than hard tabs. That way when I try to maintain your code, it looks consistent no matter which tools I use.

Chris Noe on November 9, 2009 5:51 AM

Trailing whitespace breaks our product builds all the time because C compilers don't treat it portably in multiline #defines. Some compilers object to space after the continuation characters '\\', and others let it fly, allowing a build break on a different platform build. This topic causes a suprising amount of grief. Some people configure their editors to remove it, but since everybody doesn't do so, it can easily muck up version control systems that have merge capability.

Peeter Joot on November 9, 2009 6:02 AM

"Imagine how it is for those of us who spend a lot of time in Python world, where the whitespace isn't just an OCD obsession, but can actually modify the functionality of code!"

this is why whitespace is evil.
Think of all the wars that could have been avoided if python didn't require tabs!

Eric on November 9, 2009 6:06 AM

Weird how Jeff thinks he speaks for all programmers.

Joey on November 9, 2009 6:16 AM

I don't like to be filling my screen with even more characters, but one handy trick is to set the 'visible whitespace' character color to your background color.

Most of the time it's invisible, but select the text and it pops out.

ieb on November 9, 2009 6:25 AM

People, it is time for all of you to discover the Tab-key.

securityhorror on November 9, 2009 6:25 AM

"this is why whitespace is evil.
Think of all the wars that could have been avoided if python didn't require tabs!"


Python doesn't require tabs -- it requires tabs OR spaces. The number of spaces is irrelevant so long as it is consistent.

Python and whitespace is NOT evil because it demands you pay attention to levels of indentation (GOOD) thus the readability of the code, to humans and to the parser, is guaranteed. Debugging is therefore very easy.

Trailing space is irrelevant. Any programming paradigm that still pays attention to space or tabs after a statement (unless of course its quoted) is a ridiculous hack and should be consigned to the dustbin.

Craiggybear on November 9, 2009 6:26 AM

I know I'll get flamed for this, but VB5 and QuickBASIC both remove whitespace at the end of lines AND they also convert tabs to spaces.

Yes, I actually use both languages to do serious work.

Matej Horvat on November 9, 2009 6:33 AM

So this non-visible code that is wrong -- where are the unit tests that demonstrate the failure?

Hugh Brown on November 9, 2009 6:34 AM

I am neither a C# programmer nor do I have experience with ASP (or ASP.NET). So can someone explain the issue here?

In my naive view, because the whitespace is not within ASP tags (), it will just be between the table start tag and the tr start tag, but this would not be a reason to say "Oh my god!".

GodsBoss on November 9, 2009 6:35 AM

Jeff,

Your whitespace is the least of your problems when it comes to that code:

1. you're missing the tag.
2. Why are you even marking up comments as tables at all? It's *not* tabular data.

I find it funny that you reacted to the whitespace but completely missed the above. I certainly wouldn't leave my markup in your hands :)

Andy on November 9, 2009 6:35 AM

Configure your IDE / editor to hightlight trailing spaces. Configure your diff tool or your version control system to highlight whitespace errors like trailing space.

Enable pre-commit hook that checks that you do not add trailing whitespace (and other important checks, like committing file with merge markers).

If you work cross-platform and end of line character matter (CRLF vs LF vs CR) configure your version control system to do the conversion automatically.

Captcha: stopgaps those

Jakub Narębski on November 9, 2009 6:36 AM

meh.

The <td&rt; got stripped out.

"Your comments: (no HTML)" yet I have to write using HTML entities? C'mon, Jeff. You need to fix that.

Andy on November 9, 2009 6:39 AM

I always used to think coding with visible whitespaces was annoying, but then I changed their color so they're just barely visible.

Now I can see them all the time but they're not in my way! WIN-WIN!

weazl on November 9, 2009 6:40 AM

This entire post was about the extra whitespace at the end of the first line? Seriously?

Brad on November 9, 2009 6:44 AM

For those who are confused "trailing" means after the line (referring to the first line).

In case anyone wonders why that is a big deal. Imagine trying to add code to the end of the line. You hit the "end" key and your cursor flies off to netherland. Ok. Not too big a deal. Now imagine that you need to add something to the end of 300 lines that all have extra white space and you have 5 minutes.

Yeah. Now it's a big deal.

Practicality on November 9, 2009 6:51 AM

Source Insight can remove trailing whitespace.

Trailing spaces once cost me 3 days. It was a Windows 2003 sysprep.inf, configuring multiple network adapters. The INF looks basically like this:

name=Adapter1
[Adapter1.Settings]
setting1=value

You can imagine what trailing spaces after "name=Adapter1" would do...


Also recently, I copied some vbScript samples from the web, and got weird "compile" errors, which were probably caused by incorrect CRLFs in those samples. I don't know why they happened.

Jonathan on November 9, 2009 7:01 AM

If this really gets under your skin, it seems like occasionally highlighting a few lines in the IDE with a click and drag would show the trailing whitespace. If you don't like the spaces, delete them. "Problem" solved... Some things just don't need to be over-thought. Not every problem demands a software/tool-based "solution."

A repository can hold things other than code, too. You can't just assume that trailing spaces never matter. Someone put them there. Might be they had a reason.

Maybe I'm just not getting it. Big deal.

Big Deal on November 9, 2009 7:11 AM

Well, at least we saw code in this posting.

captcha: foot blastoff (keep that gun pointed away from my foot!)

AC on November 9, 2009 7:17 AM

I use vim and I use the following to detect leading/trailing whitespace chars.

" Borrowed from http://docs.google.com/View?docid=dfkkkxv5_65d5p3nk
if v:version >= 700
set list listchars=eol:\ ,tab:>-,trail:.,extends:>,nbsp:_
else
set list listchars=eol:\ ,tab:>-,trail:.,extends:>
endif

This shows '[tab]foo bar ' as --->foo bar.. (with specific coloring to differentiate from real chars)

Justin on November 9, 2009 7:17 AM

There are a few comments here that ask something along the lines of "why is this wrong? The compiler/interpreter/browser can still handle it, it doesn't break any tests."

We don't write our programs for machines, we write them for the next programmer.

Paul on November 9, 2009 7:18 AM

While not directly related to whitespace issues, I think what Martin Wickett made a pretty good point above. It feels dirty to me to have two different languages (C# and HTML) "weaved together".

I know that's normal for ASP.NET MVC, but is there a better way?

Would html helper methods or user controls just move the problem to a different file without improving anything?

This seems far LESS readable to me:

...

public List CommentRows(object Model)
{
List Rows = new List();
foreach (var json in Model) {
HtmlTableRow r = new HtmlTableRow();
r.id = "comment-" + json.id;
r.class = "comment";
r.Cells.Add(VotingImages(json));
r.Cells.Add(CommentText(json));
Rows.Add(r);
}
return Rows;
}

Zack on November 9, 2009 7:21 AM

While not directly related to whitespace issues, I think what Martin Wickett made a pretty good point above. It feels dirty to me to have two different languages (C# and HTML) "weaved together".

I know that's normal for ASP.NET MVC, but is there a better way?

Would html helper methods or user controls just move the problem to a different file without improving anything?

This seems far LESS readable to me:

<%= Html.Table(CommentRows(Model)) %%gt;

...

public List CommentRows(object Model)
{
    List Rows = new List();
    foreach (var json in Model) {
        HtmlTableRow r = new HtmlTableRow();
        r.id = "comment-" + json.id;
        r.class = "comment";
        r.Cells.Add(VotingImages(json));
        r.Cells.Add(CommentText(json));
        Rows.Add(r);
    }
    return Rows;
}

Zack on November 9, 2009 7:23 AM

Aww come on, any UNIX user is going to tell you that spaces are more portable!

I was going to make a bumper sticker that said "Every time you use spaces instead of tabs to indent your code you kill the earth a little more because your compiler's parser has to work harder" , but could not find a way to shorten it.

"Indent with tabs ... or this kitten gets it!" seemed more practical, but would offend too many people.

I may settle on a T shirt that says "hg revert ..."

Tim on November 9, 2009 7:25 AM

While not directly related to whitespace issues, I think what Martin Wickett made a pretty good point above. It feels dirty to me to have two different languages (C# and HTML) "weaved together".

I know that's normal for ASP.NET MVC, but is there a better way?

Would html helper methods or user controls just move the problem to a different file without improving anything?

This seems far LESS readable to me:

<%= Html.Table(CommentRows(Model)) %gt;

...

public List CommentRows(object Model)
{
    List Rows = new List<HtmlTableRow%gt;();
    foreach (var json in Model) {
        HtmlTableRow r = new HtmlTableRow();
        r.id = "comment-" + json.id;
        r.class = "comment";
        r.Cells.Add(VotingImages(json));
        r.Cells.Add(CommentText(json));
        Rows.Add(r);
    }
    return Rows;
}

Zack on November 9, 2009 7:25 AM

Seriously, most of you just need to chill. Get yourself a merge tool that can ignore white space differences and forget about this non-issue. There are many, many things more important to your productivity and your company's bottom line.

And yes, I am a programmer

John on November 9, 2009 7:26 AM

sorry about the multipost. I'm giving up on trying to get the formatting right.

Zack on November 9, 2009 7:26 AM

The problem, at least as I see it, is that it is an awfully bad hack to start sticking lines of code into markers. The whole thing is so utterly cryptic that it's a wonder you can type it in at all. It's an example of bad technology (from poor syntax), not of problems with whitespace. The whitespace issues are secondary (the symptom of the disease).

If the technology sucks, one sure sign is that little changes can cause mystifying effects. That type of embedded instability makes it hard to deploy consistently, which makes it very stressful to use. If it wasn't for the Internet (and easy access to answers) we'd no doubt avoid these types of crappy technologies, and they'd die natural (and much deserved) deaths.

We should really start a "just say no to super-fugly technologies" campaign. They seem to linger far too long these days.


Paul.

Paul W. Homer on November 9, 2009 7:28 AM

Seeing as how nobody has attempted to bring the joy of Spark into this thread I will have a go.

There are view engines for MVC that suck less, handing the integration of code and markup much more cleanly than the multiline beesting nastyness of the default view engine.



Ryan Roberts on November 9, 2009 7:29 AM

At least in corporate "enterprise application" code, the problem with trailing whitespace is that it often indicates cruddy, cut-n-paste coding by cut-rate, one-size-fits-all, lowest-bid consultants.

Invisible trailing whitespace often indicates randomly indented code too.

Both of these things (cut-n-paste shortcutting know-nothing quick fixes, and semi-random indentation) cause different problems, but have some of the same "leading indicators", including trailing whitespace.

Bruce Ediger on November 9, 2009 7:38 AM

Throw this in your .vimrc, problem solved:

autocmd BufWritePre *.cs :%s/\s\+$//e
autocmd BufWritePre *.aspx :%s/\s\+$//e

Paul Betts on November 9, 2009 7:40 AM

I'm afraid I'd have to argue against any extra whitespace (trailing or leading) when dealing with HTML generating code.

I know that bandwidth isn't a major concern for many people, but when generating the HTML in a loop, please remember that every bit of extraneous whitespace is an extra byte (or two) of data that must be transmitted that has no purpose to the end-user (it just makes the generated HTML easier to read).

The example above would generate 24 bytes of "end-user useless" whitespace per iteration of the loop. If the loop executed 10 times per page view, that's 240 bytes. 5,000 page views x 240 bytes = 1,200,000 bytes (1.14 MB)

I would at least consider having a process that would remove the leading whitespace in production code, or alternately, a process that would add the whitespace to the source dump of code for testing.

Scott on November 9, 2009 7:49 AM

I fail to see the problem in the snippet you provided. Unless it is important in the look of the generated HTML.

Well, a long time ago, I have set the option in my text editor, SciTE, to strip trailing whitespace, and I happy with this setting. That's an alternative to your options (ie. a built-in feature of the editor).
And I don't have the problem of Barry Kelly: it is smart enough to keep the indentation of the last line with indentation, and to keep the caret position when running over empty lines.

In Eclipse, I use AnyEdit Tools to take care of these extra spaces.

PhiLho on November 9, 2009 7:57 AM

Funny, my first thought was "what's wrong?"... and then as I read on, I realized I'd subconsciously assumed that, had I gotten my hands on that code, I would've instinctively deleted those spaces. That stuff drives me nuts too.

Daniel on November 9, 2009 8:17 AM

There are html optimizers for web servers that can be employed on the job (although general value additions is quite negligible). Also I found following CodeProject article trying to do similar stuff.

http://www.codeproject.com/Articles/38067/Compress-Response-And-HTML-WhiteSpace-Remover.aspx

Hasith on November 9, 2009 8:24 AM

Oh. My. GOD! You care more about meaningless whitespace than using semantically correct markup. What a noob!

Josh Stodola on November 9, 2009 8:31 AM

Haha, so true!

Ian Devlin on November 9, 2009 9:12 AM

If white-space causes such issues and this many comments, the programming world indeed has gone backwards...

Steve on November 9, 2009 9:20 AM

Only downside to that /\s+$/ search:
What about languages that let you specify blocks of text? That whitespace may be useful for display-formatting purposes. Suddenly that simple regex gets a lot nastier (if it can even be done in regex).

Granted, that likely means you're doing something wrong, but sometimes adding a space or two to align things is the easiest fix.

Otherwise, I completely agree, and have done similar things for a while. But I must admit, my first shock-reaction was "OMG spaces not tabs!" Spaces are a royal pain, as they lock-in the layout of your code. Use tabs, and IDEs can display them however you like, and usually auto-align things correctly, where spaces explicitly break auto-formatting behavior.
Yes, some languages freak at tabs. Clearly they're exceptions.
Maybe, some day, we'll get elastic tabstops in regular editors. They rather nicely eliminate repetitive tabs / spaces.

Groxx on November 9, 2009 9:58 AM

and that from a freaking coder who thinks two whitespaces is good for users to use as markup language

sunfire on November 9, 2009 10:24 AM

Okay, I'm now forcing my VS to indent code with 5 whitespaces instead of 3

offler on November 9, 2009 10:32 AM

I leave whitespace visible but set the color to a very low contrast with the back-ground--e.g., light, light gray against white. I can see it quickly by squinting but it doesn't get in the way when I'm concentrating on the code.

If only I could set whitespace color in Eclipse :p .

Brett on November 9, 2009 10:50 AM

Removing trailing whitespace on save is always a good thing. Even if there's no functional difference, it's nice to be able to compare versions in your SCM without having to worry about whitespace. Now, don't even think about opening the "space vs. tab" can of worms!

Simon on November 9, 2009 10:56 AM

Did we all get in to this industry because we are 'control freaks?'

Igore on November 9, 2009 11:06 AM

Really? I mean ... really?!?!

Dave on November 9, 2009 11:20 AM

"If you're not a programmer, you may be looking at these two images and wondering what the big deal is. That's fine. But I humbly submit that, well, you're not one of us."

I humbly submit that you're not one of us either...

lolatwood on November 9, 2009 11:39 AM

Gool old Notepad2:
Auto strip trailing blanks option (File, Line Endings, Default)

mosaic on November 9, 2009 11:47 AM

zzz... I thought this post was going somewhere - but then it didn't. I was wondering 'what am i missing' and when the big reveal was some whitespace I died a little.

@lolatwood - funny :)

sleepysmurf on November 9, 2009 12:04 PM

KDevelop has a setting to strip all trailing whitespace on saving. However this won't be visible in the IDE until you close and reopen the file. I like the idea of a code cleaning bot that runs via commit hook/cronjob and tidies up with simple rules like trailing whitespace, extra line break at the end of each text file, tabs to spaces etc.

Chris on November 9, 2009 12:37 PM

CTRL+K, CTRL+D baby.

Jefferson Taylor on November 9, 2009 12:49 PM

Dude, Jeff, calm down.. it's just a bit of space.

stuckinphp on November 9, 2009 1:10 PM

$foo =~ s/.*?\s+// if it bothers you that much.

I prefer languages where whitespace doesn't matter to the compiler - C, Perl, Lisp...

Paul N on November 9, 2009 1:38 PM

If the problem is the extra bytes sent over the network, perhaps the ASP template engine has an option to strip the whitespaces on the fly ? Another option is compressing the response, I don't know how to do it in ASP but with servlets is easy to do, and the browser takes care of the unzipping automatically. This is convenient for very heavy pages of course. In any case, I prefer the readability provided by the extra spaces.

lluis on November 9, 2009 1:39 PM

Different material. I will try this. Thanks so much :)

GORGO on November 9, 2009 1:42 PM

If that code ends up getting downloaded, like with JavaScript, HTML, or CSS, the extra white space wastes download time, and costs money. I bet the world could save hundreds of dollars by taking out the trailing spaces.

Kirk Cerny on November 9, 2009 1:43 PM

Whitespace.
You can't see it,
it must not matter.
If it does,
Tool broken.

captcha: Danner peet

Dopey on November 9, 2009 2:16 PM

People who don't care about whitespace, don't have to deal with merging code. I make sure everyone I work with has to fix their own whitespace merge conflicts. Sometimes they even learn to set their IDE up correctly.

The next question is; should we extend this to automated code formatting? Personally I am not willing to take that step yet, because I don't like any automated code formatters, and more importantly all the code I write is formatted correctly. :)

Mike Miller on November 9, 2009 2:17 PM

White space has rights too!

Steve on November 9, 2009 2:20 PM

I agree... OH. MY. GOD! If I ever saw this in my code I would kill the mofo who did it. Luckily I've not had that problem... yet.

OCD Follower on November 9, 2009 3:02 PM

We have one developer here (only one) who doesn't run with Visual Studio's "Auto-Format on Save" feature enabled. You can always tell when he was the last person to check in a file. Well, you can tell when you're diffing your own changes at least.

Tullo on November 9, 2009 3:06 PM

Trailing whitespace and tabs (bird tracks in Visual Studio) should definitely be removed from the end of lines. Sometimes I think my colleagues are trying to encode Morse code with a combination of tabs and spaces.

Daniel Ballinger on November 9, 2009 3:39 PM

In Python, EOL whitespace can be relevant!
Try the following piece of code out:

if condition1 and \...
condition2
....block of statements

Python will complain about that trailing whitespace after the line-continuation character!

a_m0d on November 9, 2009 3:41 PM

I'm surprised! I use Kate for editing and I always thought that *every* decent editor/IDE had a "remove trailing spaces" option.

Angel on November 9, 2009 3:49 PM

Stack Overflow: How to automatically remove trailing whitespace in Visual Studio 2008?
http://stackoverflow.com/questions/82971/

Daniel Ballinger on November 9, 2009 4:03 PM

I guess that's why my editor has a function to strip white space off the ends of lines. Ultraedit 32. But I don't have a key assignment for it. Not that there's much that I need to do with that, it's usually the data that I use that on.

Bryan Price on November 9, 2009 5:43 PM

I couldn't agree more!
What you need in your settings is, replace tabs with spaces, and a tab spacing of 2 or 4 (I used to use 4, but with web pages that can push it too far out).
Tab spacing of 8 is very 1970's assembler!
Otherwise, the formatting depends on what tools you view the source in, which can seriously mess up the alignment.

Bruce Hatton on November 9, 2009 5:55 PM

I let emacs silently remove trailing whitespace on every save:

(add-hook 'before-save-hook 'delete-trailing-whitespace)

Yes, my diffs are occasionally larger than necessary, but that's not my fault, it's the guy before me who left all that garbage in the file.

And once I had a multi-line C macro in a header file with CRLF line endings. Compiling on Solaris, only the CR was escaped, leaving LF intact and breaking the macro. Took several pairs of eyes before we figured out why the macro was breaking the compilation in strange ways.

Martin on November 9, 2009 6:00 PM

Ctrl+A, Ctrl+E+C in Visual Studio takes care of those pesky, non-conforming outsider characters along with other formatting gaucherie.

John Q. Public on November 9, 2009 6:33 PM

To those that say that there's no problems with trailing whitespace because the language can handle it, there's an awful lot of other things that languages can handle just fine that we generally avoid doing. I see it as an issue of productivity, as the existence of trailing whitespace makes the End key pretty useless.

SL on November 9, 2009 6:34 PM

Right, don't forget to set your editor to strip all trailing white spaces. Matter closed. Now, can we stop congratulating ourselves for our freakishness? This thread is really starting to freak me out.

Parenthesis on November 9, 2009 7:21 PM

Check out Perl::Tidy, and to a greater OCD extent, Perl::Critic. It turns out your language can AUTO-FORMAT ITSELF ANY WAY YOU WANT IT TO if it were a little bit smarter. You want cuddled elses but your colleagues don't? No problem, just Tidy it to the group's standard when you commit (which Eclipse will do for you) and Tidy it back on update. Works for all whitespace and all punctuation, plus comments, array formatting, etc.

Oh, and if you really want to see some whitespace coding horror, check out the Acme::Bleach novelty module on CPAN. It replaces your source code with a series of non-printable whitepaces which, when interpreted, produce the same run-time as the original code.

use perl on November 9, 2009 9:47 PM

I tried Acme::Bleach once and it destroyed the code. Maybe it was because it was Perl 5.004 on HP-UX or something.

I also loved that the Delphi IDE automatically removed trailing whitespace.

I guess I must be more hardcore OCD than Jeff, because I often go through the code and check for trailing whitespace manually! Though I find it's only a problem if I copy/paste.

Trailing whitespace is boring. Tabs vs spaces is the real horror!

John Ferguson on November 10, 2009 1:32 AM

I might be wrong, but isn't \s*?$ a non-greedy match to any number of trailing whitespace? Won't this always match exactly 0 characters of whitespace? Shouldn't it be: \s*$

Oliver on November 10, 2009 2:11 AM

What whitespace at the end of the lines?

signed: the VB guy

(I know, I know... in the example above, also for VB guys the whitespace would not be trimmed)

Dejan on November 10, 2009 2:31 AM

May be worth saying too that most companies (and here I'm thinking those situation where there's more than one person committing to the repository) enforce the removal of trailing whitespaces on their code guidelines documentation.

This is also, as far as I know, a common guideline among open source projects.

I'm surprised however as to why Jeff ignored the setting on most editors used for coding (modern and old alike) that automatically remove these on save. This setting alone removes the need for his three proposed solutions.

But assuming such an editor feature wasn't present or couldn't be present for some reason, it's worth saying that most diff tools can also ignore trailing spaces at our request.

Mario on November 10, 2009 6:48 AM

I've recently switched to tab formatting in designer HTML in Visual Studio, and the reason is simply payload size of the page. Using Jeff's example, the the 48 space characters (not including the offending trailing white space on Line 2) could be replaced with 6 tab characters (assuming the Visual Studio default formatting setting of 1 tab == 4 spaces) and still retain the same visual layout. That amounts to a 12.5% reduction in size just on formatting. How's that for OCD?

I'd like to minify all my .as?x files, like I'm doing with all CSS and JavaScript files, as part of a build step, but haven't built/found a tool for that yet.

Craig Boland on November 10, 2009 7:18 AM

What I find most shocking about this is that anyone gives a sh*t. Nothing better to do, I guess.

MR on November 10, 2009 8:15 AM

Just thought my captcha was amusing:

heinie but

Joe on November 10, 2009 8:30 AM

Sounds to me like you are complaining about the symptoms, not the problem.

Here are the problems as I see them:

1. You are using a language with ASP-style syntax. Didn't you get the memo that those suck? They eventually trend toward unmaintainable.

2. You are using a merging repository with < 10 developers. You aren't writing the freaking Linux kernel!!! You don't need merging, it just causes all kinds of problems. Tried and true locking is the best solution when you can easily divide the work between modules. I love locking, because then I can just set Visual Studio to conform the code to the way I like, and the next guy the same. Ctrl-K Ctrl-D and it's all good.

3. Was your diff tool written in 1990? Because WinMerge has been ignoring whitespace, blank lines and CR vs CRLF for at least that long. Seriously, there are diff tools that can't do this in 2009? I would have never guessed.

4. You are using an IDE which doesn't do code cleanup for you. Set your style and have the IDE conform the code to it for you. Nice and consistent.

5. Somebody checked in a bunch of spaces at the end of a line.

PRMan on November 10, 2009 9:01 AM

Oh, this is definitely my favorite blend of OCD. Fits snuggly right next to lining up opening and closing brackets to suite your particular tastes. Nothing is quite as satisfying as knowing that everything you don't see is in order. Until you do something with it that is... Which is why you'd better make the invisible bits visible.

A very good idea for a post! You could've gone on longer though..

JPH on November 10, 2009 9:42 AM

Wow, you people are all crazy :)

Doug on November 10, 2009 10:18 AM

I'm a programmer, and I don't give a damn about terminal whitespace.

I only care about indentation because it improves comprehensibility.

(And seriously, what PRMan said. ASP syntax? You have far bigger problems than terminal whitespace.

But I completely disagree with the idea that smaller teams don't need merging... at least unless you've broken all your code into a few thousand 50-line modules. Which is its own unique and pointless hell.)

Sigivald on November 10, 2009 10:43 AM

This has to be a joke. Almost immediately after a post where you were deluged with complaints about how absurd the markup requirement to put whitespace at the end of lines to get line breaks, you make a post complaining about whitespace at the end of lines?

Then seeing all the OCD people complaining about whitespace who also support something as "unclean" as indenting with spaces is just...strange.

Anonymous on November 10, 2009 12:22 PM

Srsly kdiff3 can ignore whitespace. I'm sure any decent diff/merge tool can. Who cares?

Nick on November 10, 2009 1:03 PM

To Nick: any difftool can ignore whitespaces I guess too, unfortunately ignoring whitespaces that aren't at the end of lines can hide important changes and thus should perhaps not be done.

Marc on November 10, 2009 1:14 PM

I submit that an important part of being a nerd is knowing which things to obsess over and which things to let go. To paraphrase Dave Chappelle, pick your spots.

If you're using a language in which whitespace is not significant, I recommend choosing something else to obsess over.

KT on November 10, 2009 2:32 PM

It is nice to know I'm not alone in my Code Whitespace OCD.

Dave on November 10, 2009 3:59 PM

Locking? Surely you are joking, mr PRMan. I thought no one used locking version control since about the time fire was discovered...

Joe on November 10, 2009 4:10 PM

Ctrl+E,D

tb on November 10, 2009 4:14 PM

Guess I'm not one of you ... Thank goodness too 'cause otherwise I'd have to have myself committed for being overly anal.

any mouse on November 10, 2009 4:20 PM

@a_m0d:
> In Python, EOL whitespace can be relevant!
> if condition1 and \...
condition2
> Python will complain about that trailing whitespace after the
> line-continuation character!

That's not Python specific, and has nothing to do with the Pythonesque kind of whitespace-significance (that is indeed beginning-of-line only). It's just a consequence of the fact that, if you want to escape a character, you have to put that character immediately after the backslash. E.g. if you're in a string and you want to insert a quote mark*, you might write \"; \[space]" wouldn't work. So if you want to escape an end of line, of course you have to have the backslash write before the end of line; otherwise you're just escaping a random space.

So that's not really an instance of actual significant whitespace any more than the fact, if you have a variable "foo", you can't refer to it as "fo o", means that that language has 'significant whitespace.

Simon on November 10, 2009 4:20 PM

Other than the fact that whitespace, like case (...yes I said CASE...why should GROSSPAY, grosspay, GrossPay, or grossPay mean different things or be scoped differently? Why? WHY!? Ok...I got off on a bit of a tangent. Sorry.) shouldn't matter, it can cause problems.

I remember beating my head for two days over a piece of code that refused to compile. I'd stare at the line and tweak it one way or the other to no avail. Out of desperation I deleted the entire line and retyped it from scratch. It worked. Comparing the old and new code, I found ONE SPACE at the end of the line that didn't work.

It's hard to debug something you can't see.


Dave D on November 10, 2009 5:48 PM

It worked. Comparing the old and new code, I found ONE SPACE at the end of the line that didn't work.

aion items on November 10, 2009 5:57 PM

You left out one option regarding what to do to solve the whitespace problem. When I code, I use the Home and End keys ridiculously often. If you're like me, it's quite simple to see when you have some trailing spaces - chances are you'll see it by chance when you're just navigating the code! A lot of IDE's have customized it by default to make the Home and End keys ignore whitespace - so Home will take you to the start of code -following- the indentation, and End takes you as far as the start of trailing spaces. Usually double-tapping Home or End will take you to the -real- start or end, though, so I've become rather accustomed to that as well.

JaredMT on November 10, 2009 9:09 PM

Even at the start/end of scriptlets, we are inserting a new lines which are unnecessary. That costs us few bytes.

Jai on November 10, 2009 9:21 PM

Why haven't you started putting those ) chars hard up against the preceding (following) elements? All those newlines and spaces in front of (after) them are also getting sent to clients, you know. As an added benefit, doing this as part of your coding standard would fix the strange-space-between-my-images issue that crops up from time to time. Doing this doesn't have to make your code unreadable dross.

Using your example, the code would change to:
" class="comment">

Now any extra trailing whitespace on most lines here is server side only (the closing table tag could leak spaces to the client), and your bandwidth consumption will drop by a tiny fraction more.

Richard Atkins on November 10, 2009 10:42 PM

I pad all my code to the 80th column with spaces. Cheaper than medication.

Dave on November 11, 2009 1:47 AM

In vim you can get rid of any trailing whitespace by adding the following to your ~/.vimrc

autocmd BufWritePre * :%s/\s\+$//e

petepete on November 11, 2009 3:19 AM

The problem with "strip spaces on save" is that it only works it everyone on the team is using it and since the beginning of the project.

If you have an existing codebase with trailing spaces and turn this setting on, you'll have tons of spurious, unrelated "diffs" even for a one-line fix.

Daniel Serodio on November 11, 2009 7:25 AM

I didn't see the problem with the code, mostly because I was expecting something that would actually cause an _error_. When you finally started talking about trailing whitespace though, my brain caught up and yea... that pisses me off to.

The real problem is Visual Studio creating it seemingly at random every time you turn around.

Actually, it wouldn't bother me if it didn't screw up keyboard navigation. End should take me to the end of the text, not to the end of crappy unnecessary trailing whitespace!

Telos on November 11, 2009 8:49 AM

Don't care... extra white space is ignored, I'm sure it doesn't end up in your compiled code and that's all that matters.

Kris on November 11, 2009 10:32 AM

Why not diff -bB, that seems to ignore most whitespace differences.

Hugh Gallagher on November 11, 2009 11:44 AM

Trailing spaces do not matter really. I, personally, think that programmer should suppress all this control freakness in himself. It is a step to become professional. If you can't make a difference between important and non-important, you can't make anything real, it will always force you to rewrite infinitely to make code "perfect". But the real code is the one which released and works, it does not need to be perfect. The cost of perfectionism is too high.

vtolkov on November 11, 2009 1:16 PM

The problem with trailing white space is that it can ruin the formatting of the code when you're adding/deleting parts of it. Bad formatting can RUIN readability and absolutely grate on the nerves of people with OCD. Fixing bad formatting takes precious time and developmental resources.

John on November 11, 2009 5:40 PM

The problem with trailing white space is that it can ruin the formatting of the code when you're adding/deleting parts of it. Bad formatting can RUIN readability and absolutely grate on the nerves of people with OCD. Fixing bad formatting takes precious time and developmental resources.

John West Minor on November 11, 2009 5:41 PM

The problem with trailing white space is that it can ruin the formatting of the code when you're adding/deleting parts of it. Bad formatting can RUIN readability and absolutely grate on the nerves of people with OCD. Fixing bad formatting takes precious time and developmental resources.

John West Minor on November 11, 2009 5:41 PM

The problem with trailing white space is that it can ruin the formatting of the code when you're adding/deleting parts of it. Bad formatting can RUIN readability and absolutely grate on the nerves of people with OCD. Fixing bad formatting takes precious time and developmental resources.

John West Minor on November 11, 2009 5:42 PM

"We got into this industry because, quite frankly, we are control freaks. It's who we are. It's what we do."

lol. Yes, that's who we are!

World Cruises on November 11, 2009 7:20 PM

John. Judging by your quadruple posting above, I'd say that trailing white space is the least of your problems. For most people (but evidently and surprisingly not everyone) they are a trivial irrelevance that is easily dealt with - if they are even noticed.

Vince on November 12, 2009 12:50 AM

whitespace at end of line doesn't bother me that much, but if the code contains tab indented lines, and space indented lines, then I go mad! It's not that I prefer one over the other; in some projects I use one tab, in others I use two spaces.

Marius Gundersen on November 12, 2009 1:03 AM

That's not really a hard problem to solve:
* Mutually accepted coding conventions.
* Automatic code formatting before committing.
* Everybody in the team made to setup their IDE right.

Biggest hurdle is getting everybody to accept the coding conventions.

Whitespace definitely is not a non-issue, although trailing whitespace is lot less a problem than wrong indentation.

Jukka Dahlbom on November 12, 2009 5:42 AM

Im more worried about the horrible spaghetti code you seem to write, what happend to code separation ?

Are you really doing this with code you sell to customers ??

HJ on November 12, 2009 6:20 AM

The real thing to blame here is the fact that version control systems are still in the 80's and match source code as if it were simple text. If Version control systems were not language agnostic, they would never flag trailing whitespaces as diferences, neither putting "{" on the same line vs next line, etc.
One could checkout code and see and edit it with his/her preferences and upon commit it would be converted to an internal representation that abstracted all those differences that did not affect program semantics.

Even if you commit code with lots of spaces in the end (for some weird reason), if those spaces did not affect the program, they would be deleted.

Tiago Almeida on November 12, 2009 6:45 AM

As much as I agree, (if I saw that whitespace, I would almost certainly delete it, even if it was just some irrelevant sample code I was looking at) a commit where the only thing changed was a bunch of whitespace taken out is one of the most ridiculous things ever.

Ortzinator on November 12, 2009 6:46 AM

"We got into this industry because, quite frankly, we are control freaks. It's who we are. It's what we do."

lol. Yes, that's who we are! Good idea...

videolar on November 12, 2009 8:17 AM

I've learned over the years to to ignore whitespace, and most other formatting issues foudn in OPC. I'm going to apply that same discipline to ignoring all the incorrect arguments attempting to justify it. Also surprisingly difficult to do.

Kevin Thex on November 12, 2009 8:17 AM

Good information...

sex hikayeleri on November 12, 2009 8:18 AM

The real problem here is the use of space characters and not proper tabs. Have you ever gazed upon the horror of source code maintained by two people that both use soft tabs, but have them configured for different widths? Hard tabs, people. Separate the data from the presentation.

db2 on November 12, 2009 8:30 AM

In 1924, George Mallory, when he was asked why he wanted to climb Mount Everest, said "Because it's there." I suppose most still did not understand why. Similarly, if you didn't understand the pain of this article, you probably never will. :-)

Carleton on November 12, 2009 11:16 AM

Yes you are once we spent hours after site was suddenly crashed just to find out that we had mistakenly put 2 white spaces after PHP closing tag...
But after all we all love web designing and will go on coding...

www.simplify.co.in

Simplify Solutions on November 12, 2009 11:20 AM

This is the spergin'ist topic I have ever seen on this site, and thats saying a lot.

ADINSX on November 12, 2009 1:55 PM

Whitespace schmitespace! I went like "OH MY FREAKIN GOD" ( y Jesucristo, Madre Maria y Todos Santos) when I saw pre-dot-net style old asp with the VB code and the markup together and no separate code-behind file. Eeew! How "Artist-Formerly-Known-As-Prince", as in "Tonight we're gonna web-code like it's 1999!"

So, um, Jeff, are you like trying out for US Shark Jumping team for the 2010 Winter Olympics in Vancouver?

José on November 12, 2009 4:43 PM

Love it. I recently forced all the programmers on my team to make sure their VS options had tabs NOT SPACES due to the repeated "conflicts" when updating source control. What? the whole file is in conflict?! WTF!?

misteraidan on November 12, 2009 6:46 PM

afw wfwqf wqf
fwqf
wqf
fwq

admin on November 12, 2009 7:12 PM

wfwf
wf
fwq

fw
wqfw
f

fw

admin on November 12, 2009 7:13 PM

Thanks

sanalcasus on November 12, 2009 7:15 PM

Just be glad your boss doesn't inist on using tabs instead of spaces! *le sigh*

On a side note, you'd think that being an OCD freak you'd have spotted the following:

"Also, how exactly is that day is different from any other? But seriously."

is=any?

Jon Cage on November 13, 2009 12:24 AM

gwwegweg weg weg wge gwe gwe wge ge

sanalcasus on November 13, 2009 12:59 AM

gbfd jkhgıugib ihboıih

sanalcasus on November 13, 2009 1:00 AM

ewwegtwehren 4t443h43

sanalcasus on November 13, 2009 1:01 AM

@misteraidan

"I recently forced all the programmers on my team to make sure their VS options had tabs NOT SPACES..."

This is evil. Could you say what team you run so I can avoid it.

Anon on November 13, 2009 1:25 AM

As long as the white space isn't case sensitive I will get some sleep at night

Rene on November 13, 2009 2:30 AM

Beware not to remove intentional trailing whitespace characters in verbatim string literals (i.e. @"text").

Example:

More on C#'s verbatim string literal syntax:
http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx

buddydvd on November 13, 2009 3:02 AM

What's with wall the freaks using spaces instead of tabs? It's sick I tell you, sick!

Nobody on November 13, 2009 5:00 AM

I don't see what all the fuss is about.

Voice of reason on November 13, 2009 5:05 AM

For once I concur with Jeff: http://dabr.co.uk/status/5387659406

Eddy Young on November 13, 2009 5:56 AM

Why are OCD types using spaces over tabs for indentation? Using spaces is a dirty hack.

Anonymous on November 13, 2009 6:14 AM

this blog sucks ass

whocares on November 13, 2009 8:58 AM

"Hard tabs, people. Separate the data from the presentation."

Tabs are all about presentation (in languages that ignore whitespace).

Thus, you violate your own maxim by using tabs (or even newlines, in most cases).

Anonymous on November 13, 2009 11:45 AM

Solution: auto-convert the code to a very strict canonical format before commit. There should be one and only one way to represent the same functional code structure.

adi on November 13, 2009 1:44 PM

This is my take on the maddening side of the smallest mistake in my code:

http://blog.openmountain.com/2009/11/09/the-funny-side-of-web-development-and-multiple-languages/

IN this post I compare Web coding to a Robin Williams routine on golf. Fixing a mistake in some minor part of code is like trying to hit a tiny ball 350 yards into a small hole.

Cheers!

Bob Benedict on November 13, 2009 3:30 PM

In our java builds, we have checkstyle (a style checker, duh) built into our build process to enforce our style standard, and it has rules to check for trailing whitespace. If you don't fix before checking in.... BOOM broken build :D

Justin Standard on November 13, 2009 5:11 PM

perhaps i've been out of the game too long, what exactly is wrong with this code?

i see the extra whitespace on the foreach line, but does this actually break functionality or make the html render incorrectly?

former web developer on November 13, 2009 6:26 PM

Here is why tabs are better than spaces for indenting code. Let's assume that tabs are set to 4 spaces. When indenting code, it is unlikely that one would want to insert code or select text starting in the middle of a tab. The programmer will most likely want to select at the beginning of a tab or at the end of a tab. When spaces are used, the programmer will have to click in an area that is half the width of a character to insert the cursor before an indent or after an indent. Using tabs, the programmer has 2 character widths where they can click to insert the character. That's 4 times as much space. Also, fewer keystrokes are required to navigate tabs than spaces (though, some editors can make the spaces act like tabs in this regard).

The only reason I can think of to not use tabs (aside from being anal-retentive) is because different text editors can have different tabs set. However, if you're consistent with the use of tabs, this should make no difference. If programmer A likes 4 spaces and programmer B likes 2 spaces, they can both do their work the way they want without affecting the other. The problem occurs when one programmer decides to use spaces when the rest of the code is in tabs. This is more of a personnel issue, I think. If the developers can't agree on a standard then they have bigger problems.

Dave on November 13, 2009 8:30 PM

I think some of you guys are missing the point. It's how something as innocuous are whitespaces can be such a big headache. Sheesh

Visual C# Kicks on November 14, 2009 6:27 PM

as*

Visual C# Kicks on November 14, 2009 6:28 PM

This is mainly a problem in template languages as per the example. A particular example in PHP is where files end in "?>" followed by whitespace. Perhaps tolerable if you're just printing HTML, but if you're trying to print an image or other binary, for example, the whole world explodes. And, worse yet, you might not notice until you get phone calls exclaiming "Our PDFs are broken!".

Perhaps avoided by rigorous testing, but, really, who has time for that?

Schalken on November 15, 2009 2:38 AM

One reason to use library construct like "String.EMPTY" is that it is statical analysis friendly, and can be easily searched for.

Chuan Li on November 15, 2009 6:46 AM

How far we have sunk in our professional thinking to post this many comments about white space.

Steve on November 15, 2009 10:04 AM

The extra spaces in sourcecode is how the csharpians communicate with me!

Mostly to tell which process NEEEDS TO DIE next.

tINfOILhAT on November 15, 2009 9:32 PM

I hate unnecessary whitespace at the end of lines too!

It seems completely irrational take make it such a big concern, but who really cares about rationality!? We know it rashes us, and we know the their nagging existance will not be silenced until they are removed.

Good to hear other people have the same level of OCD I do.

Daniel Carvalho on November 16, 2009 2:11 AM

Wow, I thought I was the only web developer in the ASP.NET world who cared about good client-side code!

It's too bad Microsoft is so clueless. VS2008's default setting inserts four spaces when the tab key is pressed, there's still no minimal CSS auto-formatting option, and .NET's auto-generated JavaScript is still a hideous mess written by people who think whitespace-laden C# syntax is acceptable for JavaScript. Apparently MVC in VS2010 has some minifying functionality, but I haven't seen it yet.

If you don't understand why lean client-side code matters, just wait until next year, when Google starts using file size/download time as part of their search result ranking criteria. When you see all your sites drop a notch, don't come crying to all the real web developers - we'll just say "I told you so, web n00b!"

Droog on November 16, 2009 8:37 AM

Actually, this is trolling in a way, but it is necessary.

CH comments are sooo many that I just don't ever seem to be able to read them all. It's too much. So I end up violating the first-do-a-search rule at the page level.

So, as many may have requested before, I shall repeat:
Please allow some markup in comments and let us hope that commenters who want to say something useful take the additional trouble to use *bold*, /italic/ or _underline_

Over a period of time, and over a variety of topics, i estimate that casual comments coming from lazy commenters will have less or no markup (i hope, let's all discuss this) and so it will be easy to filter comments.

Want some marketing? Here:

*****
Responsible Markup Initiative @ CH blog
*****

Again, the complaint is that there are too many comments to read and many comments without lot of useful content.

Assumption:
------------
Trolls when left hungry for some time, will die of hunger.

otherkiller on November 16, 2009 10:48 AM

Eclipse Ganymede handle very well those issues, it can be configured to remove end line white spaces and bottom of file empty lines.
Also it as a pretty nice eature for auto indenting code.

I use both functionnality on php/PDT projects and they are just fine for me :)

For sure I use other editors for python, one showing me every tab, I tend to do the same for YAML files.

Benoit on November 17, 2009 1:24 AM

I know the answer, I'm hired? :)

Ion Todirel on November 17, 2009 4:26 PM

(add-hook 'before-save-hook 'delete-trailing-whitespace)

Marius Andersen on November 17, 2009 6:05 PM

I think the user of PHP is more popular with the days elapse.

Laptop-battery on November 18, 2009 2:09 AM

I think it's a great idea to really get and fight whitespaces. Here is my solution as an Xcode user script:

http://on-pro.tumblr.com/post/244987553/whitespaces

Thanks Jeff!

nikan on November 18, 2009 4:35 AM

yea white spaces are definitely gay for programmers. i know because i iz one. a suggestion is to have a script built into your checkin routine that forces all code to limit spaces between words to 1. if ur gay and dont know how to do this or leik your language doesnt support regex then there is an easy way to. create a recursive function that does a search and replace - replacing double spaces "__" with single spaces "_". o yea and it helps to be a little drunk when writing recursive code.

madmax on November 18, 2009 8:17 AM

What I hate is copying and pasting code and there is a ` instead of a ' somewhere!!! one time it took me a freaking hour to find what was the problem with the quotation!!!

momo on November 18, 2009 9:52 AM

What I hate is copying and pasting code and there is a ` instead of a ' somewhere!!! one time it took me a freaking hour to find what was the problem with the quotation!!!

dedektif on November 18, 2009 5:18 PM

What I hate is copying and pasting code and there is a ` instead of a ' somewhere!!! one time it took me a freaking hour to find what was the problem with the quotation!!!

dedektif on November 18, 2009 5:22 PM

I hate unnecessary whitespace at the end of lines too!

It seems completely irrational take make it such a big concern, but who really cares about rationality!? We know it rashes us, and we know the their nagging existance will not be silenced until they are removed

007 casus on November 19, 2009 6:04 AM

I'm glad I don't program in whatever god-forsaken language this is. Because whitespace that screws up the program is just moronic.

Scott M on November 19, 2009 1:46 PM

@Dave: "I pad all my code to the 80th column with spaces. Cheaper than medication."

72 columns is enough - you have to leave room for the girl to add the line numbers so you can merge the decks.

DavidR on November 20, 2009 8:14 AM

Uncredible, I have read the post about the bad codes of flickr, yahou., reddit etc. And now that one. You whould work for me :-)

Stefan on November 20, 2009 8:29 AM

Myabe its just the example you gave, but its no big deal really, get a life.

Michael on November 24, 2009 3:43 AM

If it's my file, I press Ctrl+K+D sometimes, and that usually gets rid of them + the other formatting annoyances. If I modify somebody other's file, I can mess up the svn patch by doing that, so sometimes when I notice the whitespaces in the patch file, I go back to the file and delete them. Anyway it's annoying.

csuporj on November 25, 2009 4:54 PM

> At least in corporate "enterprise application" code,
> the problem with trailing whitespace is that it often
> indicates cruddy, cut-n-paste coding by cut-rate,
> one-size-fits-all, lowest-bid consultants.

This whole discussion is ridiculous enough, when it's a tool problem that can be solved with proper editors. But, then, blaming consultants? I know of many lamo-waiting-for-retirement-even-tho-they-are-only-in-their-30s-programmers that write the worst code on the planet.

Let's be nice. Let's get good tools.

bak on November 27, 2009 11:05 AM

My old programming teacher always wrote the most incomplete and syntax violating examples in class - his excuse? "I let the parser find my typing errors"

Sam Johnson on November 30, 2009 3:45 PM

I have a full-body itchiness just talking about it.
write well,thanks for post.
so maybe the world won't explode if there are a few extra bits of whitespace in my code.

valves manufacturer on November 30, 2009 6:50 PM

very good blog, I come here every day,thanks very much for post.

sanitary fittings on November 30, 2009 6:52 PM

Ask very well,No surprise there. But did you know that even the code you can't see may be wrong, too?

ball valves on November 30, 2009 6:54 PM

what it's like to spend every freaking minute of every freaking day agonizing over the tiniest details of the programs you write0

butterfly valves on November 30, 2009 6:57 PM

Seriously - 8000 comments and only one person mentioned that this was a) horrible markup and b)just plain old bad code. Never ever mix markup and c# code. That should be an asp repeater bound to a data source. Who cares about the whitespace...

Derek on December 1, 2009 10:20 AM

Here's how I keep my whitespace under control in emacs:

(setq-default indent-tabs-mode nil
require-final-newline t)
(setq whitespace-check-indent-whitespace nil)

(require 'whitespace)
(global-whitespace-mode t)
(add-hook 'before-save-hook
'whitespace-cleanup)

Jack on December 2, 2009 4:12 PM

I m sure sure I use other editors for python, one showing me every tab, I tend to do the same for YAML files.

sinyal kesici on December 3, 2009 1:42 AM

thanks admin
information is the most beautiful treasures

sex video on December 3, 2009 1:42 AM

I use Visual Studio 2005 and every now and then I use this procedure to bulk-remove trailing white space from the code:

* Press "CTRL + SHIFT + H" to open "Replace in Files" dialog
* Find what = ":b+$" (colon, small b, plus, dollar)
* Replace with = "" (empty string)
* Use = "Regular expressions"
* Look in = ""
* Look at these file types = "*.asp;*.css;*.js"

Works nicely. But until you get used to this procedure, remember to backup your files.

Salman on December 4, 2009 10:22 PM

Myabe its just the example you gave, but its no big deal really, get a life.
I agree

toshiba laptop batteries on December 7, 2009 4:12 AM

very great blog, I come here every day,thanks very much for post.

laptop batteries on December 7, 2009 4:16 AM

thanks admin
Are you really cool

tarsus on December 7, 2009 11:51 AM






(no HTML)


Verification (needed to reduce spam):


Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.