user72491
user72491

Reputation: 3675

What is the proper way to format code?

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:

Upvotes: 19

Views: 12005

Answers (22)

spinn
spinn

Reputation: 324

I know this is an old question, but I tripped over it doing a search for something else, and had an observation: look at the existing answers. They're generally short, yet they contain blank lines.

That's what paragraphs are. As in writing, lines are a quick, visual way to separate concepts. It doesn't mean each paragraph above should be broken into a separate answer; it doesn't mean each code "paragraph" should be broken into a separate method.

It's a silly complaint. If it were still possible to talk to that professor, I'd explain what "wall of text" means.

Upvotes: 2

Robert Rossney
Robert Rossney

Reputation: 96702

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.

Upvotes: 2

CJM
CJM

Reputation: 12016

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.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

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.

Upvotes: 3

Brian Postow
Brian Postow

Reputation: 12167

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!

Upvotes: 2

Juliet
Juliet

Reputation: 81516

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.

Upvotes: 3

dr. evil
dr. evil

Reputation: 27265

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.

Upvotes: 3

George Stocker
George Stocker

Reputation: 57872

I follow Microsoft's Guidelines for C#.

Edit: The standard for C# is Don't fight the IDE. If you hit CTRL K+D, the IDE will automatically put blank lines in between code sections.

To follow that up, if you look at C# sample code on MSDN or anywhere else, there's normally a blank line in between each logically placed group. So There will be a blank line after all your member variables, a blank line after each method, etc.

In response to the comments expressing shock and horror that I use an IDE for C# programming:


REAL PROGRAMMERS

Upvotes: 19

TheTXI
TheTXI

Reputation: 37875

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

Upvotes: 6

Magnar
Magnar

Reputation: 28810

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.

Upvotes: 1

Jeremy French
Jeremy French

Reputation: 12157

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.

Upvotes: 2

sipsorcery
sipsorcery

Reputation: 30699

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!

Upvotes: 3

Tundey
Tundey

Reputation: 2965

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.

Upvotes: 3

belgariontheking
belgariontheking

Reputation: 1349

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.

Upvotes: 4

John MacIntyre
John MacIntyre

Reputation: 13021

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

Upvotes: 10

Joel
Joel

Reputation: 19358

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.

Upvotes: 8

Romain Linsolas
Romain Linsolas

Reputation: 81577

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

Upvotes: 2

Andy
Andy

Reputation: 3854

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.

Upvotes: 3

Lazarus
Lazarus

Reputation: 43064

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

Design Guidelines for Class Library Developers

Upvotes: 0

sharptooth
sharptooth

Reputation: 170479

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.

Upvotes: 2

John Feminella
John Feminella

Reputation: 311436

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

Upvotes: 3

leppie
leppie

Reputation: 117220

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.

Upvotes: 11

Related Questions