When to use classes, and when functions and objects are enough
Learn when a class is worth it: a function for an answer worked out from its arguments, a plain object for data you read and save, and a class for data kept between calls under rules. Then see why TaskKit’s tasks stay plain objects.
Fundamentals
TypeScript
When to use classes, and when functions and objects are enough. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Two lessons ago TaskKit got its first class, and now TaskStore keeps
its tasks behind #tasks. Open tasks.ts next to store.ts, though,
and you find no class at all: capitalize, percentFull and
tasksToJson are plain functions, and Task is an interface, so each
task is an object written with braces. Having just learned classes,
you may want to turn all of them into classes too. Should you?
Think of three things from your day. A calculator works out 2 + 5
from the keys you press, and needs nothing from yesterday's sums. A
receipt holds what you bought: you read it, file it or take a photo of
it, and nobody guards what is written on it. A bank keeps your money
from one visit to the next, and lets it out only by its rules. Nobody
builds a bank to add two numbers, and nobody locks a receipt behind a
counter. Code comes in the same three shapes. By the end of this lesson
you can say which shape any part of TaskKit should have, and why a task
has to stay a plain object.
Three shapes for code
You have written all three. A function (lesson 5.1) takes values,
works out an answer and gives it back. A plain object is an object
of named values, written with { … } (lesson 6.1) or built by
JSON.parse from JSON (JavaScript Object Notation, data written as
text; lesson 12.1), never by a class with new. A class
(lesson 13.1) builds objects that keep their data, together with the
methods that change it. Here is one of each from TaskKit:
percentFull(2, 5); // 40percentFull(2, 5); // 40
A function: percentFull
Does: Works out an answer from what it is given
Never: Keeps nothing once it has answered
A plain object: one Task
Does: Holds values to read, print and save
Never: Has no rules about how they change
A class: TaskStore
Does: Keeps its tasks from one call to the next
Never: Lets nothing change them but its own methods
A function answers, a plain object holds, a class keeps and guards
Which shape a piece of code should have comes down to two questions:
what does it keep, and must rules guard it? The next three sections
take one shape each.
A function: an answer from what it is given
Everything percentFull needs comes in through its parameters, and
once it has answered, its card comes off the call stack together with
its boxes (lesson 5.8): nothing of the call is left. That is what you
want from code that works something out. One call shows everything it
does, so it is easy to test, and it needs nothing but its arguments,
so any file can use it.
Bad — a class with nothing to keep:
every call builds an empty object just to reach one method.
Good — a function: it takes the
numbers and gives back the answer.
Both print 40 and 80. Format has no properties, so this never
holds anything, and every file that wants a percentage has to write
new Format() first. Someone reading the class looks for the data it
keeps and finds none. A class with methods and no properties is a
sign that its methods want to be functions. That is why tasks.ts,
a file of answers worked out from what they are given, holds no
class.
A class: data kept between calls, with rules
Now the opposite job. A task list has to remember what was added, so
that the next add can refuse a title it already holds. Here is the
same call made twice to a function, and twice to an object. Press
Next step to walk through it, or let it play:
Yourcode
percentFull
home
1
Your code to percentFull: percentFull(2,5)
2
All 8 steps shown.Step 1 of 8: Your code → percentFull — percentFull(2, 5)Step 2 of 8: percentFull → Your code — 40Step 3 of 8: Your code → percentFull — percentFull(2, 5)Step 4 of 8: percentFull → Your code — 40Step 5 of 8: Your code → home — home.add("buy milk")Step 6 of 8: home → Your code — "Added: buy milk"Step 7 of 8: Your code → home — home.add("buy milk")Step 8 of 8: home → Your code — "Already on the list"
All 8 steps shown.
The same call gives two answers, because home keeps its list
between calls and add reads it before it changes it. Here is
home's class. Run it:
It prints Added: buy milk, Added: call Mom and
Already on the list. A list that lives between calls has to live
somewhere, and you have seen three places for it:
A box outside every function. A titles list at the top of the
file, and an add function that pushes onto it. It works, but any
line of the file can change titles without going through add,
just as any line could reach store.tasks before lesson 13.2 made it
#tasks. And the file can only ever have that one list.
A function that keeps a box, a closure (lesson 5.5).
makeNumbering keeps count between calls, and no other code can
reach it. For one job, numbering tasks, that is all it takes, with no
class.
A class. When several jobs share one set of data, the class
keeps them in one place. TaskStore's add, count, list,
load and save all work on the same #tasks, under the same
rules, and every new TaskStore(5) builds another store with tasks
of its own.
So a class earns its place when it keeps data from one call to the
next, and rules must guard how that data changes.
A plain object: data to read, print and save
The third shape is the simplest, and every task TaskKit holds is one.
Task is an interface in tasks.ts (lessons 6.5 and 9.1), and each
task is a plain object: { id: 1, title: "Buy milk", status: "todo" }. A task needs no method to guard it. Its one rule is that its id
never changes, and the interface already keeps that rule with
readonly (lesson 6.2). printList reads tasks, tasksToJson writes
them out, and the rules about adding one live in TaskStore, which
holds them all. The work on a task is done by functions that take it,
so the task itself stays data. Command in command.ts is the same:
readCommand builds one from what you typed, and the switch in
index.ts reads its kind (lesson 7.5).
A task has a second reason to stay plain. It does not stay in memory:
save writes it to tasks.json, and the next run's load builds it
again from that text. Decide below what JSON.stringify writes for an
object built by a class.
Predict before you run
This Task is a class, with a method that says whether the task is
done. What does JSON.stringify write for one?
Predict
What does this program print?
The common mistake: a class for data from JSON
TaskKit already has the place where this mistake would happen:
tasksFromJson in tasks.ts is return JSON.parse(text);, typed to
give back Task[]. Say you made Task a class with a method, so that
any code could ask a task whether it is done:
Common mistake
Calling a method on an object made by JSON.parse
TypeScript finds nothing wrong: JSON.parse returns any
(lesson 12.1), so TypeScript believes the type you wrote, Task.
Node then runs line 17 and stops. JSON.parse built loaded from
text, as a plain object with a title and a status. It never called
the class, so loaded instanceof Task is false, and there is no
isDone to call.
TypeError: loaded.isDone is not a function
The fix
Keep the data plain: describe it with an interface, and do the work
in a function that takes it.
It prints false: the task is still to do.
When … is not a function names a value that came from a file or
from the web, you called a method the data never had: data that
travels as text keeps only its values.
TaskKit, sorted by shape
Ask the two questions of TaskKit's main parts, and each one already
has the right shape:
Part
Shape
Why
capitalize, percentFull
Function
Works out an answer
tasksToJson, tasksFromJson
Function
Turns data into other data
printList, printSummary
Function
Prints what it is given
readCommand
Function
Reads what you typed
Task
Plain object
Data to read, print and save
Command
Plain object
Data to read once and act on
TaskStore
Class
Keeps the tasks, guards their rules
Nothing in TaskKit changes in this lesson. The one part with data to
keep and rules to guard became a class in the last two lessons;
everything else stays what it was.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser: two questions about which shape
fits, a class to turn into a function, and functions that share one
list to turn into a class.
Recap
Recap · 3 questions
Check yourself
Why does each TaskKit task stay a plain object?
Check yourself
One job must keep one number between calls, out of reach of
other code. What is enough?
Check yourself
When is a class worth writing?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
When to use classes, and when functions and objects are enough
What things are
Word
What it means
Function
Works out an answer from its arguments
Plain object
Named values, written with { … }, not built by new
Class
Builds objects that keep data, with the methods that change it
Which shape
When the code
Use
Keeps nothing between calls
A function, like percentFull
Holds values to read, print or save
A plain object with an interface
Keeps data that rules must guard
A class, its data in # names
Keeps one box for one job
A closure: a function that keeps a box (5.5)
When it breaks
Sign
What it means
… is not a function
A method called on data from JSON
instanceof is false
JSON.parse never builds a class's object
A class with no properties
Its methods want to be functions
Module 13 on one page
Cheat sheet
Module 13: Classes: The Basics
13.1 Classes: properties, constructors, and methods
Code or rule
What it means
class TaskList { … }
Write a blueprint called TaskList
constructor(name: string)
Take what new passes in
this.name = name;
Put the parameter into the object
new TaskList("Home")
Build one object from the class
home.add("buy milk")
Run a method on home
TS2564
The constructor leaves a property without a value
13.2 private, #private, and readonly
Code or rule
What it means
private titles: string[]
Make a property private to the check
#titles: string[] = [];
Make a property private to JavaScript
readonly limit: number;
Let anyone read it, nobody change it
[...this.#titles]
Hand out a copy, never the list itself
# over private
For code run with no check, like npm start
13.3 When to use classes, and when functions and objects are
enough
Code or rule
What it means
Keeps nothing between calls
A function, like percentFull
Holds values to read, print or save
A plain object with an interface
Keeps data that rules must guard
A class, its data in # names
Where to go next
You can now look at a piece of code and choose its shape: a function
when it keeps nothing, a plain object when it keeps values with no
rules, and a class when it keeps data that rules must guard. That
closes Module 13: TaskKit's tasks live in a TaskStore, and the rest
of TaskKit stays functions and plain objects, as it should.
Next is Why libraries exist, and how to choose one: popularity,
maintenance, built-in types or @types, the first lesson of Module
14, where you learn how to tell a package worth installing from one
that is not, before TaskKit gets its next ones.
Before you move on, open TaskKit's index.ts and find messageOf.
Ask it the two questions: what does it keep, and must rules guard it?
Then say in one sentence why it is a function.
percentFull to Your code: 40
3
Your code to percentFull: percentFull(2,5)
4
percentFull to Your code: 40
5
Your code to home: home.add("buymilk")
6
home to Your code: "Added:buymilk"
7
Your code to home: home.add("buymilk")
8
home to Your code: "Alreadyonthelist"
percentFull answers from what it is given; home answers from
what it keeps
Keeps one box for one job
A closure: a function that keeps a box (5.5)
… is not a function
A method called on data from JSON
Exercise · Read the code
Which one needs a class
A kitchen app has three parts. Which one is worth a class?
Exercise · Read the code
Should askTitles be a class
This is askTitles, from TaskKit's ask.ts (lesson 12.3). It puts a
reader and a list of titles in boxes. Should it become a class?
DueLabel keeps nothing, so every call builds an empty object. Replace
the class with a function, dueLabel(due), that gives back the same
text, and call it instead, so the program still prints Friday and
not set.
Loading the editor…
Exercise · Write the code
One list, several jobs
Here the list lives in a box any line can change, and the program can
only ever have one list. Turn it into a class TaskList that keeps
its list in #titles, with two methods: add, which does what
addTitle does, and count, which does what countTitles does. Then
build home with new TaskList() and use it in the last five lines,
so the program prints Added: buy milk, Added: call Mom,
Added: pay rent, The list is full and 3.
Loading the editor…
ask.tsts
export async function askTitles(): Promise<string[]> { const reader = createInterface({ input: process.stdin, output: process.stdout, }); const titles: string[] = []; let answer = await reader.question("Task to add: "); while (answer.trim() !== "") { titles.push(answer); answer = await reader.question("Task to add: "); } reader.close(); return titles;}