"The code is ugly, it needs tidying" rarely convinces a shop owner. By the end of this lesson you can say it in numbers: how many minutes the tidy-up takes, how many extra minutes each change costs while the code is left as it is, and when the tidy-up starts earning its time back.
What you're counting is technical debt: a shortcut in the code that saves time now but makes every later change more expensive until the shortcut is cleaned up. It's like buying a phone on a pay-later plan. You hold the phone today, but as long as the debt isn't paid off, interest comes every month. In code, the phone you hold today is a feature that is released on time. The interest is the extra minutes you pay every time you touch that code.
A shortcut for the 12.12 sale
A week before the 12.12 sale, Raka asks for the receipt and the confirmation email to show how much the buyer saved. To finish on time, the discount is computed again in two new places, without reading the VOUCHERS table from the Refactoring Techniques lesson:
const VOUCHERS = { SAVE10: 0.1 };
function applyVoucher(amount, voucherCode) { // place 1
return amount - amount * (Object.hasOwn(VOUCHERS, voucherCode) ? VOUCHERS[voucherCode] : 0);
}
// TD-01: copied for the 12.12 sale, listed in the debt register
function savingLine(subtotal, voucherCode) { // place 2
const rate = voucherCode === 'SAVE10' ? 0.1 : 0;
return 'Saved: ' + formatPrice(subtotal * rate);
}
function emailLine(email, subtotal, voucherCode) { // place 3
const rate = voucherCode === 'SAVE10' ? 0.1 : 0;
return email + ': you saved ' + formatPrice(subtotal * rate);
}
Only applyVoucher, which computes the total, reads VOUCHERS. savingLine (the savings line on the receipt) and emailLine (the email) write the rate themselves: 0.1 if the voucher code is SAVE10, otherwise 0. The TD-01 comment is this debt's number in the debt register, which comes later in this lesson.
The feature is released on time and all four carts stay OK. That is the benefit of the debt. But the voucher rate is now written in three places.
Then PR #14 from the Code Review Checklist lesson adds SAVE20, but only to VOUCHERS. Here are the checks for cart A with SAVE20:
OK Total: $211.00
DIFF Saved: $0.00, expected Saved: $49.00
DIFF [email protected]: you saved $0.00, expected [email protected]: you saved $49.00
The total is right, because applyVoucher reads VOUCHERS. But the receipt and the email tell the buyer they saved nothing, because savingLine and emailLine only know SAVE10. That is the interest: every time a voucher changes, you have to remember three places, not one.
Principal and interest
The term comes from Ward Cunningham, in his experience report on the WyCash system (OOPSLA conference, 1992). He said that releasing not-quite-right code is like going into debt, and "every minute spent on not-quite-right code counts as interest on that debt". So a debt has two numbers:
- Principal: the cost of paying the debt off. For TD-01: write one function
discountForthat readsVOUCHERS, use it in all three places, then run the checks. Raka's team estimates 60 minutes. - Interest: the extra cost every time that code is touched. The team estimates 10 minutes per place to find, change and check it. Now one voucher change touches 3 places (30 minutes). Once the debt is paid off, 1 place is enough (10 minutes). The difference, 20 minutes per change, is the interest.
Interest is only paid when the code is touched. Ugly code that never changes charges no interest.
Interest is counted, not felt
The principal is 60 minutes, the interest 20 minutes per change. Guess first: after how many voucher changes has paying off TD-01 earned its time back? 1, 3, or 10? This table shows the total minutes for a number of voucher changes ahead, if you leave the debt and if you pay it off first:
| Voucher changes | Leave it (30 per change) | Pay it off first (60 + 10 per change) |
|---|---|---|
| 1 | 30 | 70 |
| 2 | 60 | 80 |
| 3 | 90 | 90 |
| 4 | 120 | 100 |
| 6 | 180 | 120 |
It breaks even at the third change: both ways cost 90 minutes. From the fourth change on, paying it off is cheaper. The formula is principal divided by interest, 60 ÷ 20 = 3. Raka's vouchers change about twice a month (the team's estimate), so the payoff earns its time back within two months. Numbers like these are what you bring to Raka, not "the code is ugly".
The debt register
Debt that isn't written down never gets paid, because nobody remembers it. So the team writes it in a debt register, one row per debt. Raka's checkout debt register:
| ID | Debt | Interest | Principal | Decision |
|---|---|---|---|---|
| TD-01 | Voucher rate in 3 places | +20 minutes per voucher change, about twice a month | 60 minutes | Pay now |
| TD-02 | No test cart at exactly $200 | a wrong <= is not caught whenever the shipping rule changes |
5 minutes | Pay on the way |
| TD-03 | The old calc(k, v) in the yearly report script |
0, never changed | 90 minutes | Leave it, keep it listed |
- The same ID goes in a comment in the code (
// TD-01), so whoever reads the code can find its entry. - Keep the register where the team works: an issue tracker (an app where a team records tasks and problems) with a
tech-debtlabel, or aDEBT.mdfile in the repo (the project's code folder, kept in git). - TD-03 is ugly, but its interest is zero. Paying it off just spends 90 minutes that never come back.
What is not debt: a bug (the result is wrong, fix it now) and a feature not built yet (that goes in the backlog, the list of work waiting to be done).
Deliberate or unaware
Martin Fowler (article "Technical Debt Quadrant", 2009) sorts debt with two questions. First, did the team know it was taking on debt (deliberate) or not (inadvertent)? Second, was the debt taken carefully (prudent) or carelessly (reckless)?
- Deliberate: the team knows it is taking a shortcut. TD-01 is one: the rate was copied knowingly for the 12.12 sale, written down, with a plan to pay it. So TD-01 is deliberate and prudent.
- Inadvertent: the debt happens without anyone noticing, because nobody knew a better way yet. For example, a developer who doesn't know
?? 0orObject.hasOwnyet writesamount * VOUCHERS[voucherCode](and getsNaNwithout a voucher). They are in debt without knowing it, and only find out after learning more.
Deliberate debt is easier to manage, because it can be written down the moment it is taken.
Pay on the way: the Boy Scout Rule
Robert C. Martin, in Clean Code (2008), borrows the scouts' rule: leave the campground cleaner than you found it. For code: every time you touch a part, tidy a little. TD-02 can be paid this way. Next time you change addShipping, add one cart and one test line:
const cartE = [{ name: 'Raka Cap', price: 40, qty: 5 }]; // exactly $200
check(calculateTotal(cartE, ''), 'Total: $200.00');
The total of cartE is exactly the free-shipping minimum, so a < that becomes <= is caught right away. Five minutes, paid while you are already working on that part. A big debt like TD-01 still needs its own scheduled time.
Exercise: assessDebt
Besides the register people write, tools can measure symptoms of debt:
- the percentage of duplicated code;
- cyclomatic complexity: the number of paths through a function. Every
if, loop,&&or||adds one; - test coverage: the percentage of code the tests run;
- the number of packages (libraries installed through npm) that are behind their latest version, which the command
npm outdatedshows.
The exercise scores them with the thresholds (number limits) in the table below. These thresholds are the exercise's own. Every team agrees on its own.
| Measure | Counts when | Points | Recommendation |
|---|---|---|---|
duplicateLines |
> 20 | 25 | Reduce code duplication |
cyclomaticComplexity |
> 10 | 20 | Simplify complex functions |
testCoverage |
< 60 | 30 | Increase test coverage |
outdatedDependencies |
> 5 | 25 | Update outdated dependencies |
Every measure that counts adds its points to debtScore (for example debtScore += 25) and adds its recommendation to recommendations with push, in the table's order. The part that sets priority from the score is already in the editor: 80 and up is critical, 60 to 79 high, 30 to 59 medium, below 30 low.
In the next examples, the numbers inside { } are the four measures, in the table's order. The thresholds are strict: exactly 20, 10, 60 or 5 doesn't count yet, so { 20, 10, 60, 5 } gives a score of 0 and low. Only coverage counts in { 5, 3, 50, 1 }: score 30, medium, one recommendation. The editor's example, { 25, 12, 45, 8 }, counts on all four:
{"debtScore":100,"priority":"critical","recommendations":["Reduce code duplication","Simplify complex functions","Increase test coverage","Update outdated dependencies"]}
⚠️ Debt never paid, or paid for nothing
- "We'll clean it up later" with no record. No ID, no principal or interest, so it never gets paid. Write it in the register when you take it on.
- Paying off every debt. TD-03 is ugly but charges no interest. First pay the debt that has high interest and is touched often.
- Telling the business owner "the code is ugly". Say "every voucher change costs 20 extra minutes, paying it off takes 60, it breaks even after 3 changes".
- Treating a bug as debt. A receipt that says
Saved: $0.00for SAVE20 is a bug caused by debt: fix it today. - In the exercise, using
>=at the threshold. Exactly at the threshold doesn't count yet, so{ 20, 10, 60, 5 }must be0|low(score 0, priority low).
TL;DR: Technical debt is a shortcut in the code that saves time now but charges interest every time the code is touched (Ward Cunningham's metaphor, 1992). Count its two numbers: principal (the cost to pay it off) and interest (extra minutes per change). For example, Raka's shop copied its voucher rate into three places: the total, the receipt and the email. When SAVE20 is added only to the voucher table, the receipt and the email show Saved: $0.00, and every voucher change costs 20 extra minutes. With a principal of 60 minutes, paying it off breaks even after 3 changes (60 ÷ 20 = 3). Write every debt in a debt register with its ID, interest, principal and decision. Ugly code that never changes charges zero interest, so leave it. Deliberate means taking a shortcut knowingly, inadvertent means taking it without noticing, because you didn't know a better way yet. The Boy Scout Rule: leave the code a little better than you found it. In the exercise, assessDebt scores four measures of the code. Every measure past its threshold (percentage of duplicated code > 20, complexity > 10, test coverage < 60, outdated packages > 5) adds 25, 20, 30, 25 points and one recommendation. 80 and up is critical, 60 to 79 high, 30 to 59 medium, below that low.
⚡ A shortcut that charges interest
Write:
// TD-01: copied for the 12.12 sale, listed in the debt register
function savingLine(subtotal, voucherCode) { // place 2
const rate = voucherCode === 'SAVE10' ? 0.1 : 0;
return 'Saved: ' + formatPrice(subtotal * rate);
}
Meaning: Technical debt is a shortcut in the code that saves time now but makes every later change more expensive. Here, to release the new receipt in time for the 12.12 sale, savingLine (the savings line on the receipt) writes the SAVE10 rate itself and doesn't read the VOUCHERS table (the table of voucher codes and their rates). The confirmation email does the same, so the voucher rate is now written in three places. When SAVE20 is added to VOUCHERS only, the receipt says Saved: $0.00. TD-01 is this debt's number in the debt register (the team's list of debts).
⚡ Principal and interest
Guess first: the principal (the cost of paying TD-01 off) is 60 minutes, the interest (extra minutes per voucher change) 20 minutes. After how many changes has paying off TD-01 earned its time back?
Three. 60 ÷ 20 = 3: it breaks even at the third change, and from the fourth on, paying it off is cheaper than leaving it.
Meaning: The principal is the cost of paying the debt off. The interest is the extra minutes every time the code is touched. Numbers like these are what you bring to Raka, the shop owner, not "the code is ugly".
⚡ Write it in the debt register
Meaning: Debt that isn't written down never gets paid, because nobody remembers it. Write every debt in the debt register: its ID (for example TD-01), interest, principal and decision. Ugly code that never changes charges zero interest, so leave it, but keep it listed.
⚡ Pay on the way
Write:
const cartE = [{ name: 'Raka Cap', price: 40, qty: 5 }]; // exactly $200
check(calculateTotal(cartE, ''), 'Total: $200.00');
Meaning: The Boy Scout Rule: every time you touch a part of the code, tidy a little. For example, the small debt TD-02: the tests have no cart whose total is exactly $200, the free-shipping minimum. Without that cart, a wrong <= in the shipping check is not caught. While you are changing the shipping code anyway, add cartE and one check line. Five minutes, paid while you're already there.