Lesson 19 of 54

Code Formatting and Aesthetics

The Power of Consistent Formatting

I've seen teams spend hours debating tabs versus spaces. This is exactly backwards.

The content of the debate doesn't matter. What matters is that everyone does the same thing. Inconsistent formatting forces your brain to parse style instead of logic. Consistent formatting becomes invisible—which is exactly what you want.

Why Formatting Matters

When you read code, your brain does two things:

  1. Parse the structure (where are the blocks? what's nested?)
  2. Understand the logic (what does this code do?)

Inconsistent formatting makes the first task harder, leaving less mental energy for the second.

Research backs this up: studies in Code Complete show that consistent formatting improves comprehension speed and reduces errors during modification.

Vertical Formatting

Vertical formatting is about how code flows down the page.

Code that works together should appear together:

Javascript
// BAD: Related code scattered
const userEmail = user.email;
const orderDate = order.createdAt;
const userAge = calculateAge(user.birthDate);
const orderTotal = order.total;
const userName = user.name;
const orderItems = order.items;

// GOOD: Grouped by concept
const userName = user.name;
const userEmail = user.email;
const userAge = calculateAge(user.birthDate);

const orderDate = order.createdAt;
const orderTotal = order.total;
const orderItems = order.items;

Use Blank Lines as Paragraph Breaks

Blank lines signal "new thought." Use them to separate logical sections:

Javascript
function processOrder(order) {
  // Validation
  if (!order.items.length) {
    throw new EmptyOrderError();
  }
  
  // Calculation
  const subtotal = calculateSubtotal(order.items);
  const tax = calculateTax(subtotal, order.taxRate);
  const total = subtotal + tax;
  
  // Persistence
  order.total = total;
  order.status = 'processed';
  await saveOrder(order);
  
  // Notification
  await notifyCustomer(order);
  
  return order;
}

Each blank line marks a transition. Readers can skim the structure without reading every line.

Vertical Density

Closely related code should have no blank lines:

Javascript
// BAD: Unnecessary blank lines
const firstName = user.firstName;

const lastName = user.lastName;

const fullName = `${firstName} ${lastName}`;

// GOOD: Dense for related code
const firstName = user.firstName;
const lastName = user.lastName;
const fullName = `${firstName} ${lastName}`;

Vertical Distance

Related concepts should be vertically close:

Javascript
// BAD: Definition and usage far apart
const userService = new UserService();
// ...100 lines of other code...
const user = userService.getUser(id);

// GOOD: Keep them close or make the connection obvious
const userService = new UserService();
const user = userService.getUser(id);

Horizontal Formatting

Horizontal formatting is about line length and horizontal spacing.

Line Length: 80-120 Characters

Long lines are hard to read. Short lines waste space. The sweet spot is 80-120 characters.

Why? Human eyes read most efficiently in moderate-width columns. This is why newspapers use narrow columns and books don't print edge-to-edge.

Javascript
// BAD: Too long
const result = someObject.someProperty.someMethod(argument1, argument2, argument3, argument4, argument5);

// GOOD: Break at logical points
const result = someObject.someProperty.someMethod(
  argument1,
  argument2,
  argument3,
  argument4,
  argument5
);

Breaking Long Lines

Break at logical points:

Javascript
// Break after operators
const total = subtotal
  + shipping
  + tax
  - discount;

// Break after opening parens
const user = createUser(
  userData.name,
  userData.email,
  userData.preferences
);

// Break chained methods
const result = data
  .filter(item => item.isActive)
  .map(item => item.value)
  .reduce((sum, val) => sum + val, 0);

Horizontal Spacing

Use spaces to show relationships:

Javascript
// Tight spacing for high association
function calculateArea(width, height) {
  return width * height;
}

// Space around operators for readability
const total = price + tax - discount;

// No space inside parens
if (isValid) { }

// Space after keywords
if (condition) { }
for (let i = 0; i < 10; i++) { }
while (running) { }

Automate Formatting

The best formatting is formatting you never think about.

Use a Formatter

Prettier, Black (Python), gofmt (Go), rustfmt (Rust)—use whatever your ecosystem provides.

Json
// .prettierrc
{
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "printWidth": 100
}

Format on Save

Configure your editor to format automatically when you save. You type messy; the formatter fixes it.

Pre-commit Hooks

Enforce formatting before code enters the repository:

Bash
# .husky/pre-commit
npx prettier --check .
npx eslint .

No more formatting debates in code review. The tool decides.

CI Checks

Fail the build if formatting is wrong:

Yaml
- name: Check formatting
  run: npx prettier --check .

This catches anything that slips past local hooks.

The End of Formatting Debates

Once you automate formatting, debates end:

  • "Should we use tabs or spaces?" → Prettier decides.
  • "Where should braces go?" → Prettier decides.
  • "How do we indent chained methods?" → Prettier decides.

Energy spent arguing about formatting is energy not spent solving problems. Automate and move on.


Key insight: Consistent formatting makes code easier to read by eliminating cognitive overhead. The specific choices matter less than consistency. Automate formatting with tools like Prettier so you never argue about it again.