views:

522

answers:

13

I'm fairly new to programming and from learning I have seen different ways of formatting code, comments, etc; and have been recommended on different techniques.

I mostly program in C#, C++, and Java so I want to know what is the the best way to layout code so that if other people where to go through it, they would be impressed by how simple and easy to understand it is.

I would like to know the same thing for commenting as well.

+26  A: 

The best rule to follow is: (and probably the only rule everyone will agree on)

Be consistent!

Pick one style and stick with it. Always put your braces in the same place. Use similar naming conventions. Don't mix tabs and spaces, etc...

That being said. It is also usually a good idea to try and follow the conventions already in place for a language.


When working on a team with people, make sure that you all agree upon a style and stick with it. If you don't, often times one developer will reformat a file with their auto-formatter, and then you can have hundreds of little conflicts that were just caused by whitespace.

jjnguy
Good answer. I tried to imply that in my comment, but I didn't think my version was good enough to be an answer.
MJB
@MJB I'm willing to bet that this is the only 'right' answer. No one will ever agree on style 100%. But people will agree that you should always be consistent.
jjnguy
Some things are reasonably objective. For example, most people agree that Java files should contain line breaks and not be an entire file on one line. And if you agree with and objectively justify that, then there are probably more things that you can justify as well, objectively. Such as indentation (using it vs not using it). But +1 since consistency is the most important factor.
Mark Peters
You should mention that you should be consistent within a source repository to get readable commits/diffs. Major pain if you don't.
iwein
be consistent _AND_ have a tool that can format sources according to the chosen standard.
Thorbjørn Ravn Andersen
Good answer - people should take the bold parts to heart ...
Marius Schulz
@Marius Thanks! I agree.
jjnguy
"one developer will reformat a file with their auto-formatter..." I've seen this happen somewhere before. :)
Bill the Lizard
@Bill, Haha, that is exactly what I was thinking about when I typed that last part of my answer.
jjnguy
+1  A: 

The most important things are that

  1. Readable to you
  2. Readable to others working on the project

Everyone will have their own nuances. If your boss says you -must- use tabs, then you use tabs. If the company convention is 4 spaces on compiled code and 2 on meta data files, that's what you do.

But be consistent, and make sure it's readable. Readability is the only significant criteria.

glowcoder
+5  A: 

Thing almost everyone will agree on:

  • Put spaces after commas
  • Put newlines after semicolons (with the exception of for loop declarations)
  • Indent the body of all blocks (anything inside {}) by one tab or four spaces (your choice)
  • Put a newline after a closing } that ends a block (with a few exceptions)

There are a lot more things than that which some teams will insist upon for consistency, but these elements of code formatting are universal.

There are basically two ways to deal with if blocks and anything with the same format (for, while, using, etc):

if (condition) {
    /* code */
}

versus:

if (condition)
{
    /* code */
}

This is purely a matter of preference. Pick one style and stick with it (or conform to the rest of your team).

One possible exception to the "newline after }" rule is for grouped if/else if/else, blocks, try/catch blocks, or other closely-connected blocks, which many people prefer to space thusly:

if (condition) {
    /* code */
} else if (condition2) {
    /* code */
} else {
    /* code */
}
JSBangs
I wouldn't say spaces after commas are universal. I know lots of people who hate them...
Kendrick
Also, this one: "Put a newline after a closing `}`" I cannot agree with that 100% of the time.
jjnguy
@Kendrick, those people should be beaten with the cluebat. (I've never met anyone that eschewed spaces after commas).
JSBangs
I agree about spaces after commas, however I *do* like to put `else if` and `else` after a closing brace--I find it helps keep the connectedness of the blocks obvious.
chaiguy
+1 Though I prefer the 2nd option, where it is more apparent where the { is closed and what the } closes.
Danny Varod
Newline after closing `}` is also not universal when it comes to do-while loops. I put the `while` on the same line as the closing `}`.
Tyler McHenry
I don't agree that you need four spaces to indent the body of a block, and it's certainly not universal. And I agree that a new line after a closing `}` is often good, but am not going to do it between `} catch ( //...` or `} else {`. That is certainly not universal.
Mark Peters
Two things missing. (Be consistent was covered by another answer.) The other thing is after a logical block of code, consider an extra newline or two of whitespace, to visually separate things on screen.
Dean J
A: 

There are many styles or coding rules around. I think nobody will be impressed by layout or spacing and pay more attention to the code itself. Tools can convert from one coding style to another (code beautifier) so that you can pretty safely choose any style. Like jjnguy said, most important is to be consistent.

jdehaan
+1  A: 

The whitespace programming language. A language that only has white spaces

Craig Suchanec
There's always one in the crowd.
kenny
+3  A: 

This is a pretty controversial (and subjective) topic, so there's not going to be a "correct" answer. However, my advice is use vertical whitespace sparingly, as too much of it reduces the amount of code one can see on-screen at a given time.

I personally like to use horizontal whitespace to make code more readable like so:

public void MyMethod( int param1, double param2 ) {
    if ( param1 < param 2 ) {
        member.OtherMethod( param1 );
    }
}

...but really, to each his/her own. :)

