dwyl / learn-tdd

:white_check_mark: A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
Mozilla Public License 2.0
2.74k stars 349 forks source link

What's the point of refactoring? #134

Open nelsonic opened 4 years ago

nelsonic commented 4 years ago

A friend who is (re)learning software development asked me the following question: image It's worth capturing the answer in public and then sharing with them privately. 📝 🔗

The two primary reasons to refactor code are complexity and performance. (in that order) If the existing code works but is difficult to understand (maintain) or the code is slow to execute, then it's a good idea to refactor it.

If you have code in your project that passes all tests but is difficult to read refactor it into smaller functions that each do one thing and are sensibly named. e.g: a function that does too many things and has lots of if/else blocks ("Cyclomatic complexity") Split the blocks into smaller named functions that can be individually tested then reassemble them.

If you have a block of code that is slow it can be a good idea to refactor it. When it comes to performance optimisation, always take a scientific approach. Benchmark the slow code creating a performance test (run the function a few thousand times) and recording the result. Then you can re-run the test to confirm that the refactor actually improved/reduced the execution time. We have seen cases of people refactoring code and making things slower. Don't make that mistake.

Remember it's only refactoring if you already have passing tests for the desired functionality and you change the code that makes the tests pass. Avoid changing the tests while you are refactoring as that will increase complexity. Changing code that is untested is not refactoring it's roulette. You might get lucky and not break anything, but odds are very much against you.