To reduce duplication in your code, there usually are two ways to approach it:
- Start from the top and extract the biggest common block of code to a function
- Start from the bottom (leaves) and extract the common expression(s) to a function
It’s best to always aim for doing the latter and start by extracting smaller things rather than bigger things. Here’s why:
- There’s a much bigger chance that you will extract a function that is small enough to not require any further refactoring. You will have extracted a part of code that will have more lasting value.
- Smaller parts are easier to compose, so you will end up with a better overall design. In some cases you might discover a new abstraction hiding underneath, making it possible to express the code’s intent more clearly.
- Extracting smaller (pure) functions has more chance of being able to add tests around the new code.
- If you start from the top you will most likely make a mistake anyway because it’s really difficult to see the commonalities in a big block of code.
Starting small seems counterintuitive because it feels like nothing is getting done. We all like to removing code. It’s better to start small, it always works out better.