Also, if you're using Visual Studio or another tool that supports it, spend the time to set up your auto-formatting rules, and use the auto-format religiously. :) It will really help to keep your code clean and consistent.

chaiguy
Personally I'd say the opposite, use vertical whitespace whenever you need to delineate a logical paragraph or grouping, but I agree--don't put so much code in a method that you end up going off the screen for most methods. Don't discard readability for code-cramming, just code better.
Bill K
I do use blank lines to separate logical blocks within the same scope, so I agree there. Putting opening braces on the same line as a block affords me extra space to work with, however.
chaiguy
A: 

In general, whitespace is your friend. Add it whereever it makes code more readable. Whitespace compiles to the most efficient code possible: none!

In general, and this is subjective...

Open and close curly braces (e.g., { and }) go on a line by themselves. (Exception for javascript, where open curly brace goes on the line that creates the block.)

Leave a blank line between methods.

If it helps readability, leave a blank line between properties.

It's not strictly a whitespace issue, but only declare one variable per line. Don't stack variables in declarations.

int i, j;  // stacked declaration - don't do this!

Don't stack multiple statements on one line, either.

Keep your indentations easily readable; usually 4 spaces is good.

Keep line lengths short enough to fit on your monitor. Split long lines of code, and indent continuations.

If a parameter list is too long for a single line, format with one parameter per line.

That should get you started.

Cylon Cat
+2  A: 

Be consistent, even when modifying another developers code. If the indenting standards (if any) of your project don't prescribe how to format your code, or your don't use an automatic tool like Narrange, or Resharper, then try to stick with the formatting used by the other developer. Yes, do turn on white space indicators if you have to (for the tab vs. spaces debate)

paquetp
+1  A: 

Whitespace is not the primary factor in creating readable code. Indeed, I would never be "impressed by how simple and easy to understand it is" due to the author's use of white space. I might go the other way and think that some code is very unreadable due to a poor use of whitespace, but at best you're going to get me to not be disappointed in you.

Real readability comes from modularized, self documenting code. It flows out of consistency, intelligent naming of fields and functions, and design principles (especially separating concerns). These things will impress me. For whitespace, I have auto-formatters.

As for suggestions on best practices with whitespace, I think the other answers have all the good points covered.

Mark Peters
A: 

I recommend you read Code Complete and Clean Code. These books will teach you about formatting code, commenting, and many more topics.

kirk.burleson
+6  A: 

Do whatever you like with whitespace under the following restrictions:

  1. Don't commit changes in whitespace together with changes in code
  2. Don't change whitespace in an existing file unless you have a good (reasonably objective) argument for it.

As an optimization you can try to agree on code style with others so you don't waste time complying with 1 and 2.

iwein
This is a good point, and I've violated #1 a few times. It usually made for major pain later on.
Michael Mathews
+1  A: 

There is no "best" formatting, but if you use the same formatting as most other programmers, its easier for them to read your code, and it becomes easier for you to read their code!

Some guidelines to find out how other programmers use white sapces (from the java world):

  • read a "style guide" (like the Elements of Java style
  • read well-known code examples (for examples, the JDK contains the source code for all non-native JRE classes)
  • look at what your tools support (Eclipse has an "auto format" function, Ctrl+Shift+F); just let the tool indent your code!
mfx