4. Formatting - tuansondinh/clean_code GitHub Wiki

"If you are working on a team, then the team should agree to a single set of formatting rules and all members should comply. It helps to have an automated tool that can apply those formatting rules for you." S.76

4.1 Vertical Formatting - How big should a source file be?

Files should be circa 200 lines long with an upper limit of 500. "Although this should not be a hard and fast rule, it should be considered very desirable. Small files are usually easier to understand than large files are." S.77

4.1.1 The Newspaper Metaphor

"We would like a source file to be like a newspaper article." S.77 "The topmost parts of the source file should provide the high-level concepts and algorithms. Detail should increase as we move downward, until at the end we find the lowest level functions and details in the source file." S.77

4.1.2 Vertical Openness Between Concepts

"Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines." S.78

BAD:

package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
 public static final String REGEXP = "'''.+?'''";
 private static final Pattern pattern = Pattern.compile("'''(.+?)'''",
   Pattern.MULTILINE + Pattern.DOTALL);
 public BoldWidget(ParentWidget parent, String text) throws Exception {
   super(parent);
   Matcher match = pattern.matcher(text);
   match.find();
   addChildWidgets(match.group(1));}
 }

GOOD:

package fitnesse.wikitext.widgets;

import java.util.regex.*;

public class BoldWidget extends ParentWidget {
 public static final String REGEXP = "'''.+?'''";
 private static final Pattern pattern = Pattern.compile("'''(.+?)'''",
   Pattern.MULTILINE + Pattern.DOTALL
 );

 public BoldWidget(ParentWidget parent, String text) throws Exception {
   super(parent);
   Matcher match = pattern.matcher(text);
   match.find();
   addChildWidgets(match.group(1));
 }
}

4.1.3 Vertical Density (implies close association)

"So lines of code that are tightly related should appear vertically dense." S.79

4.1.4 Vertical Distance

"Concepts that are closely related should be kept vertically close to each other" S.80

Variable Declarations

"Variables should be declared as close to their usage as possible." S.80

In functions at the top:

private static void readPreferences() {
**  InputStream is= null;**
  try {
    is= new FileInputStream(getPreferencesFile()); 
...

Instance variables should be declared at the top of the class

Dependent Functions

"If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible." S.82

Conceptual Affinity

"The stronger that affinity, the less vertical distance there should be between them." S.84 "Affinity might be caused because a group of functions perform a similar operation." S.84

static public void assertTrue(String message, boolean condition) {
  if (!condition) fail(message);
}
static public void assertTrue(boolean condition) { 
  assertTrue(null, condition);
}

4.1.5 Vertical Ordering

  • high level (abstraction) to low level as we go down in the code
  • most important concepts at the top "with the least amount of polluting detail" S.84
  • details at bottom

4.2 Horizontal Formatting

"Programmers clearly prefer short lines." S.85

  • keep your lines short with a maximum of 120 characters

4.2.1 Horizontal Openness and Density

"We use horizontal white space to associate things that are strongly related and disassociate things that are more weakly related" S.86

GOOD:

private void measureLine(String line) { 
  lineCount++;
  int lineSize = line.length();
  totalChars = totalChars + lineSize; 
  lineWidthHistogram.addLine(lineSize, lineCount);
  recordWidestLine(lineSize);
}

4.2.2 Horizontal Alignment

  • use unaligned declarations and assignments, "because they point out an important deficiency. If I have long lists that need to be aligned, the problem is the length of the lists, not the lack of alignment." S.87 -> split up class

GOOD:

private Socket socket; 
private InputStream input;
private OutputStream output;

BAD:

private Socket       socket; 
private InputStream  input;
private OutputStream output;

4.2.3 Indentation

"A source file is a hierarchy rather like an outline."

"To make this hierarchy of scopes visible, we indent the lines of source code in proportion to their position in the hierarchy."

"Programmers rely heavily on this indentation scheme." S.88

BAD:

public void serve(Socket s) { serve(s, 10000); } public void serve(Socket s, long requestTimeout) { try { FitNesseExpediter sender = new FitNesseExpediter(s, context); sender.setRequestParsingTimeLimit(requestTimeout); sender.start(); } catch(Exception e) { e.printStackTrace(); } }

GOOD:

public void serve(Socket s, long requestTimeout) { 
  try {
    FitNesseExpediter sender = new FitNesseExpediter(s, context);
    sender.setRequestParsingTimeLimit(requestTimeout); 
    sender.start();
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}

4.2.4 Breaking Indentation

Even for short if-, while- statements, functions etc., you should avoid breaking Indentations. BAD:

public class CommentWidget extends TextWidget {
public CommentWidget(ParentWidget parent, String text){super(parent, text);}
public String render() throws Exception {return ""; } }

GOOD (much more readable):

public class CommentWidget extends TextWidget {
  public CommentWidget(ParentWidget parent, String text) {
    super(parent, text);
  }
  public String render() throws Exception { 
    return "";
  }
}

4.3 Team Rules

"A team of developers should agree upon a single formatting style, and then every member of that team should use that style" S.90

  • encode those rules into the code formatter of your IDE