Why split a project into layers?
Data, logic and interface kept apart. For the tests, for swapping the API, and for your own nerves.
fetch, rounded the degrees, drew HTML and wrote to localStorage. Then the weather service shut down, and I had to rewrite… everything. Even the rounding. What did the rounding ever do to anyone?Almost any app with an interface splits into three layers:
- data — where it comes from: the network, localStorage, a file (
api.js,storage.js); - logic — what to do with it: round, sort, decide what to show (
format.js,search); - interface — how to show it to a person and what they pressed (
ui.js, the handlers inmain.js).
There's one rule: each layer knows as little as possible about the others. format.js doesn't know about document, ui.js doesn't call fetch, api.js doesn't touch the DOM.
Why it pays off.
1. Testability. formatTemp(6.6) is checked with no browser, network or page — in a microsecond. A function that calls fetch and writes to the DOM inside can only be checked as a whole, with a fake server and a page, and it's unclear which of the three parts broke.
2. Replacement. The weather service changed — only api.js changes, as long as it returns an object of the same shape. That's the contract between layers: "getWeather(city) returns { city, temp, sky, wind } or throws an Error with a clear message".
3. Clarity. Hunting a bug with the degrees — open format.js. Nothing loads — api.js. Each file answers one question.
// Two data sources, one contract: city → { city, temp }
const fromServer = async (city) => ({ city, temp: 6.6 });
const fromCache = async (city) => ({ city, temp: 5 });
// The logic knows nothing about the source
const label = (w) => `${w.city}: ${Math.round(w.temp)}°`;
// The "interface" — here it's just console.log
async function show(load, city) {
console.log(label(await load(city)));
}
await show(fromServer, "Oslo");
await show(fromCache, "Oslo");label and show didn't even notice.Look at where the arrows point: main.js imports everyone, ui.js imports only format.js, and format.js imports nobody. Dependencies point inward, toward the simplest and most stable parts. The pure functions in the middle almost never change; the network and the interface at the edges change all the time.
You'll meet the same idea everywhere under different names: MVC, "clean architecture", "containers and presentational components" in React, "business logic separate from the framework". The names change, the point is the same: things that change for different reasons live in different places.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.