Split files, borrow parts

INPUT · Slides

When one file gets fat

01 / 05

You have been writing in one file all along

Every lesson so far finished inside a single file. While things are short that is by far the easiest way.

But start actually building an app and the same file piles up: ten functions, three classes... You end up with a file where you cannot tell what is where without reading it top to bottom.

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.