Splitting Code Changes into Separate Commits
The systems we build are inherently incredibly complex. The successful ones will encapsulate years of accumulated business logic and context and hopefully, become legacy systems that future developers will complain about or perhaps suggest rewriting entirely for no other reason that it’s a pain in their arse.
There then comes a moment of time where someone, somewhere, will start working in a section of code that features a particularly perplexing bit of logic that makes the unsuspecting developer go “huh?”.
You start chasing down the original authors of the code, or if they’ve moved on, then on and on until you find the next most likely person in the company that might understand the code to try and elicit some more insight as to why the code looks the way it does.
This is a problem that spans organisations across the globe, but the good news is, that this doesn’t have to be such a glaring problem!
Detailed Commit messages
This is where good engineering practices come in and save the day. The particular practice I’m talking about is that of detailed commit messages and splitting up complex changes into multiple commits that feature all of the context as to what has changed.
This practice allows you to impart all of your worldly logic in way that is consumable for other developers should they need to understand how a codebase has evolved over time. You can leave helpful clues as to what particular business functionality your whacky logical statements are supporting and ultimately reduce the maintenance burden on folks in the future.
Helpful Git commands
Ok, so we’ve covered why this practice is helpful, let’s have a look at some of the helpful git commands that can make the art of splitting commits easier.
Adding Patches
This command is fantastic for staging specific pieces of your code. It walks you through interactively each of the distinct blocks of code that have been changed in each of your modified files and gives you the option to stage either entire hunks (yes, they are called that) or specific lines if you need to break it up even further.
$ git add -p
Viewing Staged Changes
Once you’ve staged your changes, you can use this command to view those staged changes and verify everything looks good to go before you write those carefully crafted commit messages.
$ git diff --staged
Rebasing Your Commits
If you’ve already created some commits, coming back to then edit or squash them can be done with
the help of the rebase
command. This can also allow you to pull in any of the latest changes
from your main development branch and ensure you’re always working on the most up-to-date version
of the code.
$ git rebase -i origin/main
Conclusion
Awesome, so in this tip, we’ve covered why and how you should write detailed commit messages as well as covering some of the most commonly used commands to help you craft the perfect story.