5.- Format
Code Formatting Guidelines
You should ensure that your code is nicely formatted. Pick a simple set of rules that govern the format of your code and apply them consistently. If you are working on a team, agree on one formatting standard and have every member comply with it. An automated formatter helps enforce the style.
The Purpose of Formatting
Code formatting is about communication, and communication is a professional developer’s first priority. Readable, consistent style improves maintainability and extensibility long after individual lines of code have changed.
Vertical Formatting
File Length
Aim for files around 200 lines, with an upper limit of about 500. Smaller files are usually easier to understand than large ones.
The Newspaper Metaphor
- • The filename should be simple yet descriptive.
- • The top of the file should expose the highest‑level concepts; detail should increase as you move downward, ending with low‑level utilities.
Vertical Openness Between Concepts
Separate distinct thoughts with blank lines. Most code is read left‑to‑right, top‑to‑bottom; whitespace helps readers see where one idea ends and the next begins.
Vertical Density
Lines that are tightly related should sit close together.
public class ReporterConfig {
/** The class name of the reporter listener */
private String m_className;
/** The properties of the reporter listener */
private List<Property> m_properties = new ArrayList<>();
public void addProperty(Property property) {
m_properties.add(property);
}
}
Vertical Distance
Closely related concepts belong vertically close—often in the same file—unless you have a compelling reason to separate them. This reduces “file hopping”.
-
Variable declarations — place them near their first use.
private static void readPreferences() { InputStream is = null; try { is = new FileInputStream(getPreferencesFile()); setPreferences(new Properties(getPreferences())); getPreferences().load(is); } catch (IOException e) { if (is != null) is.close(); } }
-
Loop variables — declare them inside the loop.
public int countTestCases() { int count = 0; for (Test each : tests) count += each.countTestCases(); return count; }
-
Instance variables — declare them at the top of the class.
-
Dependent functions — if
f()
callsg()
, placef()
aboveg()
when possible. -
Conceptual affinity — functions that perform similar work or operate on the same data belong together.
public class Assert {
public static void assertTrue(String message, boolean condition) {
if (!condition) fail(message);
}
public static void assertTrue(boolean condition) {
assertTrue(null, condition);
}
public static void assertFalse(String message, boolean condition) {
assertTrue(message, !condition);
}
public static void assertFalse(boolean condition) {
assertFalse(null, condition);
}
}
Vertical Ordering
Strive for a top‑down dependency flow: high‑level functions first, low‑level details last.
Horizontal Openness and Density
Use horizontal whitespace to:
- Associate strongly related elements.
- Separate weakly related ones.
private void measureLine(String line) {
lineCount++;
int lineSize = line.length();
totalChars += lineSize;
lineWidthHistogram.addLine(lineSize, lineCount);
recordWidestLine(lineSize);
}
- No space between a method name and its
(
—they are inseparable. - Space around
=
highlights the left side vs. right side of an assignment. - Space after commas separates arguments.
Operator Precedence with Whitespace
public class Quadratic {
public static double root1(double a, double b, double c) {
double det = determinant(a, b, c);
return (-b + Math.sqrt(det)) / (2 * a);
}
public static double root2(double a, double b, double c) {
double det = determinant(a, b, c);
return (-b - Math.sqrt(det)) / (2 * a);
}
private static double determinant(double a, double b, double c) {
return b * b - 4 * a * c;
}
}
Multiplication has higher precedence, so factors appear without spaces; addition/subtraction have lower precedence, so terms are separated by spaces.
Horizontal Alignment
Avoid large columns of aligned assignments; excessively long aligned lists usually signal that the list itself is the problem.
Indentation
Source files form a hierarchy (file → class → method → block). Indent code one level deeper for each nested scope:
public class CommentWidget extends TextWidget {
public static final String REGEXP =
"^#[^\\r\\n]*(?:(?:\\r\\n)|\\n|\\r)?";
public CommentWidget(ParentWidget parent, String text) {
super(parent, text);
}
public String render() throws Exception {
return "";
}
}
Good indentation visually communicates scope and structure; broken indentation obscures it.
Following these formatting principles helps every reader—teammates and, eventually, future‑you—understand the code faster and modify it with confidence.