31

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 ?

Matthieu M.
  • 15,214

29 Answers29

87

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.

Jeff Atwood
  • 6,757
  • 10
  • 46
  • 49
Josh K
  • 23,029
  • 10
  • 67
  • 100
21

Yes for clarity.

Just like I did in this answer.

13

I do but I make sure I document it by putting

(This line intentionally left blank.)

on the line

Don
  • 257
12

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.

Allon Guralnek
  • 1,085
  • 7
  • 15
6

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

Trinidad
  • 598
5

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

Nayrb
  • 2,514
  • 1
  • 19
  • 22
5

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.

Jay Bazuzi
  • 1,604
5

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
Nathan Long
  • 3,657
4

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

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.

3

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

Maniero
  • 10,816
2

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();
}
2

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

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.

Jason Baker
  • 9,653
2

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

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

philosodad
  • 1,785
1

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.

Rei Miyasaka
  • 4,551
1

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

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.

haylem
  • 29,005
0

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.

Mark
  • 336
0

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.

0

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

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

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

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

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

user7195
  • 109
0

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

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

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.

FinnNk
  • 5,809