DeepCode is now part of Snyk. Learn more about Snyk Code.

SummerAcademy on Debugging - 2.1.14 Refactoring

Thursday, September 17th, 2020



Refactoring is the process to optimize and clean up existing code to improve readability, performance, and overall quality without changing the behavior. There are some great resources online to check out for example the refactoring book by Evan Burchard’s Refactoring JavaScript.

Refactoring best practices

Before starting refactoring code, make sure you have the time and authority to end what you started!! Refactoring of code takes time and fixing a small bug resulting in thousands of lines changed, might not what your team expects.

Here is a list of refactoring best practices from DeepCode:

  1. Improve Readability and Structure by watching out for typical Code Smells:

    1.1. Use tools such as your IDE and Prettier to make your code shiny. Review the feedback from static code analysis such as DeepCode.

    1.2. Try to keep complexity and lines of code low

    1.3. Rename variables and functions to reflect what they do

    1.4. Use const instead of var or let where possible to express your intent

    1.5. Add comments describing what a function does, its parameters, and return value

    1.6. Keep the total number of inputs to a function low. Think about using a parameter object collecting the parameters instead of individual parameters. This provides better flexibility.

    1.7. Prefer explicit inputs to nonlocal inputs - again in the sense of keeping the side effects low

    1.8. Stay within the best practices of your framework (aka usage of props)

    1.9. Prefer real, meaningful return values to side effects.

    1.10. Keep side effects to a minimum or nonexistent.

    1.11. Have a **well-defined this **when possible for functions and other variables (attributes) by making them part of classes (or at least objects) to cut down on nonlocal inputs and global variables.

    1.12. In JavaScript, mechanisms to delimit internal from external interfaces (called encapsulation in OO) are still a bit complicated. This article on private and protected properties gives a nice introduction. But it is worth the effort.

    1.13. Be aware of the difference between == and === in JavaScript

  2. Rewrite using a higher abstraction level, aka using frameworks but try not to introduce new frameworks.

  3. Review your architecture (see DeepCode’s blog post about Software Architecture types and best practices)

  4. Rewrite using a different language like TypeScript which is probably the most radical step you can do. But sometimes, it is needed.

Key Take-Aways

Refactoring is the process that comes normally after the bug fixes itself. Idea is to reduce tech debt, stacking up of complicated, unmaintainable constructions. Use your IDE or your editor to help you. How? Check our article about IDEs.

Learn more about Debugging in our latest blog posts!