DEV Community

Cover image for Importance of refactoring your code
Kingsley Ubah
Kingsley Ubah

Posted on

Importance of refactoring your code

I am Kingsley Ubah, a budding software developer and tech enthusiast. Today, I am going to write about code refactoring and why it is so important.

Refactoring your code

There is a popular saying that goes: Applications are assets but code is a liability. That is, what you create from coding is valuable but the code used in building that product is of little to no value. This is why it’s so important that you make your code as simple, readable and flexible as possible; which brings us to the main topic of today.

In simple terms, refactoring your code entails substituting better code into your application's source code in place of the undesirable ones, while preserving the core function of the program. There are various reasons for doing that: making the code more readable, flexible, scalable and more maintainable. It is a DevOPs operation which is critical to the success of any tech product or enterprise.

To illustrate, I will use this simple JavaScript code snippet:


const team = [
'Larry King',
'Harrison Ford',
'David C',
'Jackson B',
'Harry M',
];
const arries = [];
for (let i = 0; i < team.length; i++) {
if (team[i].match(/arr/)) {
arries.push(team[i]);
}
}

Enter fullscreen mode Exit fullscreen mode

Take a look at that code. You can easily make out what my intention is. I simply want to return the names that contain the regular expression. Yet, to carry out such a simply function, I wrote 4 lines of code. That just isn’t ideal, and how can we right it? By refactoring the code to just one line:


const  arries = team.filter(member => member.match(/arr/));

Enter fullscreen mode Exit fullscreen mode

This is just a very simple example, so you get the idea. Typically you would do this to large volumes of code. Remember that the essence for refactoring a program’s source code is to make it more readable, reusable, maintainable, and wholly efficient.
Test-driven development (TDD) with assertions can also be employed to create more efficient programs. Briefly, during test-driven development you write a test, then run it (failing), then make it work (passing),and then make it right (refactor). Also, many tools and IDEs now exists to automate some common refactorings, saving us valuable time and effort.

Follow me on twitter at Ubahthebuilder

Later

Top comments (4)

Collapse
 
huaruan profile image
HuaRUAN

Great article. With 10 years of software engineering experience in large organization, I would echo “ Applications are assets but code is a liability”.

Collapse
 
ubahthebuilder profile image
Kingsley Ubah

Thank you. And you're very correct.

Collapse
 
mcsee profile image
Maxi Contieri

Great article

Collapse
 
ubahthebuilder profile image
Kingsley Ubah

Thank you Maxi