Writing Maintainable & Scalable Code Architecture
Published by Brayan K
Code architecture is the way you organize and structure a JavaScript application — its files, modules, and layers — so the codebase stays easy to understand, change, and grow as the project scales.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Place a changing boundary where callers can see its contract
A task-renaming button should express an intent: rename this task. It should not also choose a storage key, decode every server response and decide conflict policy. Separate the input adapter, the application operation and the persistence adapter when those responsibilities change for different reasons. The boundary is a behavior contract, not a target number of files.
function normalizeName(raw) {
// The domain rule works without a DOM, network or storage dependency.
if (typeof raw !== "string" || raw.trim().length === 0)
throw new TypeError("name must not be blank");
return raw.trim();
}
function createRename(writeName) {
// Composition chooses the dependency; the operation chooses the rule.
return (id, raw) => writeName(id, normalizeName(raw));
}
const calls = [];
const rename = createRename((id, name) => { calls.push([id, name]); return "saved"; });
console.log(rename("task-a", " Draft "));
console.log(JSON.stringify(calls));
// ✅ Expected output:
// saved
// [["task-a","Draft"]]This small example is synchronous by contract. A real persistence adapter may be asynchronous; its caller must then await completion before displaying success. Architecture does not remove latency or failures. Async/Await Architecture & Best Practices owns asynchronous coordination.
A folder name does not enforce dependency direction
A module called domain can still import the DOM or a concrete HTTP client. Look at what imports what and where effects occur. An inward dependency direction keeps core rules independent of browser and server details; a composition root supplies concrete adapters at startup. This is useful when those details vary, not a requirement to create layers around every two-line function.
const createReader = load => id => load(id);
const local = createReader(id => ({ id, source: "memory" }));
const fixture = createReader(id => ({ id, source: "fixture" }));
console.log(local("a").source, fixture("a").source);
// ✅ Expected output:
// memory fixtureFeature folders can keep code that changes together nearby. Layer folders can make technical boundaries obvious. Neither layout proves maintainability, throughput or team scalability. Prefer a structure that makes the current change paths and ownership visible. JavaScript Modules: ES6 Imports, Exports, Bundling owns actual import/export behavior; JavaScript Design Patterns (Factory, Singleton, Strategy, etc.) owns scoped factories and adapters.
let activePrefix = "A";
const hidden = name => activePrefix + ":" + name;
const explicit = (prefix, name) => prefix + ":" + name;
console.log(hidden("task"), explicit("A", "task"));
activePrefix = "B";
console.log(hidden("task"), explicit("A", "task"));
// ✅ Expected output:
// A:task A:task
// B:task A:taskAn import cycle can make initialization order surprising; an overloaded shared utilities module can become a dependency hub. Do not solve either by moving all state into a global singleton. Map the real dependencies, then move the smallest policy or interface that breaks the unwanted coupling.
Validate at boundaries and return data the caller can interpret
const calls = [];
function rename(raw) {
if (typeof raw !== "string" || raw.trim() === "")
throw new TypeError("name must not be blank");
calls.push(raw.trim());
}
try { rename(" "); }
catch (error) { console.log(error.name, error.message); }
console.log(calls.length);
// ✅ Expected output:
// TypeError name must not be blank
// 0Input validation and authorization are different responsibilities. A valid task key does not prove a user may edit it. The server must enforce access control; browser-side checks improve feedback but cannot provide that trust boundary. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns that distinction.
async function getName(load) {
const result = await load();
if (result === null || typeof result !== "object" || typeof result.name !== "string")
throw new TypeError("repository must return a named record");
return result.name;
}
try { await getName(async () => ({ name: 7 })); }
catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// TypeError repository must return a named recordSelect fields instead of forwarding an entire external response throughout the application. That prevents a transport rename or extra private field from silently becoming part of every caller’s contract. Deep Dive into JSON, Parsing & Serialization owns parsing and schema validation details.
const internal = { id: "a", name: "Draft", token: "private" };
function publicTask(row) { return { id: row.id, name: row.name }; }
const view = publicTask(internal);
view.name = "Changed";
console.log(Object.keys(view).join(","), internal.name);
// ✅ Expected output:
// id,name DraftA test double is useful only for the contract it implements
const failure = new Error("storage unavailable");
const createReader = load => async id => load(id);
const read = createReader(async () => { throw failure; });
try { await read("a"); }
catch (error) { console.log(error === failure); }
// ✅ Expected output:
// trueA memory repository can test application branching, selected fields and error propagation. It does not prove SQL transactions, network authorization, rate limits or durability. Contract checks should also run against the real adapter where practical. Do not describe a passing memory fixture as an integration test of a hosted backend.
const stored = { id: "a", tags: ["draft"] };
const read = () => ({ ...stored });
const task = read();
task.tags.push("changed");
console.log(stored.tags.join(","));
// ✅ Expected output:
// draft,changedState exactly what values an adapter owns or copies. Deep Copy vs Shallow Copy & Data Structures owns deep-copy semantics. The brief uses only primitive task fields, and its adapter returns a new selected record on every read.
Concurrency exposes a missing write contract
let stored = { name: "Draft", count: 0 };
async function increment() {
const snapshot = { ...stored };
await Promise.resolve();
stored = { ...snapshot, count: snapshot.count + 1 };
}
await Promise.all([increment(), increment()]);
console.log(stored.count);
// ✅ Expected output:
// 1Both operations read the same state before either writes. Awaiting each operation internally does not serialize independent callers. A revision-aware compare-and-swap contract can reject stale writes; the real repository must check the revision and commit atomically. A separate read followed by an unconditional server write does not implement that contract.
function memoryRepository(seed) {
const rows = new Map(seed.map(row => [row.id, { ...row }]));
return {
async read(id) {
const row = rows.get(id);
return row ? { ...row } : null;
},
async compareAndSwap(id, revision, name) {
// No await between this check and write in this single-threaded fixture.
const row = rows.get(id);
if (!row || row.revision !== revision) return false;
rows.set(id, { id, name, revision: revision + 1 });
return true;
}
};
}
const store = memoryRepository([{ id: "a", name: "Draft", revision: 0 }]);
const first = await store.read("a"), second = await store.read("a");
console.log(await store.compareAndSwap("a", first.revision, "First"));
console.log(await store.compareAndSwap("a", second.revision, "Second"));
console.log(JSON.stringify(await store.read("a")));
// ✅ Expected output:
// true
// false
// {"id":"a","name":"First","revision":1}This fixture’s check and write run without an await in one JavaScript turn. It is not a distributed transaction. A conflict should reach a caller that can refresh or ask the user to reconcile changes; automatically retrying a stale human edit can overwrite another person’s intent.
Guided exercise: make no-change behavior explicit
Complete the literal hints. Returning unchanged must avoid a needless write; changed input is trimmed before it reaches the dependency.
const writes = [];
function rename(current, raw) {
const name = raw.___(); // 👉 replace ___ with trim
if (name === current.name) return "___"; // 👉 replace ___ with unchanged
writes.___(name); // 👉 replace ___ with push
return "renamed";
}
console.log(rename({ name: "Draft" }, " Draft "));
console.log(rename({ name: "Draft" }, " Final "), writes.join(","));
// ✅ Expected output:
// unchanged
// renamed FinalIndependent brief: rename through a conditional repository boundary
Implement createRenameTask with read and compareAndSwap dependencies. Validate callable dependencies at construction. A rename accepts a lowercase ASCII task key beginning with a letter (up to 32 characters, letters/digits/hyphens) and a trimmed name of 1 through 40 UTF-16 code units. Reject invalid intent before reading.
Read returns null or a record with the requested id, a string name and a nonnegative safe-integer revision. Return missing for null; return unchanged with a fresh selected snapshot when the name is already equal. Otherwise reject revision overflow, then call compareAndSwap(id, oldRevision, newName) exactly once. It must atomically commit at that revision and return a boolean. Return conflict for false and renamed with the next revision for true. Preserve dependency failures. Do not add retries, authentication, a DOM or network access.
function createRenameTask({ read, compareAndSwap }) {
if (typeof read !== "function" || typeof compareAndSwap !== "function")
throw new TypeError("read and compareAndSwap must be functions");
return async function renameTask(id, name) {
if (typeof id !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(id))
throw new TypeError("id must be a lowercase task key");
if (typeof name !== "string" || name.trim().length < 1 || name.trim().length > 40)
throw new TypeError("name must contain 1..40 trimmed characters");
const selectedName = name.trim();
const current = await read(id);
if (current === null) return { kind: "missing" };
if (current === null || typeof current !== "object" || current.id !== id ||
typeof current.name !== "string" ||
!Number.isSafeInteger(current.revision) || current.revision < 0)
throw new TypeError("repository returned an invalid task");
if (current.name === selectedName) return { kind: "unchanged", task: { id, name: current.name, revision: current.revision } };
if (current.revision === Number.MAX_SAFE_INTEGER)
throw new RangeError("revision cannot be incremented safely");
const committed = await compareAndSwap(id, current.revision, selectedName);
if (typeof committed !== "boolean") throw new TypeError("compareAndSwap must return a boolean");
if (!committed) return { kind: "conflict" };
return { kind: "renamed", task: { id, name: selectedName, revision: current.revision + 1 } };
};
}
function memoryRepository(seed) {
const rows = new Map(seed.map(row => [row.id, { ...row }]));
return {
async read(id) {
const row = rows.get(id);
return row ? { ...row } : null;
},
async compareAndSwap(id, revision, name) {
// No await between this check and write in this single-threaded fixture.
const row = rows.get(id);
if (!row || row.revision !== revision) return false;
rows.set(id, { id, name, revision: revision + 1 });
return true;
}
};
}
const store = memoryRepository([{ id: "task-a", name: "Draft", revision: 0 }]);
const rename = createRenameTask(store);
console.log((await rename("missing", "New")).kind);
console.log((await rename("task-a", " Draft ")).kind);
const results = await Promise.all([rename("task-a", "First"), rename("task-a", "Second")]);
console.log(results.map(result => result.kind).join(","));
console.log(JSON.stringify(await store.read("task-a")));
let reads = 0;
const guarded = createRenameTask({ read: async () => { reads++; return null; }, compareAndSwap: async () => true });
try { await guarded("Bad Key", "New"); }
catch (error) { console.log(error.name, reads); }
const reason = { unavailable: true };
const failing = createRenameTask({ read: async () => { throw reason; }, compareAndSwap: async () => true });
try { await failing("task-a", "New"); }
catch (error) { console.log(error === reason); }
// ✅ Expected output:
// missing
// unchanged
// renamed,conflict
// {"id":"task-a","name":"First","revision":1}
// TypeError 0
// true
Practice quiz
What does this complete program print? const normalize=x=>x.trim();const write=(id,name)=>[id,name];console.log(JSON.stringify(write("a",normalize(" Draft "))));
- ["a","Draft"]
- ["a"," Draft "]
- ["Draft","a"]
- undefined
Answer: ["a","Draft"]. The input adapter normalizes before the persistence boundary.
What does this complete program print? let prefix="A";const hidden=x=>prefix+x;prefix="B";console.log(hidden("x"));
- Ax
- Bx
- x
- undefined
Answer: Bx. The closure still reads mutable external configuration.
What does this complete program print? const calls=[];function work(text){if(text.trim()==="")throw Error("blank");calls.push(text)}try{work(" ")}catch{}console.log(calls.length);
- 1
- 2
- 0
- undefined
Answer: 0. Validation prevents the dependency effect.
What does this complete program print? const row={name:"Draft",tags:["a"]};const copy={...row};copy.tags.push("b");console.log(row.tags.length);
- 1
- 0
- undefined
- 2
Answer: 2. The nested array is still shared after a shallow copy.
What does this complete program print? let value=0;async function increment(){const old=value;await Promise.resolve();value=old+1}await Promise.all([increment(),increment()]);console.log(value);
- 1
- 2
- 0
- undefined
Answer: 1. Both invocations read zero before either writes.
What does this complete program print? let revision=2;function write(expected){if(expected!==revision)return false;revision++;return true}console.log(write(2),write(2));
- true true
- true false
- false true
- false false
Answer: true false. The first successful write makes the second expected revision stale.
What does this complete program print? const error={offline:true};async function load(){throw error}try{await load()}catch(reason){console.log(reason===error)}
- false
- undefined
- true
- TypeError
Answer: true. The original dependency reason can be preserved exactly.
What does this complete program print? const row={id:"a",name:"Draft",secret:"omit"};const view={id:row.id,name:row.name};console.log(Object.hasOwn(view,"secret"),view===row);
- true true
- true false
- false true
- false false
Answer: false false. Selecting fields creates a separate public record without the secret field.
Continue this course
- Previous: JavaScript Design Patterns (Factory, Singleton, Strategy, etc.)
- Next: Deep Dive into JSON, Parsing & Serialization — Parse, validate, transform, and safely serialise complex JSON data
- Quick reference: JavaScript cheat sheet