31
votes

There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

  • in a class, I will group methods that go together, while separating them by a blank line from the next group.
  • if I need to write a comment I'll usually put a blank line before the comment
  • in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

10
  • 6
    if (i % 3 != 0) { <newline here> array[i] += 2; <newline here> }, but I see your point :) Commented Nov 6, 2010 at 19:13
  • These types of questions are not constructive. There are only so many times you can rephrase the only two available answers of "yes" and "no".
    – user8
    Commented Nov 6, 2010 at 22:47
  • 1
    A better question would have been how and why do you use blank lines? I use blank lines exactly the same way as you do, with the same motivation. Commented Nov 7, 2010 at 4:45
  • 1
    @Mark, @takeshin: sorry, forgot the "how" in the keyword. It's obvious we all use them, I was trying to see how it was used by people out there (separating classes, if/else, etc...) but it seems I got very generic answers :p Commented Nov 7, 2010 at 14:49
  • 3
    for (int i = 0; i < 10; i += 3) { <newline here> array[i] += 2; <newline here> } but I see your point :) Commented Mar 22, 2011 at 13:51

29 Answers 29

87
votes

Always

Whitespace is crucial to clean readable code. A blank line (or two) help visually separate out logical blocks of code.

For example, from Steve McConnell's Code Complete, Second Edition chapter on Layout and Style:

Subjects scored 20 to 30 percent higher on a test of comprehension when programs had a two-to-four-spaces indentation scheme than they did when programs had no indentation at all. The same study found that it was important to neither under-emphasize nor over emphasize a program’s logical structure. The lowest comprehension scores were achieved on programs that were not indented at all. The second lowest were achieved on programs that used six-space indentation. The study concluded that two-to-four-space indentation was optimal. Interestingly, many subjects in the experiment felt that the six-space indentation was easier to use than the smaller indentations, even though their scores were lower. That’s probably because six space indentation looks pleasing. But regardless of how pretty it looks, six-space indentation turns out to be less readable. This is an example of a collision be tween aesthetic appeal and readability.

6
  • 12
    I can hear someone saying "but then you should Extract Method!". A paragraph is for when there's not quite enough reason to Extract Method. Commented Nov 6, 2010 at 15:51
  • 1
    It's easy to experiment and see whether it is better to have vertical whitespace or not. Take a source file that is unknown to you, remove all the blank lines, then try to follow the logic. Even with proper indentation it will be mentally exhausting because blank lines give us a chance to see things in bite-size chunks. I'm having to maintain some code that didn't use a lot of vertical blank space or indentation, so adding it was one of my first tasks for self-preservation. Commented Nov 6, 2010 at 18:37
  • 2
    I agree 100%. Whitespace is useful when it's used to deliberately split code in logical chunks. However, whitespace for the sake of whitespace is just as bad as no whitespace. One former colleague liked to put one or more blank lines after almost every line of actual code. I spent a ridiculous amount of time "refactoring" that involved hitting Backspace a few thousand times to remove useless blank lines. Commented Nov 7, 2010 at 1:43
  • I added some data to support your position. See: meta.programmers.stackexchange.com/questions/1109/… Commented Feb 5, 2011 at 4:56
  • 2
    That data says nothing about blank lines, only about indentation..
    – Blorgbeard
    Commented Jan 26, 2012 at 14:59
21
votes

Yes for clarity.

Just like I did in this answer.

13
votes

I do but I make sure I document it by putting

(This line intentionally left blank.)

on the line

4
  • 1
    White lines with comments may take the attention from the code
    – JulioC
    Commented Nov 6, 2010 at 21:37
  • 1
    Thats a lot of comments saying "This line intentionally left blank"... Can't you assume that if a line is blank, it is intentional or else it wouldn't have passed code review? Commented Nov 6, 2010 at 22:20
  • 43
    Maybe it's just me, but I assumed that the OP is joking... Commented Nov 6, 2010 at 22:29
  • 7
    How long have you been working for IBM ?
    – Guillaume
    Commented Nov 6, 2010 at 23:57
12
votes

Yes, but I don't abuse it.

