41

Sometimes you have to write in your source long lines, that are better to break. How do you indent the stuff ceated by this.

You can indent it the same:

very long
statement;
other statement;

That makes it harder to differentiate from the following code, as shown in the example. On the other hand you could indent it one level:

very long
   statement;
other statement;

That makes it easier, but it can happen, that the long line is the start of a nested block, that you want to indent, like this:

if ((long test 1) &&
   (long test 2) &&
   (long test 3)) {
   code executed if true;
}

In this case again it's hard to read. The third possibility I can think of, is to not break long lines at all, modern editors can handle it and create soft linebreaks. But with another editor you have to scroll sideways and you cannot influence the position, the editor breaks your long line.

What possibility do you prefer? Do you have other ideas to solve this? Can you support your preference with a good justification?

Mnementh
  • 50,487
  • 48
  • 148
  • 202

14 Answers14

47

I like braces on their own line because I fine it easier to see the condition and inner block all as one item (if you know what I mean):

if ((long test 1)
    && (long test 2)
    && (long test 3)) 
{
    code executed if true;
}

and I like starting additional conditional lines with what the condition is because I find that the "joining" condition is very important and it tends to get overlooked at the end of the previous line.

I also try and indent such that the effect of parenthesis are obvious (though trying to avoid long conditionals is generally a good thing).

I try and structure stuff so that I can easily "scan" for "stuff" :)

user53794
  • 3,800
  • 2
  • 30
  • 31
  • It's uncommon to set the opening brace on the following line, but that can prevent the readability-problems with indenting wrapped lines. – Mnementh Mar 30 '09 at 23:00
  • 4
    Well, it might look uncommon to you, but I always place it on a new line to let it line up in the same column of the closing brace making it easy to match them visually when scrolling upwards i code. Well, everyone has his own way of placing them. ;-) – Tamara Wijsman Mar 30 '09 at 23:08
  • 2
    it is not uncommon, it just depends on the convention that you see. It is pretty much 50/50 in my experience (with some wierdos indenting the { } along with the code that belongs in the block) – TofuBeer Mar 30 '09 at 23:46
  • 3
    +1 for putting the operator at the start of the new line. This makes it very obvious which lines are a continuation while only scanning the first few characters of each line. – too much php Aug 17 '09 at 04:58
  • If you put the brace/bracket/paren on a line by itself, you blow up the vertical span and make it harder to apprehend. I just reviewed on 185-page book that would have been *FIVE PAGES SHORTER* if they hadn’t done what you’ve done. But I’m a “braces are obligatory” kind of guy, so I never get in trouble with them the way a lot of people do. – tchrist Nov 19 '10 at 03:58
  • To be honest, I don't see the argument for 'braces on the next line'. If the closing brace falls on the same column as the block's base keyword (if/where/for, etc.) it lines up just fine visually. Consistent indentation also helps visually; when I see the piece of code above, I jump to thinking it's if/then/else instead of a simple if statement. – Kenogu Labz Dec 03 '12 at 16:47
  • 3
    Bracing style is a huge flame war, and no one should be allowed to give an opinion before having given a chance (a real chance, like a whole project) to both these alternatives. I know I first hated the style I now prefer. But now that I've used both for long, it does not really matter anymore. – Gauthier Jun 12 '13 at 11:27
32

You should try to prevent writing lines longer than 80 characters rather than breaking them:

  • Try to minimize indentation by converting conditions and encapsulating code.

Linus Torvalds: If you need more than 3 levels of indentation, you're screwed anyway,
and should fix your program.

This also has the side effect of making you code much more readable, besides that the conditions are the other things you encapsulate are ready to be used elsewhere.

bool encapsulatedLongCondition() // Add some parameters
{
  if (!condition1)
    return false;

  if (!condition2)
    return false;

  // ... (Other conditions)

  return true;
}    

if (encapsulatedLongCondition())
{
  // ... (Call some methods, try not to introduce deeper if/loop levels!)
}

Simplifying your condition through boolean algebra and trying to invert the condition and return value can help a lot. :-)

See also: Can you simplify this algorithm? See also 2: Refactor for C# has the ability to assist you with this. ;-)

  • Use type definitions and try to avoid long names

A simple example, imagine how long it would be using Days without typedef with longer names in another container.

struct Day
{
  // Some data
};
struct Event
{
  // Some data
};
typedef list<Event> Events;
typedef map<Day, Event> Days;
// Some other container that would else be long...
  • ... (You should try to analyze why your line is long and find a solution for it)

