Refactoring — what & when

Refactoring is an important aspect of software development to keep the code relevant over time and improve it’s longevity. Without refactoring, a software tend to rotten and loose it’s descriptively over time.

Refactoring

What is refactoring?

Refactoring is about

“changing the internal structure of software in order to make it easier to understand and reduce the cost of future modifications without changing its observable behaviour”.

When to refactor?

While the general answer would be that it should be in our radar all the times when writing code. Refactoring and feature building should go hand in hand.

While it’s a good idea to refactor code while developing a feature, we should keep them isolated when writing code. In essence we should not write code that refactors and add new features all at once. Ideally we should refactor, run tests to see if everything works, and then starts writing code for a new feature.

How to know if my code needs refactoring?

Generally I look for one of the below 5 symptoms in the code that is the right candidate for refactoring.

Cryptic Variables, function or module names

This is a great starting point. If you see variables, functions and modules whose names are not aligned with what the code is doing then they should be renamed to better align with the intention of the code.

Duplicate Code

While we all try to follow the DRY (Don’t Repeat Yourself) principle when writing code, we always end up writing code where a logic is duplicated at multiple places. This is another candidate for refactoring. We should try to remove the duplicate code and point everything to one single copy of the code.

Long Function

We should always try to keep our functions short (< 50 lines). Longer functions tend to violate single responsibility principle. Such functions should be avoided as much as possible.

Long Argument List

A lots of arguments/parameters make code difficult to understand and maintain. Instead use objects with good names to pass as parameters to functions. This improves the maintainability of the code.

Global Data

The last but not the least, is excessive usage of global data. The global data that is being modified could create a lot of unexpected behaviours. They are difficult to change for future requirements as their change can impact different parts of the program. If global variables are being used, try to reduce their scope as part of refactoring.

Happy reading & refactoring.

--

--

Amit Kumar Dube (अमित दुबे)

@AmitDubeDev | Professional GCP Architect | Terraform ACE | Lead Infra Consultant | Hindi Speaker