4.5 Line-wrapping

Terminology Note: Line wrapping is breaking a chunk of code into multiplelines to obey column limit, where the chunk could otherwise legally fit in asingle line.

There is no comprehensive, deterministic formula showing exactly how toline-wrap in every situation. Very often there are several valid ways toline-wrap the same piece of code.

Note: While the typical reason for line-wrapping is to avoid overflowing thecolumn limit, even code that would in fact fit within the column limit may beline-wrapped at the author's discretion.

Tip: Extracting a method or local variable may solve the problem without theneed to line-wrap.

4.5.1 Where to break

The prime directive of line-wrapping is: prefer to break at a higher syntacticlevel.

Preferred:

  1. currentEstimate =
  2. calc(currentEstimate + x * currentEstimate) /
  3. 2.0;

Discouraged:

  1. currentEstimate = calc(currentEstimate + x *
  2. currentEstimate) / 2.0;

In the preceding example, the syntactic levels from highest to lowest are asfollows: assignment, division, function call, parameters, number constant.

Operators are wrapped as follows:

  • When a line is broken at an operator the break comes after the symbol. (Notethat this is not the same practice used in Google style for Java.)
    • This does not apply to the dot (.), which is not actually anoperator.
  • A method or constructor name stays attached to the open parenthesis (()that follows it.
  • A comma (,) stays attached to the token that precedes it.

Note: The primary goal for line wrapping is to have clear code, notnecessarily code that fits in the smallest number of lines.

4.5.2 Indent continuation lines at least +4 spaces

When line-wrapping, each line after the first (each continuation line) isindented at least +4 from the original line, unless it falls under the rules ofblock indentation.

When there are multiple continuation lines, indentation may be varied beyond +4as appropriate. In general, continuation lines at a deeper syntactic level areindented by larger multiples of 4, and two lines use the same indentation levelif and only if they begin with syntactically parallel elements.

?? addresses the discouraged practice ofusing a variable number of spaces to align certain tokens with previous lines.