Skip to main content

Why Each Git Commit Should Record Only One Change

TLDR;

Git commits are not just checkpoints—they’re a map of your code’s history. When commits mix unrelated changes, tools like git blame stop being helpful, making it harder to debug, understand, and maintain code.

Solution

one purpose per commit.

Practical Examples

Mixed Commit

Imagine a web app where a button click triggers an API call:

// Before commit
function submitForm(data) {
api.send(data);
}

You decide to fix a bug in the submit function (data wasn’t validated) and refactor CSS classes on the page in the same commit:

// Mixed commit
function submitForm(data) {
if (!data.name) throw new Error("Name required"); // Bug fix

api.send(data);
}

// Refactored button style
document.querySelector("#submit").classList.add("btn-primary");

Later, a bug appears: the button style breaks in certain themes. Running:

git blame app.js

shows that the CSS change and API fix were introduced in the same commit. Now, it’s harder to isolate the root cause without sifting through unrelated changes.

Separate Commits

The Clean Approach

Commit 1: Fix form validation bug

function submitForm(data) {
if (!data.name) throw new Error("Name required");
api.send(data);
}

Commit 2: Refactor button style

document.querySelector("#submit").classList.add("btn-primary");

Now git blame immediately shows the reason for each change. If a new bug arises in form validation, you know exactly which commit to inspect.

Why This Matters

  • Debugging: Isolated commits let you trace a bug to a single purpose change.
  • Maintenance: Code history remains clear and readable.
  • Collaboration: Reviews focus on one concern, reducing mistakes.
  • Safe reverts: You can undo a single commit without affecting unrelated code.

Conclusion

Mixed commits break git blame and slow down development. Keeping commits focused may seem minor, but it pays off in faster debugging, safer refactors, and clearer history.

Tip: Ask yourself: "Could someone understand this change in isolation months from now?" If not, split the commit.