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.
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]);
}
}
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/));
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)
Great article. With 10 years of software engineering experience in large organization, I would echo “ Applications are assets but code is a liability”.
Thank you. And you're very correct.
Great article
Thank you Maxi