I've seen code where every line of code inside a method is separated by a blank line, and two blank lines are used where a logical separation occurs. That just makes it even less readable in my opinion. I've also seen whitespace used to make crazy alignments, such as this:

//Prot.   Return type                    Name                 Arg1        Arg2
//=====   ============================== ==================== =========== ========

private   int                            AMethodWithALongName(string s,   object o)
{
    ...
}

private   IDictionary<MyLongObject, int> SomethingCrazy      (string s)
{
    ...
}

protected void                           Foo                 (string str, object o)
{
    ...
}

The same misuse of horizontal whitespace can be applied to vertical whitespace. Like any tool, use it wisely.

7
  • 1
    Looks like something that would be used in a introductory level college course to drive how some concepts. Was this actually used in a professional environment?
    – rjzii
    Commented Nov 6, 2010 at 15:02
  • 1
    @Rob: It was used in production code of a large system, but without the comment header, and having large enough method bodies that the alignment puzzled me, since I couldn't see other method signatures in that file. When I collapsed the bodies of the methods, I was able to see the "reason" for the whitespace. Commented Nov 6, 2010 at 15:07
  • That may work in a header or interface file
    – Ming-Tang
    Commented Nov 6, 2010 at 17:46
  • So the guy that wrote that indentation scheme, when he added a new method to a class, and the method return type was longer than any of the existing return types, he would re-tabulate the whitespace indentation for all of the other methods in the class?
    – Mike Clark
    Commented Nov 6, 2010 at 23:02
  • @Mike, in high school we used a Java programming book (can't recall the title) that wisely advised never to use horizontal spacing like this, simply because it ends up wasting large amounts of time when you must do such re-tabulations. Commented Nov 7, 2010 at 1:16
6
votes

I don't always write software, but when I do, I use blank lines for clarity.

7
  • 4
    I often write hardware too, then print it. It's so much cheaper.
    – user131
    Commented Nov 6, 2010 at 18:19
  • 5
    Dos Equis joke?
    – Paperjam
    Commented Nov 6, 2010 at 18:38
  • @Tim In fact, it isn't so funny: 3D printing ;) (And… be nice, we aren't all native English speakers here :).
    – takeshin
    Commented Nov 7, 2010 at 9:30
  • 1
    @takeshin I wasn't poking fun at anyone, and I was alluding to 3D printing. While yes, the comment was meant in jest, I think you might be misinterpreting the intent :) Also, the fact that @Paperjam commented right under a joke about printing is .. well .. priceless :)
    – user131
    Commented Nov 7, 2010 at 11:24
  • Me does not write software but hardwire it.
    – mlvljr
    Commented Nov 7, 2010 at 12:42
5
votes

I get criticized a lot for writing my code this way. I don't understand why anyone would not do it this way.

Readability it so important when you come back to a project after an extended period of time and I've heard a saying "Always write code if the next guy who is reading it is a Psychopath who knows your location".

3
  • The assumption you're making is that decompressing your code helps readability, and I don't think that's always a given. Commented Nov 7, 2010 at 0:38
  • What Jason said. When I'm getting back into a codebase, I like to have as many LOCs per screen as possible so I can digest it quickly. If someone put in half a page of whitespace (or god forbid one of those terrible xml-style comments), I'd be very tempted to reformat it temporarily just to read it, then undo a few times to do the work (formatting wars don't lead to productivity, so I wouldn't outright delete comments and whitespace, but my preference is against them for the most part).
    – Inaimathi
    Commented Nov 7, 2010 at 14:58
  • A wall of Text is nearly impossible to read, let alone human psycology tends to resist it. I think taking the time to group similar statements together, grouping lines of code that manipulate the same variable is also good. I guess It's all preference, but I think anything done in this business should never be done quickly.
    – Nayrb
    Commented Nov 7, 2010 at 18:56
5
votes

I'm all for making code as clear as possible, and whitespace is often a useful tool in that endeavor. But let's not forget refactoring:

  • in a class, I will group methods that go together, while separating them by a blank line from the next group.

Since you have several related members, they are a candidate for a new class.

  • if I need to write a comment I'll usually put a blank line before the comment

