8

I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

12
  • 11
    a good compiler will not even care about whitespace as it will compress it into a single token during the tokenizing pass Jul 26, 2014 at 1:19
  • 5
    I would likely cause you physical harm if you commonly put 2-3 lines of whitespace in code I had to work in. Okay, perhaps I overstate things, but if your files are long enough that you need to "organize" them, you're doing too much.
    – Telastyn
    Jul 26, 2014 at 1:39
  • 9
    There is definitely some amount of whitespace at which point whitespace becomes a bad thing. (If your 100 line source file contains 10TB of whitespace, for example). The question is whether your amount of whitespace is bad...
    – user253751
    Jul 26, 2014 at 3:31
  • 5
    Too much of anything is never a good thing. That's what too much means. Jul 27, 2014 at 0:35
  • 5
    One thing to try: increase the line spacing in your editor’s display settings, so you aren’t tempted to insert so many extra line breaks.
    – Jon Purdy
    Jul 27, 2014 at 2:38

11 Answers 11

24

There's two reasons why you should strongly consider not doing this:

  1. Code is much harder to understand when you can't see all the relevant parts at once. By inserting a blank line between most lines, you're halving how much code you can see.

  2. Consistency with other people's code is important in group projects. It doesn't matter too much which particular conventions the project follows as long as it's consistent. It's hard enough to understand large systems; it's harder still when each part has different indentation schemes, naming conventions and idioms.

5
  • 2
    I agree with point 2, provided the project is using a style guide to regulate code formatting, that should be adhered to.
    – paisanco
    Jul 26, 2014 at 16:09
  • I think this is missing the point slightly. If you can't see all the code (easily) on one screen then blank lines is the least of the problems. The key answer IMO is to split code up into smaller methods. Jul 26, 2014 at 23:10
  • 2
    Agree with point 2 (+1) , Point 1 (-1) If you can't see all the code.... get a bigger screen, refactor, but do not make you code less readable for who - tablet uses, notebook users, desktops with 1920*1024, 4K screens are now cheap enough they will be common in 2 years....
    – mattnz
    Jul 27, 2014 at 7:19
  • 1
    +1 for consistency within the project. Code must be written so humans can read it. If another fellow programmer said it's hard to read the code then it's already a good reason to revise it.
    – Alex
    Jul 30, 2014 at 13:11
  • 6
    @mattnz Refactoring doesn't fix the issue. Small functions are much easier to understand, but they'll most likely call other functions. Unless you're working on some toy project, you can't hold the whole system in your head, so you may need to look at multiple definitions at once. You might want to look at constants that aren't defined close to the function you're looking at as well. No matter how you look at it, excessive whitespace cuts into how much code you can look at simultaneously.
    – Doval
    Jul 30, 2014 at 13:51
14

Whitespace is indeed useful it helps break up sections of text to make various parts more distinct and stand out "this is a block. Look at it in that context."

Horizontal whitespace is used for indentation and scope to also give hints. One of the dangers of putting too much vertical whitespace in is that the eye looses the ability to track the indentation. In languages without {}, this can be disastrous for the context of the code.

That context is very important. If something isn't on the screen, you can't quickly scan back to it - you have to scroll to it. This can mean either losing the code you were just looking at and having to move the hand to the mouse. These things take time and some expenditure of mental energy. While it can be a small amount of mental energy, it is still some unnecessary expenditure.

Lets actually look at this and get some code. This is from _header_value_parser.py

as writtenadditional whitespace

The text doesn't matter too much, but note that thats quite a bit less on the screen. One can't even get the full method in the page. And there is questions about where some of the blocks line up - the eye doesn't travel that well keeping things in line to far (it becomes more obvious in the full size image - does line 176 line up with the scope of 135 or 133?).

Its not about how many lines you are checking in (any one counting code checkin metrics is using source lines of code instead which discounts white space and may also discount comment lines). Its about keeping things in easy swap distance of the eye and the mind.

3
  • 9
    I'm not sure the illustration you gave is relevant: the current method should have been split into at least five methods a long time ago. Jul 26, 2014 at 21:23
  • @MainMa it could be. What it is meant to show is how various spots where there are 4 or 5 lines separating blocks can make it difficult to keep the context of the entire block, along with difficulty with eye tracking to follow the scope of a given block.
    – user40980
    Jul 26, 2014 at 22:09
  • 3
    I would argue the middle ground is best. Keep lines together that are tightly coupled, with one space between groups of lines. It helps convey the intent that certain lines go together, and makes it easier to scan the code, sort of like if you look away from a page in a novel and look back, you can quickly figure out where you were by the paragraph indentation. Our eyes need whitespace. At that point though, there is a strong argument for @MainMa's comment that it should be multiple functions anyway.
    – user22815
    Jul 30, 2014 at 17:25
12

Is too much whitespace a bad thing?

Clearly:Yes. If you say, it is too much, then it is a sign, for something smelly going on.

