How to break up long lines of code. (Example Line: Results of method call added to list.)
Often I generate long lines of code such as the following...
shippedItems.AddRange(OrderItem.Fetch(market: this.MARKET, shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE, orderPlacedAfter: serverTime.AddDays(-7), orderPlacedBefore: serverTime.AddHours(-85)));
... which adds the results of a method call to an existing list.
Adding white space to this line could improve readability. At one point in time or another have rationalized almost every possible behavior between:
- Leave everything on a single line and let the editor wrap where it feels is best.
- Put even shippedItems.AddRange( on a line by itself.
While over time I feel that the clarity and readability of the code that I write has improved -- and lets hope for reasons other then white space -- I have never come to peace with how to break long lines.
I will up vote any answer that does NOT include as the solution:
- shorter variable names.
- disregarding named parameters (at least for this example).
- creation of variables only used once.
There's nothing wrong with creating a variable that is only used once. Sometimes, the required indentation is just too much.
I am curious as to why you would not use a Pretty Print preprocessor to do this for you.
I would break it up something like this:
Depending on previous indentation, some lines might flow over the "max line length", but I think that characters per line is more of a suggestion and there are good times to break that rule because breaking it leads to code that is more readable than code that doesn't.
Rules that I find helpful:
- New line after an open paren.
- Line breaks after commas.
- Indent the inner method calls.
- Line up parameters to a method that are on new lines.
- Break "max line length" rules if it means the code is more readable.