Whenever code is unclear enough to want a comment, I ask if I can refactor to make the code clear enough to not need the comment.

  • in a method, I make one paragraph per step of the process

Why not make one method for each "paragraph"?

If you end up with a bunch of methods in your class, see my note above about extracting a new class.

5
votes

Yes. It makes it easier to visually scan a file. Among other things, it makes it clearer which line a comment goes with.

Some code here
// Which line does this comment go with?
More code here

// It's pretty clear which line this comment goes with
More code here

Still more code here
0
4
votes

I use blank lines sparingly and consistently, and consistently is more important than sparingly. However:

  • If every line of code is separated from the next by a blank line, there are too many blank lines.
  • If there is neither rhyme nor reason readily discernible for where blank lines are placed, then they are a distraction and there are usually too many of them.
  • If a function is so big that it needs many blank lines, it is too big.
  • If a block of code needs more than one blank line before or after it, there is something seriously astray.
  • If you have more than two blank lines between functions, you probably have too many blank lines.

Most of that is not dreadfully controversial; what follows might be. I note that K&R notation with the open braces at the end of line is depressingly often followed by a blank line. I personally dislike the braces at the end of the line and mixing that with a blank line after the brace makes a nonsense of the notation (IMNSHO). Put the open brace on the next line, on its own, and you have a mostly blank line (and, IMNSHO, more readable code). If you must use K&R brace at the end of the line, don't squander the vertical space saving with extraneous blank lines.

// I don't like this
if (something == anotherthing) {
    print ...
    update ...
}

// I much prefer this
if (something == anotherthing)
{
    print ...
    update ...
}

// I loathe this - not least for its inconsistent spacing
if (something == anotherthing) {

    print ...
    update ...
}

// I loathe this too, for its absurd waste of vertical space
if (something == anotherthing) {

    print ...
    update ...

}
3
votes

Write that which is most legible and least surprising.

function validEmail($addr) {
    $regex = "/.../";   
    return preg_match($regex, $addr);
}

This function doesn't need 12 lines of doc comments.

In fact, it doesn't need any comments.

Or blank lines.

They would detract from its essence.

1
  • 1
    A comment at the top describing what addresses are accepted would be nice. Can a regular expression really be used to validate an Email address? Commented Jan 27, 2012 at 0:04
3
votes

Inside the function? Rarely

If I have a clear different block it is refactoring to a new function. If few cases don't worth it.

For me blanks lines inside the function is one of most wrong "best practices".

2
votes

Often

Use it for logical blocks of code that are processed similarly. Once you add a comment to show that you're doing a different step - it's time to Extract Method.

Good Whitespace

{
    int x = computeX();
    x += ADJUSTMENT_FACTOR_X;

    int y = computeY();
    y += ADJUSTMENT_FACTORY_Y;

    setPosition(x, y);
}

Bad Whitespace

{
    //Open a connection
    String serverAddress = lookupAddress();
    Connection connection = openConnection(serverAddress);
    connection.login(user, password);


    //Go get stuff from the server
    item1 = connection.get(1);
    item2 = connection.get(2);

    //Close connection
    connection.close();

    //log data
    log(item1);
    log(item2);

    //Update client
    gui.updateView(item1, item2);        
}    

vs

{
    Connection connection = openConnection();
    updateData(connection);
    closeConnection(connection);
    logUpdate();
    updateGui();
}

vs

{
     updateDataFromServer();
     logUpdate();
     updateGui();
}
5
  • 4
    I'm assuming your Bad Whitespace example is a shortened version of what should be considered bad. At its current length, it seems unnecessary to split it up. Commented Nov 6, 2010 at 17:02
  • 1
    i dont see why bad is bad nor why you wrote VS
    – user2528
    Commented Nov 6, 2010 at 21:22
  • 5
    None of those comments are needed anyhow, and why in the world would one extract connection.close() to closeConnection(connection) Commented Nov 6, 2010 at 22:22
  • A code block with a comment is better than an extracted method, as long as the blocks are short and few. Extracting methods is not free; it has a code locality cost. Commented Dec 29, 2010 at 19:44
  • And you just make item1 and item2 global variables that the methods communicate through? Ick!
    – TMN
    Commented Jan 26, 2012 at 17:29
