tags:

views:

974

answers:

21

When I write code, I try to group lines of similar code together, then leave a blank line and write another block.

I believe this contributes to the neatness and readability of the code.

I'm not a big fan of bunching stuff together without any line spacing. It looks like hell, it's hard to read and it's difficult to follow.

One of the teachers I had, downgraded one of my assignments because I had spaced my code logically. He said, 'When you have to read code all day in the real world, you won't put this line spacing in and you'll be thanking me." Of course, I never did and never will thank him.

Now that I'm in the real world, most of the code files I see that have absolutely no line spacing are poorly written and poorly thought out.

This is probably more prevelant in VB type languages than in C type languages, but the same concept applies.

Two questions come to mind:

  • Where do you leave a blank line in your code?
  • How much line spacing is too much?
+1  A: 

In my opinion, adding a blank space to your code is a hint that you should split your function into smaller parts. Cleaning up your code by adding spaces is preferable to a mile long list of unseparated lines. Cleaning up your code by separating out smaller functions is better.

Magnar
Hrm... So adding a blank line before and after declaring the variables at the start of a function indicates that they should be in a new function? I don't think so.
I disagree with this. If a function/method gets too long *including* blank lines, that's a smell. Omiting blank lines to cram more into vertical space is also a smell.
slim
Single purpose is a better guide than blank lines but they are a damn good hint when you've added one to logically separate functionality. :)
Lazarus
Putting this back to 0, although I don't entirely agree with the comment, I think there's at least some sense of truth and don't think it deserves -1.
Daniel
@treant: If you declare so many variables at the start of your function that you feel the need to separate them out, that's another hint that your functions are too large.
Magnar
@Magnar again I disagree. I would have a blank line below a single variable declaration.
slim
Good answer. I give you +1
Nicolai
+0: you're advice is acceptable, but as a general rule there are just too many exceptions. Two or more sequential control-flow statements in the same method does not necessary violate the "single method, single purpose" principle, and it improves readability to have visual separation between them.
Juliet
+16  A: 
George Stocker
Also, if you go with what you see, you will need to use their wack HTML indentation rules...
leppie
Any spec that defines where you can and can't put spaces is a big negative for me (except for marking up API documentation where consistency is key). Spaces, or lack of, don't increase or decrease the understandability of the code. Guidelines should be about understandability of code.
Skizz
@Skizz, FAIL! Sure it does decrease usabillity if you have less readabillity.
Filip Ekberg
I dooon't think Ctrl+K+D adds spacing between logical blocks of code within a method, which imo is what the question is about.
Peter Lillevold
@Peter Lillevold: The author isn't clear. So I have to interpret. My answer is that the IDE tells us where we ought to place blank lines, and where it says not to, we shouldn't.
George Stocker
@Gortok: can you code without the IDE? You seem to rely on it a lot.
leppie
@Gortok: your interpretation is ok. My point was that in addition to the CtrlKD formatting (which I use all the time), grouping lines of code with single line spaces in method bodies are a great way to increase readability. If CtrlKD could to that I would classify it as A.I. :)
Peter Lillevold
leppie: If you are given a tool to make your life easier, do you always decide upon the course of self-flagellation instead?
TheTXI
@leppie : It'd be brutal to code in C# without it. If I'm writing Perl, I have no need to use an IDE. If I'm writing HTML, I have no reason to use an IDE, if I am using PHP, I have no reason to use an IDE. I could keep going, but the answer is: Use an IDE where the language essentially dictates it.
George Stocker
@leppie: I know I write all my code in notepad, because am uber1337 like you!
Geoffrey Chetwood
@leppie: Is there a point to coding without an IDE? Like maybe if you were on a mission deep in siberia and had to code up some ASP.NET really quick because charlie was on your tail and you used your last IDE to blow up the mission objective, I guess you could do it in VIM.
belgariontheking
@Peter Lillevold : The only time I don't like Ctrl+K+D is using it where other programmers haven't, and if you look at a Diff in Clearcase, it'll appear like the entire page of code has been changed, when in reality, it was just formatted.
George Stocker
I'm starting to believe every SO answer evolves until it includes an xkcd comic in it. ;-)
John MacIntyre
@Jon MacIntyre: we're talking about this on IRC, and I've decided to now include an XKCD comic into every edit I can conceivably make on a question or an answer (of mine or someone elses).
George Stocker
Rats! I thought I would be the first one to come up with this ... thought they'd call it 'John's Law' ... now that would be cool. ;-)
John MacIntyre
Indeed. I've been trying to get one.
George Stocker
I'm still waiting for my own law concerning the number of pony references in a thread inevitably approaching infinity.
TheTXI
+10  A: 

