James Clear's Atomic Habits (2018) usually gets shelved under self-help, but most of its ideas map directly onto how codebases and teams get better or worse over time. This is not a chapter-by-chapter summary. It is the handful of ideas I keep coming back to, translated into scripts, hooks and defaults you can drop into a project this week.
TL;DR
- Small improvements compound: ship small pull requests often, not heroic rewrites.
- Goals set direction; systems do the work. Invest in scripts, templates and CI.
- Use the four laws as repo design rules: make the right thing obvious, attractive, easy and satisfying, and invert them to make bad habits hard.
- Shrink new habits until they take two minutes: a
test.todo, a three-heading decision record, one line in a shipped journal. - Track to learn, not to perform. Once a number like the contribution graph becomes the target, it stops telling you anything.
Small gains compound
Early on, the book makes an arithmetic argument: 1% better every day for a year compounds to roughly 37 times better (1.01 to the power of 365 is about 37.8), while 1% worse every day leaves almost nothing (0.99 to the power of 365 is about 0.03). It is an illustration, not a law of nature, but the shape is right: small changes look irrelevant on any given day and decisive over a year.
He also describes a plateau of latent potential: effort piles up with no visible result, then seems to pay off all at once. Anyone who has learned GLSL shaders or TypeScript generics knows the feeling.
In engineering, the 1% unit is the small pull request. A small PR that lands today beats a large one next week: it gets reviewed instead of skimmed, it is easy to revert, it conflicts less, and it meets real users sooner. Feature flags help here: unfinished work can merge behind a flag instead of living on a branch for a month. Shipping something small daily is not about speed. It keeps the feedback loop short enough that mistakes stay small too.
Systems beat goals
Winners and losers usually share the same goals, Clear argues, so the goal cannot be what separates them. The system does: the repeatable process that produces the result. Goals also have a finish line, and once you cross it the behaviour that got you there tends to stop.
| Goal | System |
|---|---|
| Reach 80% test coverage | Every bug fix ships with a regression test |
| Launch v2 by March | A weekly release with a deliberately small scope |
| Pay down tech debt | Leave each file you touch a little cleaner |
| Get better at system design | Write a short design note before any cross-service change |
The coverage goal invites tests that execute lines without asserting anything. The regression-test system produces coverage exactly where bugs have already happened. Goals pick the direction; machinery does the work: scripts, templates and checks that make good behaviour the path of least resistance.
Identity before outcomes
The deepest layer of change, according to the book, is identity: not wanting to write more tests, but being an engineer who does not ship untested code. Clear frames each action as a vote for the person you are becoming. No single vote settles it; the tally does.
This is practical. Identity answers the small decisions no policy covers. Fix the flaky test, or rerun the pipeline and hope? If you see yourself as someone who leaves the build greener than they found it, you do not need a rule. It also explains why documentation drives fade: they aim at an outcome. A team that sees itself as able to onboard a new engineer in a day writes docs as a side effect.
The four laws as repo design rules
Clear splits a habit into cue, craving, response and reward, and turns each step into a law: make it obvious, attractive, easy and satisfying. They read like product principles, so I use them as design rules for the repository itself.
Make it obvious
If the right command lives on a wiki page, people will run the wrong one. Put the commands people need in package.json, where every newcomer and every editor looks first, and name them after what people are trying to do:
{
"scripts": {
"setup": "npm ci && git config core.hooksPath .githooks",
"dev": "next dev",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
"test": "node --test",
"check": "npm run lint && npm run typecheck && npm run test",
"shipped": "node scripts/shipped.mjs"
}
}npm run check is the cue: one obvious command that does exactly what CI does. Likewise, the README should open with how to run the project.
Make it attractive
We copy the habits of the groups we belong to, and on a team that norm is mostly set in code review. If reviewers call out a well-written test or a clear PR description, and senior engineers visibly do the boring things, the behaviour spreads. If only the late-night hotfix gets celebrated, expect more late-night hotfixes.
Clear also suggests temptation bundling: pairing something you need to do with something you want to do. My version: the interesting refactor waits until the dependency updates are merged.
Make it easy
Clear calls it the law of least effort: we drift toward whatever takes the least work. So remove steps from the right path. A fresh clone should reach a running app with npm run setup and npm run dev. A pull request template turns a good description into filling in blanks:
## What changed
## Why
## How I tested it
## What reviewers should look at firstAnd CI should run the exact same check script, so "works locally" and "passes CI" mean the same thing:
# .github/workflows/ci.yml
name: CI
on:
pull_request:
push:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run checkPin whichever major versions of the actions are current when you set this up.
Make it satisfying
The book's cardinal rule is that rewarded behaviour gets repeated. The problem with good engineering habits is that the cost is immediate and the reward is delayed: the test costs time now, and the bug it prevents might never visibly happen. So attach a fast reward: a suite quick enough that you actually run it, a green check on the PR, and a written record of what you shipped (more on that below).
Inverting the laws for bad habits
Each law has an inversion for breaking habits: make it invisible, unattractive, difficult and unsatisfying.
| Law | Inversion | In a codebase |
|---|---|---|
| Obvious | Invisible | Mute non-urgent channels during focus blocks |
| Attractive | Unattractive | Lint errors that explain why a pattern is banned |
| Easy | Difficult | Pre-commit hooks, branch protection, required reviews |
| Satisfying | Unsatisfying | A failed check blocks the merge immediately |
Lint rules that explain themselves
A lint error that gives a reason persuades better than a bare rule name. This ESLint flat config (the default format in ESLint 9) bans the classic leftovers:
// eslint.config.mjs
export default [
{
files: ['**/*.{js,mjs,jsx}'],
languageOptions: {
parserOptions: { ecmaFeatures: { jsx: true } },
},
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }],
'no-debugger': 'error',
'no-restricted-properties': [
'error',
{ object: 'it', property: 'only', message: 'Focused tests skip the rest of the suite.' },
{ object: 'describe', property: 'only', message: 'Focused tests skip the rest of the suite.' },
{ object: 'test', property: 'only', message: 'Focused tests skip the rest of the suite.' },
],
},
},
{
// Command-line scripts are meant to print
files: ['scripts/**'],
rules: { 'no-console': 'off' },
},
];Without ecmaFeatures.jsx, the default parser fails on every .jsx component. The second object lets command-line scripts, like the journal script below, print. With typescript-eslint, add the same rules to the object matching your .ts files.
A plain pre-commit hook
No framework needed. Save this as .githooks/pre-commit and run chmod +x on it; the setup script above points Git at the folder via core.hooksPath:
#!/bin/sh
# .githooks/pre-commit
branch=$(git symbolic-ref --short HEAD 2>/dev/null)
if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
echo "pre-commit: you are on $branch. Create a branch first:" >&2
echo " git switch -c your-branch-name" >&2
exit 1
fi
# Same checks CI runs, so a red build is caught before it is pushed
npm run --silent lintCommitting on main now fails with a hint:
$ git commit -m "Fix cart total rounding"
pre-commit: you are on main. Create a branch first:
git switch -c your-branch-nameIf your team commits straight to trunk, drop the branch check. If it works across Windows and Unix, add .githooks/* text eol=lf to .gitattributes so the script keeps Unix line endings.
Anyone can skip hooks with git commit --no-verify, so a hook is friction, not a wall. The wall is branch protection on the server: require a pull request, require the CI check and block force pushes on main. GitHub offers this through branch protection rules and the newer rulesets; the settings screens change, so check the docs for your plan.
Habit stacking
Habit stacking attaches a new habit to one you already do reliably: after the existing habit, I do the new one. The existing habit is the cue, so there is nothing to remember. A few for engineering work:
- After I open a pull request, I review one teammate's PR before starting the next task.
- After I merge, I log one line with
npm run shipped. - After I fix a bug, I write the regression test before closing the issue.
- After Dependabot opens a major-version PR, I read the release notes before merging it.
The two-minute rule for tests and docs
The two-minute rule says to scale a new habit down until starting it takes under two minutes: reading more becomes reading one page. You have to establish a habit before you can improve it, and the tiny version is how you establish it.
The two-minute version of writing tests is naming them. Here it is with Node's built-in runner, which needs no install:
// src/money.mjs
export function lineTotal(unitPrice, quantity) {
if (quantity < 0) throw new RangeError('quantity must be >= 0');
return Math.round(unitPrice * quantity * 100) / 100;
}// test/money.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { lineTotal } from '../src/money.mjs';
// The two-minute version: name the cases now, fill them in later
test.todo('rounds line totals to two decimal places');
test.todo('rejects a negative quantity');
// The first real one usually follows within the same sitting
test('multiplies price by quantity', () => {
assert.equal(lineTotal(2.5, 4), 10);
});Running node --test on Node 24 prints this (timings will differ, and the reporter format varies between Node versions):
✔ rounds line totals to two decimal places (1.5389ms) # TODO
✔ rejects a negative quantity (0.2152ms) # TODO
✔ multiplies price by quantity (1.8149ms)
ℹ tests 3
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 2
ℹ duration_ms 189.3643Todos do not fail the build, but every run counts them, which is a gentle cue. Vitest and Jest offer it.todo and test.todo too.
The two-minute version of documenting the architecture is a decision record with three headings:
# 0007: Use server actions for form submissions
Date: 2025-10-20
## Context
Forms posted to API routes, and validation was duplicated on client and server.
## Decision
New forms use server actions with a shared validation schema.
## Consequences
Form logic lives next to the page. API routes remain for external clients only.Nobody avoids writing that, and a folder of them a year later is the most useful documentation a project has.
Environment design
Clear argues that environment shapes behaviour more than motivation does. For a project, the environment is its defaults. An .nvmrc pins the right Node version. A committed .env.example turns setup from a scavenger hunt into a copy. Shared format-on-save settings mean formatting is never a review comment. A Docker Compose file means installing Postgres is not step one of onboarding.
For yourself, the book suggests giving each space one use. A separate browser profile for work, with no social tabs, is the cheapest version I know.
Never miss twice
A single slip does no real harm, Clear argues; the second one in a row quietly becomes the new routine. The rule is useful because it plans for failure.
Skipping one week of dependency updates is fine; skipping two in a row is how you end up several majors behind. A hotfix without a test is a fair call under pressure; the follow-up PR that adds the test keeps it from becoming normal. When you skip a practice on purpose, open the catch-up ticket immediately, so a second miss has to be a decision, not a drift.
Learning habits
Learning is where compounding is strongest and quitting is easiest. The habits that last are small and stacked onto existing work:
- When an error confuses you, write one line in a TIL file once you understand it.
- When you call a library function every day, read its source once.
- When a framework you use ships a release, read the changelog before upgrading.
- Read ten pages of a technical book before opening email.
Over a year, these are the difference between using a tool and understanding it.
Track what you shipped
A habit tracker makes progress visible, and that evidence is itself the immediate reward. Mine is a script that adds one line to a Markdown journal and nudges me if I skipped the previous workday:
// scripts/shipped.mjs
// Usage:
// node scripts/shipped.mjs "Added retries to the webhook handler"
// node scripts/shipped.mjs --date=2025-10-16 "Backfill a day you forgot"
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
const JOURNAL = process.env.SHIPPED_FILE ?? 'shipped.md';
const args = process.argv.slice(2);
const dateFlag = args.find((arg) => arg.startsWith('--date='));
const entry = args.filter((arg) => arg !== dateFlag).join(' ').trim();
if (!entry) {
console.error('Usage: node scripts/shipped.mjs [--date=YYYY-MM-DD] "what you shipped"');
process.exit(1);
}
// Local calendar date (not UTC), so a late-night entry lands on the right day
function toDay(date) {
const pad = (n) => String(n).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
function fromDay(day) {
const [y, m, d] = day.split('-').map(Number);
return new Date(y, m - 1, d);
}
// Step back over Saturday and Sunday: weekends are not missed days
function previousWorkday(day) {
const date = fromDay(day);
do {
date.setDate(date.getDate() - 1);
} while (date.getDay() === 0 || date.getDay() === 6);
return toDay(date);
}
const day = dateFlag ? dateFlag.slice('--date='.length) : toDay(new Date());
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) {
console.error(`Expected --date=YYYY-MM-DD, got "${day}"`);
process.exit(1);
}
// Splitting on the "## YYYY-MM-DD" headings gives [intro, day, lines, day, lines, ...]
const existing = existsSync(JOURNAL) ? readFileSync(JOURNAL, 'utf8').replace(/\r\n/g, '\n') : '';
const [intro, ...parts] = existing.split(/^## (\d{4}-\d{2}-\d{2})[ \t]*$/m);
// Group the lines by day; a day that appears twice is merged into one
const days = new Map();
function add(d, lines) {
days.set(d, [days.get(d), lines].filter(Boolean).join('\n'));
}
for (let i = 0; i < parts.length; i += 2) add(parts[i], parts[i + 1].trim());
add(day, `- ${entry}`);
// Rewrite the whole file in date order, so a backfilled day lands in its place
const sections = [...days.keys()].sort().map((d) => `## ${d}\n\n${days.get(d)}\n`);
writeFileSync(JOURNAL, `${intro.trim() || '# Shipped'}\n\n${sections.join('\n')}`);
const loggedDays = new Set(days.keys());
const recent = [day];
while (recent.length < 5) recent.push(previousWorkday(recent.at(-1)));
const hits = recent.filter((d) => loggedDays.has(d)).length;
console.log(`Logged to ${JOURNAL} under ${day}`);
console.log(`Workdays with an entry, last 5: ${hits}/5`);
if (!loggedDays.has(previousWorkday(day))) {
console.log('Missed the previous workday. Fine once; just do not miss twice.');
}Here is a replayed week using --date. With entries on Tuesday and Wednesday and nothing on Thursday:
$ node scripts/shipped.mjs --date=2025-10-17 "Removed two unused dependencies"
Logged to shipped.md under 2025-10-17
Workdays with an entry, last 5: 3/5
Missed the previous workday. Fine once; just do not miss twice.
$ node scripts/shipped.mjs --date=2025-10-20 "Split the settings page into three smaller components"
Logged to shipped.md under 2025-10-20
Workdays with an entry, last 5: 4/5After one more entry on Monday, the journal reads:
# Shipped
## 2025-10-14
- Added an empty state to the orders table
## 2025-10-15
- Wrote a regression test for the timezone bug in invoice dates
## 2025-10-17
- Removed two unused dependencies
## 2025-10-20
- Split the settings page into three smaller components
- Documented the local setup in the READMEBecause the file is rewritten in date order, a late --date=2025-10-16 entry lands between Wednesday and Friday, not at the bottom.
Day to day, run npm run shipped -- "what you did"; npm passes everything after -- to the script. Point SHIPPED_FILE at a notes folder if you do not want the journal in the repository. It pays off in standups, performance reviews, and on days when it feels like you did nothing.
Tip: Write outcomes, not activity. "Fixed the invoice rounding bug" is useful in six months; "worked on invoices" is not.
Goodhart and the green squares
The obvious tracker for developers is the GitHub contribution graph, and it is a trap. Goodhart's law, usually paraphrased as "a measure that becomes a target stops being a good measure", applies perfectly. Clear raises the same risk in his chapter on tracking: you can end up serving the number instead of the purpose behind it.
Optimise for green squares and you get one change split into five commits, a typo fix just before midnight to save the streak, scripts that commit to a dummy repository. Meanwhile the graph cannot see the design discussion that killed a bad idea or the review comment that prevented an outage. It also only counts activity that meets GitHub's rules (default branch, not a fork and so on; check their docs).
That is why the journal records sentences rather than counts, and its only number is a five-day nudge, not a streak to protect.
Warning: Never turn team activity metrics such as commits or lines changed into targets. People will hit them, and the numbers will stop meaning anything.
Where I would start
Try it on your own project in this order, one step at a time:
- Add
setupandcheckscripts, and make CI runnpm run check. - Turn on branch protection with the CI check required.
- Add lint rules and a pre-commit hook for the mistakes your team actually makes.
- Start the shipped journal: one line per workday.
- Pick one practice, tests, docs or reviews, and shrink it to its two-minute version.
None of these is impressive on its own. That is the point of the book: the returns come from repetition.