Sometimes you have complicated expressions that could benefit from being broken down to more manageable and easier to understand chunks of code.
An easy refactor is to extract out logical bits of the complicated expression into separate methods (consider private methods for these).
Here’s an example using a Salary class that calculates an employee’s total compensation:
The total_compensation method is hard to understand and would benefit from extracting some of the expression into separate methods.
After extracting the expression logic into separate methods, we now have more manageable code that is much easier to understand. If we had tests to test the total_compensation method prior to the refactoring, they should still pass at this point.
Bonus: There’s a repeating pattern here that would also benefit from refactoring. Let me know what you think in the comments.