Hope you get the general idea, this way you won't need to come up with a dirty line break. ;-)

The only place where I would see long lines occur is in the prototypes of your functions or when calling them, there you should just try to break after the last possible comma and continue on the next line. Rather than doing it after each and wasting multiple lines making scrolling bloated and your function stand out too much... You could place the return type on the line before the function name if you happen to frequently see these long lines.

void longFunctionName(ParameterType1 parameter1, ParameterType2 parameter2,
                      ParameterType3 parameter3, ParameterType4 parameter4)  
Community
  • 1
  • 1
Tamara Wijsman
  • 12,198
  • 8
  • 53
  • 82
  • I actually try to avoid long lines, to prevent running into the indentation-problems. But sometimes long lines occur. But you give some good hints to optimize them. +1 – Mnementh Mar 30 '09 at 23:05
  • Is placing return type on the previous line compatible with google style? – uuu777 Feb 20 '16 at 17:26
  • 4
    For me, long lines occur because I give very expressive names to my variables. And I don't mind long variable names (as long as they're easy to read) since most editors I use have auto-complete features. – elatalhm Apr 05 '16 at 10:18
  • 2
    Please don't omit (curly) braces when you work with if statements (as seen in this answer). Every time you do, a puppy dies. Even Jon Skeet has admitted to making mistakes because of it. – Riegardt Steyn Jul 10 '17 at 10:44
  • 1
    @Heliac Please don't omit (curly) reasons when your work is to give me advice (as seen in this comment). Every time you do, a brain dies. I'm not Jon Skeet by the way, and therefore don't make those mistakes. – Tamara Wijsman Jul 10 '17 at 14:52
10

In general I do:

if (condition) {
     something;
}

for block delimiters. However, if the case of a long line I have to break up, I use this:

if (
    (long test 1) &&
    (long test 2) &&
    (long test 3)
) {
    code executed if true;
}

Key differences from rbobby's answer:

  1. Operators at the end of each line instead of the beginning of subsequent lines, to very clearly indicate visually that the line is incomplete
  2. Line break on first line before conditional element -- this helps keep code "shape" consistent.
  3. Closing paren not indented.

