Tutorial :If you break long code lines, how do you indent the stuff on the next line?



Question:

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?


Solution:1

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


Solution:2

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)    


Solution:3

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;  }  


Solution:4

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


Solution:5

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.


Solution:6

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  }  


Solution:7

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.


Solution:8

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.


Solution:9

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.


Solution:10

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.


Solution:11

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.


Solution:12

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.


Solution:13

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.


Solution:14

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;  }  


Solution:15

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »