Which patterns prevent bugs in JavaScript code?
Four patterns do most of the work, and every one of them moves the checks to the right place.
Guard clauses. Check the arguments at the top of the function and leave early when something is wrong. That way the body of the function only ever works with good data. The alternative is to wrap the whole body inside a conditional, which pushes the real code one level deeper for no benefit at all.
Default values for everything that is optional. A default value turns a missing argument into a known value at the boundary, so the rest of the function never has to think about the empty case.
Immutable updates. Building a new value instead of changing an existing one means the old value is still correct afterwards. That is what makes undo, time travel, and change detection possible, and it removes a whole family of bugs where two parts of the program share the same object by accident.
Frozen shared configuration. When several parts of the program read the same settings object, freezing it turns an accidental change into an immediate error in strict mode instead of a strange value that shows up three functions later.
// 1. Guard clauses at the top of a function.
function parsePort(value) {
if (typeof value !== 'number') {
throw new TypeError('port must be a number');
}
if (!Number.isInteger(value) || value < 1 || value > 65535) {
throw new RangeError('port must be between 1 and 65535');
}
return value;
}
// 2. Provide defaults for anything optional.
function connect(host, port, timeout) {
if (port === undefined) { port = 5432; }
if (timeout === undefined) { timeout = 5000; }
return { host: host, port: port, timeout: timeout };
}
// 3. Freeze shared configuration so it cannot be edited by accident.
const settings = Object.freeze({ theme: 'dark', locale: 'en-GB' });
// 4. Prefer immutable updates.
function addItem(list, item) {
return list.concat([item]);
}
console.log(parsePort(5432)); // 5432
console.log(connect('db.local')); // { host: 'db.local', port: 5432, timeout: 5000 }
console.log(Object.isFrozen(settings)); // true
console.log(addItem([1, 2], 3)); // [1, 2, 3]
Two more patterns are worth mentioning. Validating at the boundary of a system, once, means that the rest of the code can trust its inputs. And keeping the shape of your data simple, with the same property names used everywhere in the code base, removes the whole class of bug where two functions disagree about what a property is called. The earlier question in this topic covered freezing objects in more detail, and the next question shows how to check one argument properly.