HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMajor

How to break up long lines of code. (Example Line: Results of method call added to list.)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linemethodaddedexamplelongcallhowcoderesultslist

Problem

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.

Solution

I would break it up something like this:

shippedItems.AddRange(
    OrderItem.Fetch(market: this.MARKET,
                    shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,
                    orderPlacedAfter: serverTime.AddDays(-7),
                    orderPlacedBefore: serverTime.AddHours(-85)));


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.

Code Snippets

shippedItems.AddRange(
    OrderItem.Fetch(market: this.MARKET,
                    shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE,
                    orderPlacedAfter: serverTime.AddDays(-7),
                    orderPlacedBefore: serverTime.AddHours(-85)));

Context

StackExchange Code Review Q#772, answer score: 22

Revisions (0)

No revisions yet.