I think I do something similar, but there are no hard rules. I like code to spaced in 'paragraphs' of grouped/related logic.

Code with no extra line spaces is terrible to read.

leppie
+3  A: 

Vertical space is usually at a premium relative to horizontal space, so excessive spacing usually isn't a good idea. I do think it's a good idea to logically separate blocks of code with a single blank line.

Sounds like your teacher is mostly a jerk. As the saying goes, "those who can, do; those who can't are on StackOverflow teach." ;)

John Feminella
I think you hit the spot there: a single blank line, no more.
leppie
+2  A: 

We have a coding standart that states that we should not put more than one blank line in a row. All the other is up to developer. In practice we do as you say - try to group logically connected lines into groups and isolate them with blank lines.

sharptooth
+6  A: 

Since we don't have an example of your personal idea of "logical" line spacing, we can't really say whether or not you deserved to be downgraded.

I tend to group similar statements or steps in a sequence together before spacing (such as variable declarations, looping, etc.)

TheTXI
A: 

I've started following the Microsoft Design Guidelines found here:

Design Guidelines for Class Library Developers

Lazarus
+3  A: 

I use line spacing very similar to you. The code I've found in the real world often tend to be laid out similarly, or at least not so bunched together that it can't be read.

Andy
+2  A: 

Use little methods, in order to have a low cyclomatic complexity. High cyclomatic complexity in methods generally means that your method must be divided into several others sub methods, which will be more easier to read, and more easier to test!

I think that your code is facing this kind of problem.

Generally, a method with 100+ lines is too big and too complex, and then must be refactored.

To summarize, instead of breaking code with line spaces, break it into separate methods...

romaintaz
Cyclomatic complexity doesn't take into account the big dumb case-type statements that are sometimes useful. They have high C.C., but are easy to understand.
David Thornley
+7  A: 

My rule of thumb is:

Put a single blank line between blocks of code that can be described with one comment.

But generally I agree that many large functions with lots of white space should be broken into smaller functions.

Joel Potter
+8  A: 

It sounds like I space lines of code similar to you.

But this is an irrelevant, personal preference and everybody is going to have thier own 'right way' to do it. The most important thing, IMHO, is to adapt the style of the environment you are going into.

Also, you will find code like this in the 'real world' ... but it sounds like you have higher aspirations. ;-)

EDIT: ... not higher aspirations than the 'real world', but higher than the mediocre crap common in the 'real world'. ... if you do happen to have higher aspirations than the 'real world' however, you might want to see a professional. ;-)

John MacIntyre
Great answer, btw.
George Stocker
+5  A: 

Basically the same thing as everyone else is saying. COBOL had very distinct rules about what a sentence and a paragraph was. I guess, in the back of my mind, I follow those. If you have a large IF statement, you didn't put a period until the very end of the nest. Similarly, I put a blank line after my last } // end if

And yes, I put the // end if, // end for, // end method stuff in there. Some of the more vocal people I know don't like it, but I like it. They say you shouldn't make your if-statements huge and that you're probably coding wrong if you NEED the // end if stuff, and I don't NEED it, but I do find it makes it easier to read. Call me old fashioned, OCD, whatever.

belgariontheking
+3  A: 

Unless you go nuts with the vertical spacing, I see no problem with separating out your code. I know people like to toss around the idea of using little methods, but something even if your method does one single thing, that single thing could take a lot of code to accomplish. Not everything can be done in a screenful of code.

Tundey
+3  A: 

Your teacher was probably half right in that in the real World you won't have the line spacing. Certainly on the Big Ball of Mud code bases I come across you're lucky if you get a line space let alone comment of explanation.

As an aside the 73 year old programmer that wrote most of this Big Ball of Mud is still working there and his explanation is that the binaries need to be kept as small as possible, I didn't bother to check whether the compilers of 20 to 30 years ago were that inefficient they couldn't strip whitespace but I'm somewhat skeptical.

I use single blank lines to break up logical sections in my own code as I find it greatly enhance readability.

As always the best test with these type of readability concerns is to grab some tricky piece of code you wrote and haven't looked at for over a year and see if you can get a grasp on it quickly. If you can then your code will be better than most of what you'll see in the real World!

sipwiz
Sounds like that 73-year-old a) doesn't know how compilers work, and b) does not heed the "premature optimization is the root of all evil" principle.
Juliet
Back when I wrote BASIC on my TRS-80, the interpreter did essentially no preprocessing, so whitespace was a performance hit. Literally every system I've used since has had some sort of preprocessing, so whitespace does not slow execution down or increase executable size.
David Thornley
+2  A: 

Spaces help to make your code more readable and I think the consensus here is that they are not for the most part a bad idea. But nobody seems to have pointed out that along with the blank line a comment may not be amiss.

