When creating a new change set, always try to minimize the amount of changes it introduces.
Do this by only modifying what needs to be modified to implement a feature or fix a bug. Keep formatting and refactoring changes for another commit.
The story of how I came to this practice
Many years ago I read Clean Code. One of the things it discussed was to check in our code a little cleaner than when we checked it out. This meshed with the idea of continual improvement through refactoring which I was already following.
I took this principle to heart and made formatting changes, introduced constants, removed commented code and made small refactorings with my change sets. I kept big refactorings for different commits… well most of the time anyways…
Then later on an open source project I contributed to, I was asked during code reviews to keep those changes out of the change sets. I was surprised since I thought I was helping improve the code’s quality. The project’s maintainers reasoning was that the change set needed to include only the changes required to correct the bug that was addressed or implement the new feature we were working on. Refactorings should be kept as different endeavors or for instances where a piece of code was being completely rewritten during the course of normal work.
Over time I started to see this made more sense than my previous practice and eventually started following this practice as well.
One thing I like to do now is keep notes of what changes I want to make, complete my current work and then make a separate commit for formatting and refactoring changes. If I don’t take notes, too often I forget all the little changes I wanted to do and never get around to doing them.
The why
When a commit needs to be read later on to understand the changes, revert them or when doing a blame/annotate to find out why a change was made it’s much easier if all the changes are related to the commit message and associated ticket number. Otherwise you need to reason for each modification if it was done in relation to the commit’s purpose or as a “bonus” refactoring.
Also, including unnecessary changes makes for longer commits which make for longer code reviews. In my experience the longer the review, the more chances some stuff will get glanced over.
Finally, every change we make, even when having a robust test suite risks introducing regressions. If you later find out your latest changes introduced a bug and it turns out it was in a refactoring, it’s much easier to revert or correct this refactoring without needing to revert a bug fix or feature at the same time.