I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Your problem is not whitespace, your problem is clean code or better: a lack of clean code.

One lesson clean code teaches us is: breaking down large code blocks into smaller ones. I bet, every block you wrap in whitespache is a block, which could be chopped up into small handy pieces.

Try it with paranoia: Every function greater than 10 lines has to be broken up into smaller chunks. And in case you are writing OO: every class longer than 200 lines is too large.

Of course 10/200 lines is an arbitrary number, but if you follow this rule for a while, you will notice the effects: a) you won't have whitespace blocks anymore b) your code gets more compact, readable and better to understand, and in the end: maintainable.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

Why worring about filesize? We do not live in the 80ies and store everything on tape. We are in the age of Big Data. That is the wrong concern. And if you break up your blocks into readable chunks, the number of files and the size will increase. But don't worry.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

That is also a wrong concern. If you are measured by the LoC or the bytesize of your output, quit your job. Code should be measured in quality not quantity.

3
  • 1
    Measuring LoC if you don't exclude whitespace and normalize multi-line expressions is not even measuring what LoC is supposed to actually measure -- "how much code is there."
    – DougM
    Jul 26, 2014 at 15:16
  • File size can still be an issue if it's something that's expected to be transmitted over the internet (e.g. Javascript). Despite popular belief a lot of places still have mediocre internet speeds, even in certain countries considered well-developed. If it's a client-side program intended to be downloaded once per install/version in compressed form then yes it's less of a concern.
    – Pharap
    Nov 29, 2017 at 21:55
  • @Pharap usually you uglify and / or gzip content, so I doubt this is a real concern. Nov 30, 2017 at 9:00
9

I recommend the Google Style Guides for the programming language you are using. I abide to these rules and they usually lead to clean-looking code. There are somethings I add myself (like 2 blank lines between functions) but overall I really like the Google Style Guides.

Update:

The different style guides vary a bit per language, as these are put together by different engineers who devote all their time working in that language, so what they have written down is what they believe leads to clean-looking code. It seems that overall, the rule of thumb is to only use blank lines to distinguish code groups. Multiple consecutive blank lines are hardly ever encouraged. Here's some excerpts from these guides:

Java

A single blank line appears:

  1. Between consecutive members (or initializers) of a class: fields, constructors, methods, nested classes, static initializers, instance initializers.
    • Exception: A blank line between two consecutive fields (having no other code between them) is optional. Such blank lines are used as needed to create logical groupings of fields.
  2. Within method bodies, as needed to create logical groupings of statements.
  3. Optionally before the first member or after the last member of the class (neither encouraged nor discouraged).
  4. As required by other sections of this document (such as Section 3.3, Import statements).

Multiple consecutive blank lines are permitted, but never required (or encouraged).

Python

Two blank lines between top-level definitions, be they function or class definitions. One blank line between method definitions and between the class line and the first method. Use single blank lines as you judge appropriate within functions or methods.

C++

Minimize use of vertical whitespace.

This is more a principle than a rule: don't use blank lines when you don't have to. In particular, don't put more than one or two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be discriminating with your use of blank lines inside functions.

The basic principle is: The more code that fits on one screen, the easier it is to follow and understand the control flow of the program. Of course, readability can suffer from code being too dense as well as too spread out, so use your judgement. But in general, minimize use of vertical whitespace.

Some rules of thumb to help when blank lines may be useful:

  • Blank lines at the beginning or end of a function very rarely help readability.
  • Blank lines inside a chain of if-else blocks may well help readability

Objective-C

Blank lines before and after @interface, @implementation, and @end are optional. If your @interface declares instance variables, a blank line should come after the closing brace (}).

Unless an interface or implementation is very short, such as when declaring a handful of private methods or a bridge class, adding blank lines usually helps readability.



I only put the information here regarding vertical whitespace, but some of the guides also have info on horizontal whitespace and a lot more formatting information (comments, blocks, indentation, etc...)

And the project is open source so if you have any suggestions you could email one of the project owners.

2
  • 1
    I like that you mentioned following a well-known style guide. Can you expand your answer to include relevant white space guidelines from the Google Style Guide for, say, Java? Jul 26, 2014 at 15:09
  • @AustinMullins Done :) Jul 27, 2014 at 5:18
5

It's depend of what you mean by too many space. For me it's important and primordial to use space for improve the readability of your code. Use one line free to seperate few block in function, free space between function and class it's good, and allign symbol with few language can be cool also:

sub my_function {
     my $arg = @_;

     my $a       = 42;
     my $b       = 50;
     my $sum     = $a + $b;

     my $map = {
         key         => 'value',
         second => 'second value'
     }

     if ( $sum > $ arg ) {
         return $sum
     }

     return;
}

A little example what I love, hovewer if you use too my line space is not good. For example five free line between the last return and the conditional structure, for me it's a bad idea.

1
  • Is this a realistic example though? The shorter code fragment: my $sum = 92 if ($sum > $arg) { return $sum; } achieves the same, doesn't it? Nov 6, 2023 at 14:12
