Commit History Best Practices

Have you ever found yourself looking at code you wrote 6 months ago wondering why you did it that way? A well-crafted commit history transforms your repository into a comprehensive story of your codebase, where the purpose of every change is understood. In the rest of this blog post I wish to share best practices to achieve this outcome.

Single Logical Changes

Every commit should represent a single change that you want to make to the codebase. In order to reach a certain objective many changes may need to be made; this is what many know as merge or pull requests; I will refer to it as a collection of commits.

For example, “Adding a tertiary styled button”. In order for that to be done, we need to generalize the existing button styles, so that they can be extended and have the color changed. This change would be broken down into two logical steps.

Clear Commit Subject Lines

A commit subject line should clearly state how the system changes once this commit is applied. Think of explaining WHAT in less than x amount of characters

Using our previous example:

Good: “button now has API to specify background color”

Bad: “Need to refactor the button code for tertiary style”

In the good example it is clear how this commit changed the system, if I wanted to understand why the change was made that’s what the commit body is for.

Meaningful commit body

The body is your opportunity to explain WHY you made the change. Using the previous example “We needed to add this API to support tertiary style buttons” gives great context as to the reason for the change. It is also a great opportunity to explain other thoughts and considerations that went into the decision.

Consistent Format

Just as we apply style guides to our codebase, commits should follow a consistent format. As long as the content is meaningful, the format does not really matter. For example:

TLDR

When selecting the changes to the commit to add ask yourself Does this commit contain more than one change that can be separated?

While writing the subject line, answer the question How does the system change when my commit is merged?

When adding the body, ask yourself Why did I make this change, how could this change be better, why did I do it this way?