This has the visual effect of making parameter/conditional lists look kinda like code blocks (but with parens instead of curly braces. I find the symmetry pleasing. It also avoids having a bare opening curly brace on a line (which I think looks terrible).

Cory Petosky
  • 12,458
  • 3
  • 39
  • 44
  • By using the normal indent mechanism on new lines, rather than trying to line code up on subsequent lines, you also avoid the "tab vs spaces" holy war. – Rebs Jul 15 '21 at 02:21
9

I have two simple rules:

  1. Statement block: one indentation;
  2. Line continuation: two indentations or parenthesis aligned, whatever is further indented.

So, in the if case:

if ((long test 1) &&
        (long test 2) &&
        (long test 3)) {
    code executed if true;
}
Juliano
  • 39,173
  • 13
  • 67
  • 73
  • It's harder to read and understand this, than rbobby's-variant, with the brace on a new line. – Mnementh Mar 31 '09 at 08:36
  • 7
    This is actually terrible – void.pointer Sep 08 '15 at 14:08
  • 1
    This is actually used and recommended by Google: https://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Function_Declarations_and_Definitions , and clang-format also does this kind of indentation by default. – Juliano Sep 08 '15 at 14:16
  • @Juliano are you sure? Google style guide uses that format for long function parameter lists at both declaration and call site, but in the latest style guide they align each conditional in an if statement: https://google.github.io/styleguide/cppguide.html#Boolean_Expressions –  Jan 21 '16 at 21:56
  • It's also Oracle/Sun style: http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html @user755921 Google doesn't align each conditional in an if statement - they just uses regular indent 2 spaces, but continuation indent 4 spaces. This style is also used by default in Intellij IDEA. – Van0SS Apr 13 '18 at 03:30
3

I have a slight variation on what's already written here:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) 
{
    code executed if true;
}

I like having my boolean operators at the end of the line.

Long method names, or methods with lots of parameters are like this:

reallyLongMethodName (paramA,
                      paramB,
                      paramC);

with the bits lined up with the param name above; not the bracket...

Also, to reduce indentation, I've started using multiple return points in my code, as well as continues and breaks in my loops. eg

for(int i = 0; i < MAX; i++)
{
    if(!isPrime(i)) // predefined prime finding func
        continue;

    //now we have only prime values of i
}
masher
  • 3,814
  • 4
  • 31
  • 35
  • yes. I always line up my method parameters. some devs call me a neat freak for updating my code and others to this style... – MikeJ Mar 30 '09 at 23:13
  • What's the benefit to that? Updating working code of other programmers and using additional effort to spread it out over several lines makes you lose efficiency. – Tamara Wijsman Mar 30 '09 at 23:26
  • Trying to line up parameters across multiple lines leads to arguments being horizontally aligned randomly with different function name lengths. It also means changes to the function name or indent create N lines of changes rather than just one. If you instead use normal indentation all arguments are aligned consistently and code is easier to read. It also avoids the "tab vs space" holy war. – Rebs Jul 15 '21 at 02:22
2

I side with, "Don't fight the IDE."

However my IDE (Eclipse, Visual Studio) wants to break lines is how they are broken.

This may mean inconsistencies between languages, which is OK.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
2

Always indent, but if statements are special; I like to line up the tests, and I put the extra && operators on the left:

if (  (long test 1)
   && (long test 2)
   && (long test 3)) 
{
    code executed if true;
}

Pulling the && to the left to align with if is also possible, but I find this alternative harder to read.

Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533
  • This only looks nice if you indent with spaces, which I hate as it steals you the ability to decide yourself how much indention you like to see. So I always intend with tabs as whoever views the code can decide himself if a tab is 1, 2, 3, 4, 6, or 8 spaces, whatever he prefers. And thus I cannot use spaces to align an indention as I don't know how many spaces an indention will be for the viewer. – Mecki Jan 31 '17 at 15:56
1

With astyle, or whatever automatic indenter you're using. It seems to do a good enough job, and there usually are more important things to think about.

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
1

I keep bracketed expressions at the level of their opening:

if ((long test 1) &&
    (long test 2) &&
    (long test 3)) {
  code executed if true;
}

This makes it obvious which level each expression is at.

brian-brazil
  • 31,678
  • 6
  • 93
  • 86
1

I'd say it doesn't really matter what method you use providing it meets the following criteria:

  • it is sensible
  • you apply the same convention throughout your code.

If you're in a team development, do try to agree on a convention between you, by some arcane voting mechanism if you can't reach agreement otherwise and there's no-one to dictate.

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
1

The only reason for formatting code in a particular way is to make it readable. This is inherently subjective - do it in a way that looks good and that you feel would be more readable for someone looking at the code for the first time. And I'm going to buck the conventional wisdom and say, don't worry about any common standard - for two reasons

1) it's difficult in this situation, because there are so many different possibilities for broken lines

2) it doesn't buy you anything. period. again, code formatting is simply to make your code readable, having a standard way of formatting the particulars of your code does not buy you readability.

user13276
  • 4,873
  • 5
  • 21
  • 16
0

For Java Oracle provides those conventions. Java Code Conventions - Oracle.

  • Break after a comma
  • Break before an operator
  • Prefer higher-level breaks to lower-level breaks
  • Align the new line with the beginning of the expression at the same level on the previous line
  • If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 8 spaces instead

For an example,

longName1 = longName2 * (longName3 + longName4 - longName5)
            + 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
                        - longName5) + 4 * longname6; // AVOID

Another :

//DON’T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}
//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}

More examples are given in that document.

prime
  • 14,464
  • 14
  • 99
  • 131
0

In my opinion, a line width of 78 or 80 characters is useful since it makes it easier to have multiple files open next to each other on the same screen.

Justification, what about a quote by Linus Torvalds? :)

The answer to that is that if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.

I normally follow a conglomerate of the Google C++ coding style (you can adapt this to Java, too, I guess) and this C++ coding style.

Manuel
  • 6,461
  • 7
  • 40
  • 54
0

I almost never indent on the same line. However, I have on very rare ocassion re-initialize a bunch of variables like this

a 
= b
= c
= d
= e
= f
= 0;

The one key thing with doing something like this though, is to keep the assignment operator as the first character on the next line. This will give the maint. programmer a WTF moment when they see it, forcing them to look at, not just gloss over it.

Wrapping a very long statement, I'll do it where ever I feel it makes sense ... not necessarily on the first indent. So :

reallyLongMethodName (paramA,paramB,paramC);

would not get formatted like

reallyLongMethodName (paramA,
    paramB,
    paramC);

but would end up more like

reallyLongMethodName (paramA,
                    paramB,
                    paramC);

with all the parameters lining up with the opening parenthesis.

For if's and whiles, I'd do something like

if((long test 1) 
&& (long test 2) 
&& (long test 3))
{
    code executed if true;
}
John MacIntyre
  • 12,910
  • 13
  • 67
  • 106