Script Valley
Writing Clean Code: Naming, Functions & Structure
Code Structure and OrganizationLesson 3.3

How to organize code within a single file

file-level ordering, imports first, constants second, class ordering, newspaper metaphor, related code colocation

Within-File Organization: The Newspaper Rule

File organization newspaper metaphor

A well-organized file reads like a newspaper: the most important, high-level information comes first, and details get buried at the bottom. Readers should be able to scan the top of a file and understand its purpose without reading everything.

Standard file order:

// 1. External imports
import express from 'express';
import { db } from '../database';

// 2. Internal imports
import { validateUser } from './validators';

// 3. Constants
const MAX_SESSIONS = 5;
const SESSION_TTL_MS = 86400000;

// 4. Types / interfaces (TypeScript)
interface SessionOptions { ttl: number; }

// 5. Public functions (what callers use)
export function createSession(userId, opts) { ... }

// 6. Private helpers (implementation details)
function encodeSessionToken(payload) { ... }

The newspaper rule means public functions appear before the private helpers they call. This lets a reader understand what the module does before getting into how it does it.

Keep related code close together. If function A calls function B, function B should appear directly below A — not 200 lines later. The mental model is a call stack: top-level functions at the top, helpers immediately below the callers that use them.

Class method ordering follows the same principle: constructor first, public methods next, private methods last. Static methods that behave like utilities go at the bottom or in a separate utility file.

Consistent ordering within a team should be enforced by a linter or formatter rule so it's never a debate in code review.

Up next

How to avoid circular dependencies between modules

Sign in to track progress