10

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.

iwein
  • 25,788
  • 10
  • 70
  • 111
Immanu'el Smith
  • 683
  • 2
  • 8
  • 18
  • Tried to add a "subjective" tag, but can't because of 5 tag limit. However, not that answers will be somewhat subjective! – Cylon Cat Jun 14 '10 at 17:25
  • 11
    There are exactly n "BEST" ways to do it, where n is the number of people you ask. I assume you will get a handful of great suggestions here; choose which one you like best and stick with it. Consistency makes it easy to read, but will never impress future programmers. On the other hand, if you change whitespace usage mid-module, those future-programmers who come along to fix your code will hate you. – MJB Jun 14 '10 at 17:25
  • 2
    Try `whitespace` for programming. It's great. – aviraldg Jun 14 '10 at 17:26
  • 3
    "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." When future programmers go over your code layout, whitespace is going to be the least of their concerns – Michael Mrozek Jun 14 '10 at 17:28
  • 3
    It always puzzles me some when an answer to a somewhat subjective question is accepted so fast... – Mark Schultheiss Jun 14 '10 at 17:54
  • @Mark, I was surprised as well. – jjnguy Jun 14 '10 at 17:59
  • 1
    Everything else I already have known, however no one has ever stressed the importance of being consistent. So fair it is to say that I asked a question and it was answered. – Immanu'el Smith Jun 14 '10 at 18:07
  • @MJB: i'd say it's something closer to log(n)^2... – RCIX Jun 15 '10 at 07:19
  • @RCIX: Okay... Is there math to prove that, or do you just not like my round numbers? – MJB Jun 15 '10 at 12:29
  • @MJB: No math to prove it, but i've observed that there are generally several styles for a given language, and people adhere to (some small variation of) one of those. :) – RCIX Jun 15 '10 at 23:00
  • @RCIX: that's ok, i was just messin' with you. – MJB Jun 16 '10 at 02:12
  • I've nominated the question for reopening because it has been given an answer supported by facts and expertise (mine) which is objectively and provably correct. The fact that there is also much (annoyingly) subjective chatter about code style is irrelevant and no good reason to close the question. – iwein Jul 09 '15 at 04:18

13 Answers13

30

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
  • 136,852
  • 53
  • 295
  • 323
  • 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 Jun 14 '10 at 17:27
  • @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 Jun 14 '10 at 17:30
  • 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 Jun 14 '10 at 17:36
  • 2
    You should mention that you should be consistent within a source repository to get readable commits/diffs. Major pain if you don't. – iwein Jun 14 '10 at 17:36
  • 1
    be consistent _AND_ have a tool that can format sources according to the chosen standard. – Thorbjørn Ravn Andersen Jun 14 '10 at 18:01
  • Good answer - people should take the bold parts to heart ... – Marius Schulz Jun 14 '10 at 19:33
  • "one developer will reformat a file with their auto-formatter..." I've seen this happen somewhere before. :) – Bill the Lizard Jun 14 '10 at 20:17
  • @Bill, Haha, that is exactly what I was thinking about when I typed that last part of my answer. – jjnguy Jun 14 '10 at 20:37
  • I've given this more thought than it merits probably, but I respectfully disagree. Consistently (but blindly) auto-formatting is much more harmful than manually formatting as you please. Consistent formatting is a side effect of careful coding, not a rule to follow. I would go as far as to say that the autoformatter is an advanced tool not to be used lightly (although in cases where a style is agreed upon it can be rendered harmless). – iwein Jan 02 '11 at 19:15
  • I've been sending new team members over to this question after screwups (e.g. causing a production issue that cannot be traced back to a single commit). It has improved debugging production issues in my teams significantly. Whitespace is important, and there is exactly one right way to deal with it. The accepted answer is wrong. – iwein Jul 09 '15 at 04:24
15

Keep your diffs clean.

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.

Why?

The most important factor in dealing with whitespace is not readability of the files themselves, but the readability of the diffs. The diffs are the things that you'll be looking at when cold sweat is trickling down your spine and thinking seems harder than usual.

The above two rules make sure the diffs are clean and readable. Being consistent in how you deal with whitespace helps, but it is foolproof only in a perfect world. It is a nice thing to strive for, but not as important as keeping the diffs clean.

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
  • 25,788
  • 10
  • 70
  • 111
10

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 */
}
JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
  • 1
    I wouldn't say spaces after commas are universal. I know lots of people who hate them... – Kendrick Jun 14 '10 at 17:31
  • 1
    Also, this one: "Put a newline after a closing `}`" I cannot agree with that 100% of the time. – jjnguy Jun 14 '10 at 17:33
  • 4
    @Kendrick, those people should be beaten with the cluebat. (I've never met anyone that eschewed spaces after commas). – JSBձոգչ Jun 14 '10 at 17:33
  • 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. – devios1 Jun 14 '10 at 17:35
  • +1 Though I prefer the 2nd option, where it is more apparent where the { is closed and what the } closes. – Danny Varod Jun 14 '10 at 17:36
  • 1
    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 Jun 14 '10 at 17:39
  • 1
    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 Jun 14 '10 at 17:40
  • 2
    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 Jun 14 '10 at 17:42
3

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,639
  • 11
  • 19
2

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.

devios1
  • 36,899
  • 45
  • 162
  • 260
  • 1
    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 Jun 14 '10 at 18:07
  • 1
    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. – devios1 Jun 14 '10 at 19:51
1

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.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
1

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

Craig Suchanec
  • 10,474
  • 3
  • 31
  • 39
1

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
  • 80,126
  • 17
  • 159
  • 190
1

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

kirk.burleson
  • 1,211
  • 2
  • 18
  • 29
1

Some stuff to do: Be sure to search Stack Overflow for more examples with similar tags.

What does a good programmer's code look like?

https://stackoverflow.com/questions/563036/what-is-elegant-code

Stuff NOT to do:

https://stackoverflow.com/questions/237719/most-frustrating-programming-style-youve-encountered

Community
  • 1
  • 1
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
1

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
  • 7,168
  • 26
  • 29
0

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
  • 19,700
  • 6
  • 57
  • 97
0

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
  • 7,111
  • 2
  • 25
  • 33