Refactoring: Improving the Design of Existing Code
By Martin Fowler
This book is easily the most impactful book I have ever read and dramatically changed how I approach writing code, making changes, making commits, PRs, testing, etc. In truth, this book deserves an entire blog post of its own, but I'll share just a bit here.
Most people use the word "refactoring" incorrectly. There is a very small and specific definition of "refactor" we ought to use. A "refactor" is when we change the organization of the code without changing the functionality of the code. I think of it a lot like solving math problems. We can modify the equation, so long as it remains equivalent, such as adding a number to both sides. This implies that in order to refactor anything we must first have the code under tests. How else can we be certain that the code is functionally the same?
Once we have tests, then our objective in a refactor is to go from "green to green". We rearrange and reorganize the code so that we're able to achieve our future goals while doing nothing to change the current behavior. That means you don't commit anything extra. No little fixes here. No tweaks there. Just the refactor.
What's amazing about being this strict about refactoring is that you gain some super powers. The latter half of the book is a collection of refactor recipes. Step by step instructions on how to transform this to that and back again. It's just like the math formulas I was talking about. How to shift from here to there without breaking anything.
You need to grab this book. I own the first edition, which is in Java. I've never even written Java and it's that helpful. There's a second edition now that's rewritten in JavaScript that will probably be a lot more accessible to most of you.