Capstone A: the task model

Project A starts here, with the value the whole tracker is about. A task has an id, a title and a done flag, and the class that holds them is the only place where a task can be wrong: the constructor refuses an id that is not a positive integer, a title that is empty and a done flag that is not a boolean. Every other file of the project then trusts a Task to be valid.

The lesson builds the project folder, writes the model and runs a check program against it. The check prints three valid tasks, a copy with the done flag set, and the four errors that the constructor throws, so the output shows the class working and the class refusing.

The folder and the manifest

The folder is named tasks and holds a manifest, a lint config and a src folder. The manifest names the two scripts a reader types, and type says that every .js file is CommonJS, so require and module.exports are the shape of every module of the project.

mkdir tasks
cd tasks
mkdir src

The file package.json:

vi package.json

{ "name": "tasks", "version": "1.0.0", "description": "A task tracker that keeps its list in a JSON file", "type": "commonjs", "scripts": { "test": "node --test --test-reporter=dot", "lint": "eslint ." }, "devDependencies": { "@eslint/js": "^10.0.1", "eslint": "^10.14.0" } }

The test script runs every test file of the folder, and the dot reporter is the one the lesson on node:test introduced: one character per test and no duration. The lint script runs the flat config of the ESLint lesson, which the project keeps in the same folder.

The file eslint.config.js:

vi eslint.config.js

const js = require('@eslint/js'); module.exports = [ js.configs.recommended, { languageOptions: { ecmaVersion: 'latest', sourceType: 'commonjs', globals: { console: 'readonly', process: 'readonly', }, }, }, ];

The two names in globals are the ones the runtime gives and the language does not: console for the output and process for the arguments and the exit code. A third name that a file uses without declaring it is an error of the lint run, which is the point of the list.

The class and its three fields

The id is the position of the task in the list and the only stable name it has, so it is a positive integer. The title is the text a reader typed and is trimmed once, in the constructor, so no other file has to trim it again. The done flag is a boolean rather than a truthy value, because a file that was edited by hand can hold 'yes' and the class is the last moment at which that can be caught cheaply.

The class is a plain class from the lesson on classes, with a default parameter for done and two methods that do not change an instance. The fields are written on this and not declared as class fields, so the file stays the smallest version of the idea.

The file src/task.js:

vi src/task.js

const MAX_TITLE = 60; class TaskError extends Error { constructor(message) { super(message); this.name = 'TaskError'; } } class Task { constructor(id, title, done = false) { if (!Number.isInteger(id) || id < 1) { throw new TaskError('id must be a positive integer, got ' + id); } if (typeof title !== 'string' || title.trim() === '') { throw new TaskError('title must be a non-empty string'); } if (title.trim().length > MAX_TITLE) { throw new TaskError('title is longer than ' + MAX_TITLE + ' characters'); } if (typeof done !== 'boolean') { throw new TaskError('done must be a boolean, got ' + typeof done); } this.id = id; this.title = title.trim(); this.done = done; } complete() { return new Task(this.id, this.title, true); } toJSON() { return { id: this.id, title: this.title, done: this.done }; } static fromJSON(data) { return new Task(data.id, data.title, data.done); } } module.exports = { MAX_TITLE, Task, TaskError };

MAX_TITLE is exported as well as used, so a test can name the limit instead of writing the number 60 a second time. The four checks come before the three assignments on purpose: an object that does not pass them is never built, which is why every caller can read a field of a task without asking whether the field is there.

The errors of a bad task

TaskError extends Error and sets its own name, which the lesson on error classes explains. The class matters to the code around it: the command line of lesson 128 catches a TaskError and prints its message, while any other error keeps its stack and is a bug rather than a wrong call.

The check program builds two tasks, completes the first one, and then tries four tasks that the constructor has to refuse. Each refusal is caught and printed with its name and its message, so the output reads as a specification of the model.

The file check.js:

vi check.js

const { Task, TaskError } = require('./src/task'); const tasks = [new Task(1, 'write the model'), new Task(2, ' read the JSON file ')]; tasks.push(tasks[0].complete()); for (const task of tasks) { console.log(task.id + ' [' + (task.done ? 'x' : ' ') + '] ' + task.title); } console.log('the first task is unchanged: ' + tasks[0].done); console.log('the task as JSON: ' + JSON.stringify(tasks[1])); const bad = [ [0, 'no id'], [3, ' '], [4, 'x'.repeat(61)], [5, 'a title', 'yes'], ]; for (const [id, title, done] of bad) { try { const task = new Task(id, title, done); console.log('accepted ' + task.id); } catch (error) { if (!(error instanceof TaskError)) { throw error; } console.log(error.name + ': ' + error.message); } }

