01 / 05
Split files, borrow parts
INPUT · Slides
When one file gets fat
02 / 05
A look at an everything-file
Below, "a class for a product", "the product data" and "the work of listing them" all live in the same file. It is still on the short side, but can you see there are already three jobs mixed in?
class Item { constructor(name, price) { this.name = name; this.price = price; }}const items = [ new Item("pen", 120), new Item("notebook", 180),];for (let i = 0; i < items.length; i++) { console.log(items[i].name);}Result
pen notebook
03 / 05
The trouble comes when you fix it, not when you write it
A big file gets painful later, when you put your hands back in.
- to find the place you want to change, you read past code that has nothing to do with it
- you give something a similar name and carelessly write over an earlier definition
- there is work you want on another screen too, but the only way to take it is the whole file
Even the person who wrote it has forgotten after a week. The bigger the file, the longer remembering takes.
04 / 05
Cut by job, not by line count
So where should you cut? Not "cut once it goes over 100 lines" — the knack is to cut by job. The example above splits into three.
- data … the class for the product itself, and its contents
- calculation … work like getting a total
- display … work that puts it on the screen
Once you can cut it this way, all that is left is splitting the files. Split the files while it is all still mixed, on the other hand, and nothing gets easier to read.
05 / 05
First, try cutting inside one file
The writing that spans files comes in the next lesson. Before that, get hold of the feel of cutting by job.
There is only one thing to do: take work that is stuck in one lump and split it into functions and classes with meaningful names. If you can cut it to where reading the name suggests the contents, that is enough.
Right — let us start with cutting practice.