Refactoring Code for Simplicity and Performance

Refactor your code.

As a developer, inheriting messy code often comes with the job. In many circumstances, it’s considered to be a rite-of-passage and helps build your skills while improving the solutions you are developing and maintaining.

I recently came across an article via Hacker NewsTim Moxley’s Avoid Else, Return Early post is concise and perfectly illustrates how to refactor code to improve legibility and reduce time spent on maintenance.

Refactoring your code, whenever possible, is a valuable exercise and will provide immediate and long term benefits to any project that you work on. It’s a practice that we routinely apply to all development projects here at Valiant Technology, and I’ve included a real-world example from our development team below.

Did I Really Write This?

Have you ever looked at a piece of code you wrote, say 6 months ago, and asked yourself if you actually wrote it? Chances are that you have, and that’s a good thing. It means that your skills are growing and you are noticing better ways to approach solutions to the problems you tasked to solve.

If you do look at code you’ve written in the past and determine that it is perfect, take another look.

Technology progresses at a fast pace, and so do the techniques and methods used in software development. Being totally confident in the code you write, over time, is a bad – even dangerous way of looking at your work. While you may be writing code that you are comfortable with, and is perfectly stable within the context of what you’ve set out to accomplish, there’s a good chance that you’re racking up technical debt in the process.

Technical debt, for those unfamiliar with the term, is a concept that reflects the implied cost of additional work caused by choosing an easy solution now instead of a better approach that would have taken more time. It can happen for many reasons – shifting timelines and budgets, adjusting goals, and a team of developers with individual, differing, styles are all common causes.

Refactoring Code and Reducing Technical Debt

There are many ways to reduce technical debt within a project, and we’re going to concentrate on refactoring as a strong way to begin the process.

Refactoring code is the process by which you simplify existing code without causing a change in it’s expected output. This includes restructuring your code to contain fewer lines, using meaningful variables to make the code easier to understand, and expanding on documentation so other team members fully understand what your code is designed to do.

A Real-Life Example of Refactoring

Our development team wrote a wrapper for Yelp’s Fusion API last summer as an exercise. The wrapper works nicely, and we’ve implemented it in a “lunch suggestions” bot for Microsoft Teams. After running the codebase through CodeClimate, we found that some of the conditional logic wasn’t written as well (or as simple) as it could be.

This is just a small block of the code, but it serves as an excellent example of how refactoring can improve code performance, legibility, and help reduce technical debt.

The code snippet is from a function that sends authentication details to Yelp’s API so that we can begin making requests for local restaurant information:

Before Refactoring

public static function bearerRequest($id, $secret) { 
    $uri = self::$apiUri . "/oauth2/token";
    $body = self::urlEncoded([ "grant_type" => "client_credentials", "client_id" => $id, "client_secret" => $secret ], false);
    $response = self::doRequest($uri, $body, "post");
    if($response->code == 200){
        return $response->body;
        } else {
        throw new \Exception("API responded with a HTTP status of {$response->code}.");
    }
}

The code sends a request to Yelp’s API, and if the response doesn’t contain a “200OK” status code in the header, we know there’s been a problem and to raise an exception – this allows the code that called the function to know something has gone wrong and take the appropriate actions.

This works perfectly well, but a few minor changes can be made to make the code easier to understand, and eliminate some of the conditional logic that isn’t absolutely necessary.

After Refactoring

public static function bearerRequest($id, $secret) {
    $uri = self::$apiUri . "/oauth2/token";
    $body = self::urlEncoded([ "grant_type" => "client_credentials", "client_id" => $id, "client_secret" => $secret ], false); 
    $response = self::doRequest($uri, $body, "post");
    if($response->code !== 200) throw new \Exception("API responded with a HTTP status of {$response->code}.");
    return $response->body;
}

 

The difference between the code snippet, before and after refactoring, is minor. We’ve taken 5 lines of conditional logic and reduced down it to 2 without changing how it works. This makes it easier to read and understand, and eliminates the if/then/else conditional logic that wasn’t really needed in the first place.

Now, think about this change in terms of scale. It doesn’t seem like much in the above example, but can make a major difference in a monolithic application. There’s the potential to remove hundreds, even thousands, of lines from a large application – making it much easier to maintain and help reduce technical debt. The time you may have to spend debugging or working on a feature is reduced, and energy can be put in to more productive, revenue generating, efforts.

But Wait… There’s More!

Maintaining good code is a never ending process and there are plenty of other ways to refactor and improve the quality of your work. Next time, we’ll talk about some of the ways that you can make your code more readable with well-written comments.

Do you have a tip that you’d like to share? Please leave them in the comments below!

As a developer, inheriting messy code often comes with the job. In many circumstances, it’s considered to be a rite-of-passage and helps build your skills while improving the solutions you...

Continue reading

Subscribe to Valiant's Monthly Email Digest

Valiant's monthly email digest is filled with original content written by our staff, tech news, and business insights.