2
votes

Not only do i use whitespace, i use braces for clarity.

Braces i use to say these can potentially be functions.

code
{
    code
    code
    code
    code
}
{
    code
    code=code
    code
    code

    code()
    code()
}
2
votes

At one time, I'd sprinkle blank lines liberally throughout my code. Nowadays, I tend to be more sparing. I think that this is part of what Steve Yegge was talking about here:

Hopefully the scene I've painted so far helps you understand why sometimes you look at code and you just hate it immediately. If you're a n00b, you'll look at experienced code and say it's impenetrable, undisciplined crap written by someone who never learned the essentials of modern software engineering. If you're a veteran, you'll look at n00b code and say it's over-commented, ornamental fluff that an intern could have written in a single night of heavy drinking.

The sticking point is compression-tolerance. As you write code through your career, especially if it's code spanning very different languages and problem domains, your tolerance for code compression increases. It's no different from the progression from reading children's books with giant text to increasingly complex novels with smaller text and bigger words.

...

A programmer with a high tolerance for compression is actually hindered by a screenful of storytelling. Why? Because in order to understand a code base you need to be able to pack as much of it as possible into your head. If it's a complicated algorithm, a veteran programmer wants to see the whole thing on the screen, which means reducing the number of blank lines and inline comments – especially comments that simply reiterate what the code is doing. This is exactly the opposite of what a n00b programmer wants. n00bs want to focus on one statement or expression at a time, moving all the code around it out of view so they can concentrate, fer cryin' out loud.

I fundamentally agree with him. It's much better to compress the code so you can get as much of it as possible on one screen than to space it out too much. That's not to say that you should never use blank lines. It's just that I think unless the grouping you're trying to create doesn't increase readability immensely, it does more harm than good.

2
votes

A Professor Emeritus Gave Two Great Pieces of Advice

  1. Whitespace is Free
  2. Don't use the staples that poke back up through the front of the paper, or I'll fail you.
0
1
vote

My rules of thumb are these:

  1. If I have trouble reading the code I wrote yesterday, I probably need to extract a method or three.

  2. If my class definition is too long to read easily, I probably need to extract a module/interface/object.

  3. Method definitions: add a line

  4. Module/Class definitions: add two lines

1
vote

I like to think of whitespaces the same way as paragraphing. You group together lines that contribute to one idea.

If you're starting a new idea or a new facet of the same idea, you start a new paragraph -- like this.

In imperative code, I group together tasks that perform one cohesive task; in declarative code, I group together code that describes one cohesive statement of an idea.

You clearly have no trouble doing that in English (some people are horrible with paragraphing), so with a little practice, applying the same skill to code should be no stretch at all.

1
vote

Blank lines are a must in my opinion. I use them to separate different logical blocks of code. Makes the code readable. Readable code is good code ;)

My ideal code piece would be each logical block being separated by a blank line and a comment on top of each block that has a major logic.

