Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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 ?

share

locked by maple_shaft May 31 at 13:00

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

6  
if (i % 3 != 0) { <newline here> array[i] += 2; <newline here> }, but I see your point :) –  Merlyn Morgan-Graham Nov 6 '10 at 19:13
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. –  DominicMcDonnell Nov 7 '10 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 –  Matthieu M. Nov 7 '10 at 14:49
3  
for (int i = 0; i < 10; i += 3) { <newline here> array[i] += 2; <newline here> } but I see your point :) –  Berin Loritsch Mar 22 '11 at 13:51
show 6 more comments

29 Answers 29

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.

share
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. –  Frank Shearar Nov 6 '10 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. –  the Tin Man Nov 6 '10 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. –  Mike Spross Nov 7 '10 at 1:43
2  
That data says nothing about blank lines, only about indentation.. –  Blorgbeard Jan 26 '12 at 14:59
show 3 more comments

Yes for clarity.

Just like I did in this answer.

share
add comment

I do but I make sure I document it by putting

(This line intentionally left blank.)

on the line

share
1  
White lines with comments may take the attention from the code –  JulioC Nov 6 '10 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? –  alternative Nov 6 '10 at 22:20
43  
Maybe it's just me, but I assumed that the OP is joking... –  JSBձոգչ Nov 6 '10 at 22:29
7  
How long have you been working for IBM ? –  Guillaume Nov 6 '10 at 23:57
add comment

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.

share
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 Nov 6 '10 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. –  Allon Guralnek Nov 6 '10 at 15:07
show 5 more comments

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".

share
show 3 more comments

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

share
4  
I often write hardware too, then print it. It's so much cheaper. –  Tim Post Nov 6 '10 at 18:19
5  
Dos Equis joke? –  Paperjam Nov 6 '10 at 18:38
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 :) –  Tim Post Nov 7 '10 at 11:24
show 4 more comments

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.

share
add comment

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
share
show 1 more comment

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 ...

}
share
add comment

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.

share
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? –  kevin cline Jan 27 '12 at 0:04
add comment

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".

share
add comment

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();
}
share
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. –  Allon Guralnek Nov 6 '10 at 17:02
1  
i dont see why bad is bad nor why you wrote VS –  acidzombie24 Nov 6 '10 at 21:22
5  
None of those comments are needed anyhow, and why in the world would one extract connection.close() to closeConnection(connection) –  alternative Nov 6 '10 at 22:22
show 2 more comments

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()
}
share
add comment

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.

share
add comment

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.
share
show 1 more comment

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

share
add comment

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.

share
add comment

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 :(

share
add comment

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.

share
show 2 more comments

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.

share
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". –  Jason Baker Nov 7 '10 at 0:45
show 1 more comment

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.

share
add comment

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.

share
add comment

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.

share
add comment

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.

share
add comment

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).

share
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 Nov 7 '10 at 3:44
show 1 more comment

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.

share
add comment

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 ;)

share
add comment

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.

share
add comment

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.

share
add comment

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