2

Beside the other good answers, there are also tools issues. Good text editors will provide facilities (like highlighting) to match opening and closing brackets. But some of them, like gedit, won't do it when they are too far away. Of course it means you should also avoid long methods, but too much vertical blank can also harm.

Blank lines can be usefull to help making a program easy to read if they are used to separate logical blocks (like paragraphs in a text). If everything is separated that's like if nothing was.

0

You can have too much whitespace - usually its annoying to see a blank line between block and the ending curly brace, eg:

if (x)
{
    // do something

    // do more


}

That annoys me a lot. But then, I like multiple blank lines between functions - 1 line is enough for logical blocks within a function, so 2 makes each function stand out that little more.

Within functions, you do not want to space it out so much that it looks like the logical blocks within it are functions themselves. You're trying to break up a big block of text so its easy to read (like paragraphs in a book) without introducing extraneous white that starts to disrupt reader's ability to group these blocks together.

So: a quick standard for you: 1. indent correctly. 2. single blank line between blocks, where appropriate 3. multiple blank lines between functions. 4. nowhere else.

Stick to that and you'll have happy colleagues and tidy code.

0

It definitely depends on the various factors others have mentioned.

There are some circumstances where I want more whitespace, e.g. I may prefer

class Thing

  def method1
    stuff
  end

  def method2
    stuff
  end

end

to

class Thing
  def method1
    stuff
  end
  def method2
    stuff
  end
end

because if those methods get long, having the whtespace lines between them is helpful.

So as a general guideline for code, for % of whitespace lines, I would look for a figure of between 10% and 30%. Less than that and you have long algorithms, more than than that and you may be scrolling up and down and losing context and visual 'see together' grouping.

However, that said...

for some uses, having it 'all on one screen' is really helpful.

A good example if my .bashrc file which had got to 3 or 4 'screens worth' and was leading to more:

  • duplication for same settings
  • conflicting uses of same settings
  • forgetting what settings do

So in this case, I went to a lot of effort to 'compact' it down. In this case not just whitespace but making if then constructs fit on 1 line, e.g.

test -f ~/.bash_aliases && . $_

and was able to get it down to 27 lines which I can see all at once, even in a small terminal window, i.e.

enter image description here

Finally, the two issues you mention - file size and padding length are not factors that any programmers I know and respect would pay attention to - remember 100GB is a hundred thousand million bytes. Extra line spaces would just be considered to be your preference for line space. If the code actually worked this would usually be a relatively minor issue, though with a team, one that should be agreed on.

0

When it comes to whitespace, file size and compile performance should be of no concern, and whitespace should have no effect on compiler output.

It's all about readability, but readability of a given sample will be different for different readers.

As has been stated in other answers, too much vertical whitespace has the effect of lifting bits of code out of context, which can impair understanding when that context is necessary to proper understanding. I will generally never separate anything by more than one blank line - enough to set off a bit of code without sacrificing context. I worked with a developer who insisted upon four blank lines between functions. He found it helpful for readability, I felt was excessive, contributed nothing to readability and that it hampered navigation.

If you are working in a team, you should have a style guide and work to that (whether home-brewed or something more widely distributed); presumably it will accommodate the majority of the readers who will have to work with that code.

0

Whitespace in code can be used to create emphasis, a blank line before and after a block of code can be used to indicate that the code in the block is a little closer tied to itself than it is to the surrounding code. If you put a blank line between every line of code you have prevented yourself from using this method of emphasis, so you use multiple blank lines where you need this emphasis. You gained nothing in terms of emphasis, you just gained a lot of blank lines.

You think your code looks cleaner. The funny thing about the state of being clean is that it is actually the lack of anything that is considered dirty. Looking clean, as opposed to actually being clean, simply means that you can't see the dirt. So yes, blank lines a plethora undoubtedly does make your code look cleaner as it limits how much code is visible at the same time, and therefore also how much code uncleanliness is visible at the same time. But your code simply looking clean does nothing to help you or anyone else write or maintain it. On the contrary, being able to see the dirt is a prerequisite for being able to deal with it.

There is a somewhat similar argument to be made about the much more widespread practice of excessive use of spaces, take a piece of code like:

while ( x > y || foo != bar || ! ( a in b ) ) {

By using a style with no default spaces a few spaces could have been used to emphasise the three distinct parts of the condition:

while(x>y || foo!=bar || !(a in b)){

If you have a hard time getting used to cutting down on whitespace consider configuring your editor to use a bigger font and/or more linespacing, then at least your colleagues can read your code without hassle, and given time you may be able to gradually change your settings towards normal.

0

Adding lots of whitespace into a function may break it up into handy blocks, but it conveys no useful information.

If you feel the need to add more than one blank line between sections, you should also be adding a comment to explain what the next bit of code is going to do.

Plus, as Thomas Junk has pointed out, over-long functions would be better split into smaller, more managable ones.

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