Two lines of code look smarter than ten. It's often the opposite: the two lines take the longest to read. Think of directions to your house. "Turn left at the mosque, third house, the green one" is more useful than GPS coordinates to eight decimal places. Both are right, but only one can be followed without a device. Short code full of tricks is like those GPS coordinates: it is right, but its reader has to know its tricks first to understand it.
The principle is called KISS (Keep It Simple, Stupid, which means "keep it simple"): pick the simplest solution that's correct. "Clever" code makes its author proud. Simple code makes its reader understand it fast.
The clever version and the plain version
Here are two ways to write the checkout function of Raka's T-Shirt Shop. First, the clever version, only two lines:
const calculateTotal = (c, v) =>
'Total: $' + (t => t + (t < 2e2) * 15)(c.reduce((s, i) => s + i.price * i.qty, 0) * (v === 'SAVE10' ? 0.9 : 1)).toFixed(2);
Before you read on, guess: if t is 189, what does the piece of code (t < 2e2) * 15 give? The answer is in the section "Reading the clever version".
Second, the plain version, which uses a loop:
const VOUCHER_DISCOUNT = 0.1;
const FREE_SHIPPING_MIN = 200;
const SHIPPING_FEE = 15;
function calculateTotal(cart, voucherCode) {
let total = 0;
for (const item of cart) {
total += item.price * item.qty;
}
if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
return 'Total: $' + total.toFixed(2);
}
Run both with the four carts in the first lesson's Lab. They give exactly the same results:
| Cart | Clever version | Plain version |
|---|---|---|
A + SAVE10 |
Total: $220.50 |
Total: $220.50 |
| A, no voucher | Total: $245.00 |
Total: $245.00 |
| C, no voucher | Total: $90.00 |
Total: $90.00 |
D + SAVE10 |
Total: $204.00 |
Total: $204.00 |
So the difference isn't the result, it's how many tricks the reader has to know.
Reading the clever version
To read the clever version, you have to know five things:
(t => ...)(...): an arrow function (a function written with=>) called right away, so the total after the voucher discount can be namedt.2e2is 200 (exponent notation: 2 × 10²).(t < 2e2) * 15: a boolean times a number.truecounts as 1 andfalseas 0, so it gives 15 or 0.* 0.9: the 10% discount written the other way round, as "pay 90%".reduce((s, i) => ...): a sum of the prices, with one-letter names.
With t = 189, 189 < 200 is true, and true * 15 = 15: shipping is added. The plain version only needs for...of and if, and you can read it in order, line by line.
You feel the difference when you look for a bug
The buyer with cart D asks why they paid for shipping. In the plain version, you just put a console.log between the steps:
console.log('subtotal:', total); // subtotal: 210
if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
console.log('after voucher:', total); // after voucher: 189
if (total < FREE_SHIPPING_MIN) total += SHIPPING_FEE;
console.log('after shipping:', total); // after shipping: 204
The answer is right there: after the discount the total is $189, below the $200 limit. In the clever version there's no place for a console.log between the steps, so you have to rewrite the code into the plain version first. Code that's hard to understand is also hard to test and debug (to find a bug and fix it). As a result, every change after it is slower.
Too many safeguards isn't simple either
The opposite of the clever version is a version that guards against every possible case. This code is the starting code of the exercise. The try/catch in this code is a block that catches errors so the program doesn't stop:
function isAdult(age) {
try {
if (age !== null && age !== undefined) {
if (typeof age === 'number') {
if (age >= 18) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} catch (e) {
return false;
}
}
All that code answers one question, whether age is at least 18. The comparison age >= 18 already gives true or false by itself:
function isAdult(age) {
return age >= 18;
}
if (x) { return true; } else { return false; }is the same asreturn x;.- A
try/catcharound a comparison catches nothing, becauseage >= 18never throws (stops the function with an error) whenageis a number. - For numbers the results are exactly the same:
isAdult(18)istrue,isAdult(17)false,isAdult(0)false,isAdult(65)true.nullandundefinedstill givefalsetoo. - One difference that matters:
isAdult('20'). The old version givesfalsebecause of thetypeofcheck. The new one givestrue, because'20' >= 18turns the text into a number. If the age can arrive as text from a form, writereturn typeof age === 'number' && age >= 18;, still one line. A refactor has to keep the results for the inputs that really come in.
Classes and design patterns (ways of arranging code that have a name) added "in case we need them later" are too many safeguards as well. For example, a VoucherFactory and a DiscountStrategy for the single voucher SAVE10. The companion principle is called YAGNI (You Aren't Gonna Need It). It means: add an abstraction once the need is there, for example when there are dozens of vouchers with different rules.
The exercise: isAdult
In the exercise, simplify isAdult(age) into one boolean expression. What gets graded:
- the three output lines stay
true,false,true(for 20, 17, 18); isAdult(18)istrue,isAdult(17)false,isAdult(0)false,isAdult(65)true;- there's no
try {orelseleft.
The function stays isAdult and its parameter stays age.
⚠️ Simple isn't about line count
- Thinking one line means simple. The clever version is only two lines, but it takes five tricks. The measure is how much the reader has to understand, not the number of lines.
- An
ifthat returnstrueorfalse. Return the condition directly:return age >= 18;. - A
try/catchthat swallows every error. Swallowing an error means catching it and then doing nothing with it. If the code inside can't throw, remove thetry/catch. If it can, swallowing the error silently hides bugs. - Removing a safeguard that turns out to be needed. Check what input really comes in first. If text can come in, keep the
typeofcheck, in one line. - Abstractions for a future that hasn't arrived. Classes, design patterns such as a factory, and settings (config) for a single case add things to understand and give nothing now.
TL;DR: KISS (Keep It Simple, Stupid) means choosing the simplest solution that's correct. The clever checkout function ((t < 2e2) * 15, * 0.9, an arrow function called right away) and the plain version with a loop give the same results on all four carts. But the clever one takes five tricks to read, and has no room for a console.log between its steps. Too many safeguards isn't simple either: an isAdult check (is the age at least 18?) with try, nested ifs (an if inside an if) and return true/false is just return age >= 18;. The results are the same for numbers (18 true, 17 false, 0 false, 65 true). Over-engineering (making code more complex than needed) makes code harder to understand, test and debug (find and fix bugs in), so development slows down. Add abstractions when they're needed (YAGNI, You Aren't Gonna Need It), and make sure a refactor still gives the same results for the inputs that really come in.
⚡ The clever version, two lines
Write:
const calculateTotal = (c, v) =>
'Total: $' + (t => t + (t < 2e2) * 15)(c.reduce((s, i) => s + i.price * i.qty, 0) * (v === 'SAVE10' ? 0.9 : 1)).toFixed(2);
Guess first: this is a checkout function written as short as possible. 2e2 is 200. If t is 189, what does the piece of code (t < 2e2) * 15 give?
It gives 15. 189 < 200 is true, and true counts as 1, so shipping is added. To read this clever version, you have to know five tricks.
Meaning: KISS (Keep It Simple, Stupid, which means "keep it simple"): pick the simplest solution that's correct. This clever version and the plain version with a loop give the same results on all four carts. The difference is how many tricks the reader has to know.
⚡ The plain version has room for console.log
Write:
console.log('subtotal:', total); // subtotal: 210
if (voucherCode === 'SAVE10') total -= total * VOUCHER_DISCOUNT;
console.log('after voucher:', total); // after voucher: 189
Meaning: This is part of the plain version, with a console.log between its steps. The buyer with cart D (an order of $210) asks why they paid for shipping. The answer is right there: after the discount the total is $189, below the $200 free-shipping minimum. The clever version has no place for a console.log between its steps, so it's harder to test and debug (to find a bug and fix it).
⚡ Too many safeguards isn't simple either
Write:
function isAdult(age) {
return age >= 18;
}
Meaning: The function isAdult checks whether an age (age) is at least 18. Its old version was wrapped in a try/catch (a block that catches errors), with checks for null and typeof and nested if/else (an if inside an if). But if (x) { return true; } else { return false; } is the same as return x;, and a try/catch around a comparison catches nothing, because comparing numbers never causes an error. For numbers the results are exactly the same: 18 true, 17 false, 0 false, 65 true.