DEV Community

Cover image for 6 tips for refactoring code
Kelvin Graddick
Kelvin Graddick

Posted on

6 tips for refactoring code

⁣⁣What is code refactoring?

Refactoring is the process of restructuring existing code (changing the factoring) without changing its external behavior.

Here are 6 tips for refactoring code:

Tip 1: Remove duplication

Follow the D.R.Y. principle and Don’t Repeat Yourself.
— If you see code, functions, and/or logic being repeated, rewrite the code to remove the duplication.

Tip 2: Improve responsibility

Follow the Single Responsibility Principle. Variables/classes/functions should have a single responsibility and thus only a single reason to change. Ensure a separation of concerns by having separating things into sections that handle a certain ‘concern’.
— avoid coupling of different logical entities

Tip 3: Remove unneeded code and over-complexity

— Remove anything that is unneeded to simplify the code and reduce confusion or “why is this here?”
Y.A.G.N.I “You aren’t gonna need it”: avoid trying to cover every possible extra case and future scenario if the likelihood is low or very unknown

Tip 4: Be consistent and follow standards

Sometimes it’s better to stay consistent with the current project, even if there might be a better way.
— Follow standards where you can to make your code more predictable to others

Tip 5: Adopt a design pattern when needed

A design pattern is a general, reusable solution to a commonly occurring problem in software design.
— Always keep things simple first; only adopt a design pattern when the code begins to show it

Tip 6: Pull-up Push-down

Determine if methods, objects, and/or logic need to be consolidated at a ‘higher’ level, or need to be pushed down to a ‘lower’ one
— in the case that logic is duplicated in two places, pull up toe a higher level
— in the case that logic is shared between multiple places, but only utilized in one; push down to the one that uses it

⁉️ What tips so you have for refactoring code?

Top comments (0)