views:

1099

answers:

15

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?

+1  A: 

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
+2  A: 

Manual line breaks: Just Say No.

chaos
+1  A: 

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.

Sorry to say that, but this code is extremely hard to read for me.
Mnementh
+4  A: 

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
It's harder to read and understand this, than rbobby's-variant, with the brace on a new line.
Mnementh
+2  A: 

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
As an emacs user I'd normally argue w/ the Visual Studio user, but he's exactly right on this one.
T.E.D.
I don't fight the IDE... it fights me!
Juliano
+1  A: 

I've asked a similar question in the past:

Where to wrap a line of code, especially long argument lists?

The difficulty with this type of question is its subjective nature, so I wasn't able to accept an answer.

I think the important part is to keep the indenting style is consistent throughout your code base.

coobird
A: 

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
I can fit 2 100 char buffers side by side on my screen.In general, Linus is right.
T.E.D.
A: 

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  A: 

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" :)

It's uncommon to set the opening brace on the following line, but that can prevent the readability-problems with indenting wrapped lines.
Mnementh
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. ;-)
TomWij
+1 for matching braces. It just makes things so much clearer, so why wouldn't you?
chimp
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
+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
+5  A: 

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: http://stackoverflow.com/questions/380885/can-you-simplify-this-algorithm/381034#381034 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)
TomWij
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
+1  A: 

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
+1  A: 

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
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
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.
TomWij
I have the "advantage" of only having to work on my own code...
masher
A: 

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.

A: 

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
A: 

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