/* This section preps the widgets for display */
block 
of some 
code

/* This section passes the widgets to the display handler */
and 
so 
on

Remember most code will be read many times over it’s life so anything you can do to make life easier for future maintainers is a great plus.

Jeremy French
+2  A: 

1) I agree with you about line spacing

2) In my office there's a lot of lack of line spacing because "you get to see more of the code on one page that way." They also put multiple statements on one line, and over (IMHO) use ?:... I hate it.

3) I do disagree with the phrase "That's why he is a teacher". as an (ex) teacher, I have to say that I would downgrade people for NOT putting space between sections before I took off points for putting space. I don't think I did either. My point is that him being an ass is orthogonal to his being a teacher. (EDIT: that section got edited from the original, but I'm leaving it here to maintain the rule of 3...)

Don't malign teachers!

Brian Postow
+3  A: 

I consider code as an article. Have you ever tried to read 2 pages of article which has no paragraph or line spacing in it?

I agree with you, not having line spaces between logical groups is just insane.

dr. evil
+1  A: 

One of the teachers I had, downgraded one of my assignments because I had spaced my code logically. He said, 'When you have to read code all day in the real world, you won't have this line spacing and you'll be thanking me."

Unless you're seperating blocks with 5 or 10 lines of whitespace (which would drive anyone nuts), you're instructor is just being an ass.

Coding standards are not etched in stone, and they are certainly not the same for all software shops. All companies have different coding standards. For what its worth, some of the coding standards at my company state explicitly "visually seperate logically related blocks of code using a single blank line".

Although we should strive not to write 200-line long methods, its still very common for all of our short methods to contain more than one control flow element, and we should understand that vertical whitespace is just as important as horizontal whitespace in readability. You can satisfy the "single method, single purpose" principle even if you put a blank line between a for-loop and an if-statement in the same method.


[Edit to add] And just a few more comments:

1) Its very presumptuous that several people in this thread are assuming that the OP is writing 200-line methods, or that there is a necessary correlation between adding blank lines and writing sloppy methods.

2) For what its worth, while the OP's instructor is utterly wrong in assuming that his coding standards are the the same everywhere. However, you should treat the programming course as its own little software shop with its own standards, so your code should be written in a way which follows those standards.

If your instructor is grading you based on how well your code conforms to coding standards, then insist on getting a list of standards. I know if my grade was docked because it didn't conform to standards that the instructor had never given to me (or if his standards say "prefix variables with their datatype"), heads would be rolling.

Juliet
+1  A: 

I've just been working on some code that goes in the opposite direction; each statement is separated from the next by a blank line. The authors also liked to use four lines of comment right aligned at column 60 instead of a one-line comment indented at code level. It is hard to read, and tedious to fix. Another feature of the code (C code), the break from a previous case is 'attached' to the case of the next, but there's a blank line after the case, separating it from its code. Ick!

Blank lines around blocks of code are good. Not having too many blocks of code in a single function is good. Blank lines around every line of code is unpleasant. Too much, or too little, of a good thing is a bad thing.

Jonathan Leffler
My thoughts exactly. We have code written by a (former) programmer that fits your description to the letter, and the "blank line between every line of code" is indeed annoying and doesn't help anyone.
Mike Spross
A: 

I'm not going to begin to suggest any specifics. There are plenty of good suggestions here and elsewhere on the interweb.

But I would say be consistent. At least within an application or module - since I know I refine my approach from time to time, but I try to keep all code in the same places looking the same.

If you are consistent, it's easy enough for any other developer to pick your tempo and style.

CJM
A: 

Not to sound pretentious, but I think of blank lines in code as having a similar function to phrase marks in music notation, or line breaks in poetry: they communicate intent to the reader without changing the semantics of the content.

Here's a method I just copied and pasted from a project:

public static void Startup(bool startupUser)
{
    URI = "";
    AutoComplete = new AutoCompleteWrapper();
    SessionToken = Guid.Empty;
    ExternalDataSetLock = new object();

    ConfigDS.Init();
    CalendarDS.Init();
    CalendarDSBuilder.Init();

    if (startupUser && UserName != null)
    {
        string autoCompleteFilename = Path.Combine(UserFolder, "autocomplete.xml");
        AutoComplete.Load(autoCompleteFilename);
    }
}

What do the blank lines do here? They clarify that there are basically three different kinds of initialization taking place in this method. If I add a new property that needs to be initialized on startup, I know where I'm going to put the line that initializes it. The blank lines also hint at how I intend to refactor this function if it doubles in size.

The risk of using blank lines is the same as the danger of any other kind of implied meaning: it's implied. The implication you're making when you write the code may not be the implication that the person reading the code understands.

But mercy, that's no reason not to use them.

Robert Rossney