Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What's the point of refactoring? #134

Open
nelsonic opened this issue Apr 24, 2020 · 0 comments
Open

What's the point of refactoring? #134

nelsonic opened this issue Apr 24, 2020 · 0 comments

Comments

@nelsonic
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant