A Set of Refactorings

A Set of Refactorings

5 ways to improve the existing code.

In this article, we will have a look at 5 ways you can improve the existing code.

Extract Function

Sometimes you have a small piece of logic that when extracted to a function with a meaningful name, the code can become more readable and easier to work with and because you know what the function's intent is, you may also know whether you need to have a look into that function or not when reading the code.

Separate intent and implementation

From

Sample where the function could be extracted

To

Sample where the function is extracted

Inline Function

In some instances, it is more readable to inline the function.

From

Screenshot from 2021-06-26 09-11-22.png

To

Sample where the function is inlined

Renaming

This one is pretty simple, but will come in handy many times, renaming variables, for them to become more readable and requiring less cognitive load to understand.

From

Sample with bad variable name

To

Sample with good variable name

Splitting variables

Sometimes you come across variables being reassigned, which itself is a code smell, oftentimes in such cases, the variable in one of the positions has a bad or wrong name.

This can be improved by instead of reassigning the variable, declaring a new one with a proper name.

Personally, from my experience, reassigning variables makes the code confusing, and often requires a lot of cognitive loads to understand the code.

From

Sample with reassignment

To

Sample with two variables

Extracting variables

In some instances, you may have a lot of logic going on, and by breaking up the logic into variables, it is not just easier to read the code and requires less cognitive load to understand, but also easier to debug the code because you can put in a debugger or log out the values.

From

Sample with inlined variables

To

Sample with extracted variables