node check.js

1 [ ] write the model
2 [ ] read the JSON file
1 [x] write the model
the first task is unchanged: false
the task as JSON: {"id":2,"title":"read the JSON file","done":false}
TaskError: id must be a positive integer, got 0
TaskError: title must be a non-empty string
TaskError: title is longer than 60 characters
TaskError: done must be a boolean, got string

The two valid tasks keep the order of the list, the trimmed title lost its spaces, and the completed copy of the first task is a third entry with the flag set. The four refusals name the field and the value: positive integer, non-empty, 60 characters and boolean.

The message of the last one shows the type it received rather than the value, which is the useful half for a reader who wrote 'yes' in a file: the fix is a boolean, and the type is what the constructor compared.

A new task from an old one

complete returns a new task and does not set a field of the old one. That is one line longer than a setter and it pays for itself in the command that marks a task as done: the list is a new array with one new task in it, and the array that the caller passed in is untouched, so the save that follows cannot write a list that half the program has already changed.

The alternative, task.done = true, is not wrong; it is a decision about who owns the flag. With a copy, the owner is whoever holds the new value, and a function that returns a list is a function whose result can be compared with its input.

The check prints the flag of the first task after the copy was made, and it is still false. The lesson on pure functions is the same idea one level up: a function that returns a value instead of changing an argument can be tested with one call.

The JSON round trip

The list has to reach a file, and JSON writes plain objects rather than class instances. toJSON is the hook that JSON.stringify calls on its own, so a task is written as its three fields without a second conversion, and fromJSON is the other direction, written by hand because the constructor is the only way to make a valid task.

Task.fromJSON(JSON.parse(text)) therefore validates what the file holds, which is the reason it exists: a file edited by hand or written by an older version produces a message with the field at fault instead of an object with a missing field that fails three functions later.

The line of the output that starts the task as JSON is the result of JSON.stringify on a task, and it is the text that the next lesson writes into the task file.

Exercises

  1. Build a task with a title of exactly 60 characters and one of 61. Which one is accepted, and which comparison decides it?
  2. Pass undefined as the third argument and print the task. Which value does the default parameter give, and what would null do instead?
  3. Add a rename(title) method that returns a new task with another title. Which two lines of the check would show that the old task kept its title?
  4. Print String(new Task(1, 'x')). What does a class print without a toString, and which one line would change it?
  5. Call Task.fromJSON({ id: '1', title: 'x', done: false }). Which error comes out, and why is that better than an object with a string id?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Where does the model refuse a bad task?

    Answer

    In the constructor, before any field is set

    Every other file then trusts a Task instance, and the check happens once.

  2. What does this program print? class Task { constructor(id, title) { this.id = id; this.title = title; } } const task = new Task(2, "write"); console.log(task.id + 1, task.title.length);

    Answer

    3 5

    The id is a number, so the plus adds one, and the title has five characters.

  3. What does complete() return in this project?

    Answer

    A new task with the done flag set

    The old task keeps its flag, so a caller can compare the two versions.

  4. What does this program print? class TaskError extends Error {} const error = new TaskError("bad id"); console.log(error.message, error instanceof Error);

    Answer

    bad id true

    The message is the first argument and the subclass is an Error through the chain.

  5. Why does the class trim the title in the constructor?

    Answer

    So no other file has to trim it again

    One place decides what a title is, and every reader of the field gets the same value.

  6. What does this program print? const task = { id: 1, title: "a", done: false }; const back = JSON.parse(JSON.stringify(task)); console.log(back.done, typeof back.id);

    Answer

    false number

    JSON keeps the three fields and their types, and a boolean stays a boolean.

  7. What does JSON.stringify call on an object that has a toJSON method?

    Answer

    The method, and it writes what the method returns

    The hook lets a class decide its own written form, which is how a task becomes three fields.

  8. What does this program print? console.log(Number.isInteger(1.5), Number.isInteger(2));

    Answer

    false true

    The first number has a fraction and the second one does not.

  9. Why does the project keep MAX_TITLE instead of writing 60 twice?

    Answer

    The export lets a test name the limit without copying the number

    One value, one place: a test and the constructor read the same constant.

  10. What does this program print? function make(id) { if (id < 1) { throw new RangeError("small id"); } return id; } try { make(0); } catch (error) { console.log(error.name); }

    Answer

    RangeError

    The name of the error follows its class, and the message is the text inside it.

The programs on this page were run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image