Notes Tutorials

Git as a thinking tool

Git isn't just a backup or a way to share code. Used well, it makes you work in small, clear steps: one idea per commit, a diff you read before you commit, messages that explain why, branches for experiments, and safe ways to undo.

7 min readAlso available in Bahasa Indonesia →

“Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.” That’s the textbook definition from Pro Git, and it’s true. Most people learn Git that way: as a backup, or as the thing you push to so your teammates can pull.

But the last few parts already used Git for more than that. In part 12, git blame explained why a strange line existed. In part 15, git bisect found the commit that broke a discount. Both only worked because someone, earlier, made small commits with useful messages. This part is about being that someone, and about how doing so changes the way you work.

One commit, one idea

Here’s a common situation. You’re working on pricing.py and you’ve made two changes: a new 10% discount for 20+ items, and thousands separators in format_rupiah. git diff shows both:

@@ -1,6 +1,8 @@
 def final_price(price, qty):
     total = price * qty
-    if qty >= 10:
+    if qty >= 20:
+        total = total * 90 // 100
+    elif qty >= 10:
         total = total * 95 // 100
     return max(total, 0)
 
@@ -14,4 +16,4 @@ def tax(amount):
 
 
 def format_rupiah(amount):
-    return "Rp" + str(amount)
+    return "Rp" + f"{amount:,}".replace(",", ".")

The easy move is git commit -am "update pricing". But these are two separate ideas. If the new discount turns out to be wrong, you want to undo it without losing the formatting fix. If someone runs git blame on the discount line next year, they should land on a commit about discounts.

git add -p lets you pick which parts go into the next commit. It will “Interactively choose hunks of patch between the index and the work tree and add them to the index”, which “gives the user a chance to review the difference before adding modified contents to the index.” Git shows each hunk and asks:

(1/2) Stage this hunk [y,n,q,a,d,j,J,g,/,e,?]? n
(2/2) Stage this hunk [y,n,q,a,d,K,g,/,e,?]? y

Answer n for the discount and y for the formatting, and only the formatting is staged:

$ git diff --staged
-    return "Rp" + str(amount)
+    return "Rp" + f"{amount:,}".replace(",", ".")

Commit that, then commit the rest. Two commits, each about one thing:

123227b Add 10% discount for 20+ items
cb2ed24 Show thousands separators in rupiah amounts
2a8c473 Add pricing helpers

The real benefit comes before any of this: once you know you’ll commit one idea at a time, you start working one idea at a time. You finish the formatting, commit, then start the discount. That’s the decomposition from part 9 again, with Git keeping you honest.

Read your own diff before you commit

git diff --staged shows exactly what’s about to be committed. Reading it is the cheapest code review there is. In the few seconds it takes, you often catch:

  • a leftover print or var_dump from debugging,
  • a change you made by accident in a file you only meant to look at,
  • a second idea that belongs in its own commit,
  • a password or API key that should never be committed (more on that below).

If you can’t summarize the staged diff in one short line, it’s probably two commits.

Commit messages: say why

The code shows what changed. The message is the only place to say why. Chris Beams puts it well: “A diff will tell you what changed, but only the commit message can properly tell you why.”

His widely cited seven rules:

  1. “Separate subject from body with a blank line”
  2. “Limit the subject line to 50 characters”
  3. “Capitalize the subject line”
  4. “Do not end the subject line with a period”
  5. “Use the imperative mood in the subject line”
  6. “Wrap the body at 72 characters”
  7. “Use the body to explain what and why vs. how”

The imperative mood has a simple test: a good subject line completes the sentence “If applied, this commit will …”. Add 10% discount for 20+ items works. Added stuff and fix don’t.

When the reason isn’t obvious, add a body:

Add 10% discount for 20+ items

Wholesale customers asked for a second tier. 10-19 items keep 5%.

Six months later, git blame on that line leads straight to the reason:

$ git blame -s -L 3,4 pricing.py
123227b4 3)     if qty >= 20:
123227b4 4)         total = total * 90 // 100

Compare that with the refund fix in part 12, where the message “Fix negative totals from refund rows (qty = -1) in CSV import” explained a line that otherwise looked pointless. That’s the kind of message you’re writing for.

Small commits make history useful