Of course, if people over do it by adding multiple blank lines everywhere, I find it very irritating :(

1
vote

I only use whitespaces within a function/method to separate declarations and code.

If you feel the need to have some lines to separate sub-blocks of code implementing some logic, then they should be but in another function/private method. It's up to your compiler to not make that too big an overhead.

typically, in peusdo-code:

def function(arg1, argn, ...)
    INITIALIZERS

    CODE
    BLOCK_START
        INITIALIZERS

        CODE
    BLOCK_END
    CODE
end

If I see useless whitespace, I usually cringe.

2
  • That looks C-ish, my C++ Coding Standard recommend NOT to declare an object without initializing it, which precludes this use :/ Commented Dec 13, 2010 at 15:42
  • @Matthieu M: OK, then replace DECLARATIONS by INITIALIZERS. But I never want to see INITIALIZERS in middle of a block. If it needs to be, then that's something that requires a smaller scope, so it needs a private method/function.
    – haylem
    Commented Dec 13, 2010 at 15:46
0
votes

White space is extremely valuable.

Here's the deal... nerds that write complicated code like E=MC2 are great at showing off thier programming skills.

Now let's jump ahead six months, and it's 2:00 AM in the morning and the system that hasn't been looked at in six months has broken on the very line of E=MC2. This is nearly impossible to debug... everyone is freaking out.

Suppose the code looked more like this...

See Dick
See Jane
See Dick and Jan

If it's 2:00 AM and the code is broken. A quick glance will show you that line three should have been

See Dick and Jane

Problem solved.

Bottom Line... use whitespace.

2
  • 1
    Erm... neither of these examples really backs your point though. Personally, I think that E=MC2 is more readable than E = M C 2(the bottom line was to use whitespace, right?). Oh, and unless you're still in high school I'm sure you can come up with a better way to refer to people you disagree with than "nerds". Commented Nov 7, 2010 at 0:45
  • @Jason - Good point bad choice of words. E=MC2 is much more readable, that was not the point I was trying to get across. It's more like you were talking about on your website YAGNI and SYNDI. jasonmbaker.com/tag/programming Commented Nov 7, 2010 at 11:14
0
votes

As many others have stated, blank lines make for easier reading of code. However, there are some languages that enforce this standard. One that I can think of off the top of my head (not so much about blank lines but proper indentation) is Python.

0
votes

I agree, I use whitespace the same way. However, if I find myself using whitespace to break a method into too many parts, it's a sign I might need to refactor that code into multiple methods. Too many logical sections in a method might signal that the method will be harder to test.

0
votes

I use them to seperate code into logical units. I've seen very few code samples that did not use blank lines, of course obfuscation is excepted.

0
votes

The Psychopath answer is the best, but I would replace that with assuming that the next person is an idiot, and that they will assume that you are, and you will want to prove them wrong.

Just as important to readability is the use of comments. I open each function or subroutine with a comment block, explaining in clear text, what it is, what it does, what the arguments are, and what the expected outcomes are (including a list of error conditions). Then there is no question of what it is intended and/or designed to do. What it achieves may vary, but that is further down the track.

I think way too many coders either assume that it will be they, themselves that will be doing "repairs" on code, or simply don't care.

0
votes

Blank lines are important. However, wasting a whole blank line on the opening brace reduces the amount of code you can see in a screenful. Should be:

for (int i; i < 10; ++i)
{  if (i % 3 == 0) continue;

   array[i] += 2;
}

(Don't get me started on putting the brace '{' on the same line as the 'for'... that's meshuggah).

2
  • 2
    YES. I want to see your whole function on one screen. Don't put the opening curly brace on it's own line. That's what indentation is for.
    – KevBurnsJr
    Commented Nov 7, 2010 at 3:44
  • The whole point of a brace on its own line is to cleary define blocks of code. Adding a line of code after the brace is ruining the only reason why this religion is held! You may as well put it on the same line as the 'for'. Commented Dec 29, 2010 at 20:27
0
votes

Yes. For readability. Sometimes I even put blank lines in code that I did not write. I find it easier to understand code when they have logical grouping via blank lines - like u can "speed-read" through it.

0
votes

We should use blank lines between codeblocks as we do when we are writting a letter.

For example, between functions, or inside a function when we finish a loop...

People will thank you a clean code if they have to do maintenance on it ;)

0
votes

We use the whitespacing recommended by Microsoft StyleCop. Aside from readability and consistency I've found that (together with small class sizes) properly laid out code makes it much easier to manage merges when various people in a team happen to be working on the same areas.

I'm not sure if it's just my imagination but diffing tools seem to do a better job of recognising where equivalent code starts and finishes when merging when it's laid out neatly. Nicely laid out code is a joy to merge. Ok, that was a lie - but at least the pain is kept to manageable levels.

0
votes

Never a blank line, not in the whole file. That is not to say there are not breaks in the code:

 code;
 //
 morecode;

Blank lines are for opening sections of the code to work on, you have a couple hotkeys in your editor to take you to the prev/next blank line.

Not the answer you're looking for? Browse other questions tagged or ask your own question.