Everything in the history tools gets better with small commits:

  • git blame points to a commit about one thing, not “misc changes”.
  • git bisect (part 15) finds a small commit, so the bug is in a few lines, not a few hundred.
  • git revert can undo one idea cleanly.
  • Code review is faster when each commit can be read on its own.

Small doesn’t mean tiny. It means one coherent change, ideally one where the tests from part 14 still pass.

Branches are cheap, so experiment

Not sure an idea will work? Try it on a branch. Pro Git explains why that’s no big deal: “The way Git branches is incredibly lightweight, making branching operations nearly instantaneous”, and “branches are cheap to create and destroy.”

$ git switch -c try-round-to-hundreds
$ # edit, test, commit...
$ git log --oneline -1
d695d2e Try rounding totals down to hundreds
$ git switch main
$ git branch -D try-round-to-hundreds
Deleted branch try-round-to-hundreds (was d695d2e).

The experiment is gone and main was never touched. If the experiment had worked, you’d merge it instead. Either way, you could try something risky without worrying about getting back to a working state.

Undo safely

Mistakes are normal. The question is how to undo them without making things worse.

git revert undoes a commit by adding a new commit that reverses it. The docs: “git revert is used to record some new commits to reverse the effect of some earlier commits (often only a faulty one).” Say the thousands separator broke a report that expected plain numbers:

$ git revert --no-edit HEAD~1
[main 6ea0a5a] Revert "Show thousands separators in rupiah amounts"

$ git log --oneline
6ea0a5a Revert "Show thousands separators in rupiah amounts"
123227b Add 10% discount for 20+ items
cb2ed24 Show thousands separators in rupiah amounts
2a8c473 Add pricing helpers

The formatting change is undone, the discount commit after it is untouched, and the history shows what happened and when. This is the safe choice for anything already pushed and shared.

git reset moves the branch back and can throw changes away. It’s useful on your own, unpushed work, but git reset --hard throws away uncommitted changes. The git revert docs, pointing to it as the alternative, warn: “Take care with these alternatives as both will discard uncommitted changes in your working directory.” If you’re not sure, commit or make a branch first. A commit can almost always be recovered; uncommitted work that’s been reset usually can’t.

Keep secrets and junk out

“A gitignore file specifies intentionally untracked files that Git should ignore.” Put generated files, dependencies, and local secrets in it:

.env
__pycache__/
$ git check-ignore -v .env
.gitignore:1:.env	.env

There’s one catch worth knowing: “Files already tracked by Git are not affected.” If .env was committed before you added it to .gitignore, it’s still in the repository and in its history. Remove it from tracking with git rm --cached .env, and treat any secret that was ever committed as leaked: change the password or key. Part 22 comes back to this.

The loop

Put together, Git gives you a rhythm:

  1. Pick one small change.
  2. Make it, and run the tests.
  3. Read the diff.
  4. Commit with a message that says why.
  5. Repeat.

When you work like this, you’re never far from a working state, you always know what you’ve changed, and the history becomes a log of your reasoning that you (and others) can search later.

Why this matters day to day

  • Less fear. If every step is committed, any experiment can be undone in seconds.
  • Faster reviews and debugging. Small commits with clear messages are easy to review, bisect, and revert.
  • Answers for your future self. “Why is this here?” is one git blame away, if the message says why.
  • Working with AI tools. Commit before letting an AI tool change your code, then read its changes with git diff like any other diff. If you don’t like the result, one command takes you back. Part 24 comes back to reviewing AI changes.

Try it yourself

  1. Make two unrelated changes in one file, then use git add -p to commit them separately.
  2. Look at your last ten commit messages. Rewrite the worst one so it completes “If applied, this commit will …” and says why.
  3. Create a branch, try something risky, then delete the branch without merging. Check that main is unchanged.
  4. Revert one of your own commits on a practice repo and read the resulting history.

Summary

  • Git records changes so you can recall, explain, and undo them; used well, it shapes how you work.
  • One commit, one idea. git add -p lets you split mixed changes.
  • Read git diff --staged before every commit.
  • Messages say why: short imperative subject, body for the reason.
  • Small commits make blame, bisect, revert, and review useful.
  • Branches are cheap: experiment freely, delete what doesn’t work.
  • git revert undoes safely with a new commit; be careful with git reset.
  • .gitignore keeps junk and secrets out, but doesn’t affect files already tracked.

References