About this book

Refactoring improves your code without changing its behavior. With refactoring, the best approach is to apply small targeted changes to a codebase. Instead of doing a huge sweeping change to your code, refactoring is better as a long-term and continuous enterprise. Refactoring TypeScript explains how to spot bugs and remove them from your code.

You’ll start by seeing how wordy conditionals, methods, and null checks make code unhealthy and unstable. Whether it is identifying messy nested conditionals or removing unnecessary methods, this book will show various techniques to avoid these pitfalls and write code that is easier to understand, maintain, and test.

By the end of the book, you’ll have learned some of the main causes of unhealthy code, tips to identify them and techniques to address them.

Publication date:
October 2019
Publisher
Packt
Pages
120
ISBN
9781839218040

 

About TypeScript

What Is It?

TypeScript (https://www.typescriptlang.org/) is a superset of JavaScript. That is, it's JavaScript with a bunch of additional features. After you've written your code, it compiles into JavaScript.

TypeScript was created by Microsoft and led by Anders Hejlsberg (who was one of the core members of the group that formed the C# programming language, among others).

TypeScript's primary features and benefits include the following:

  • A fairly advanced type system
  • Support for future and bleeding-edge JavaScript features
  • Fantastic support for developer tooling inside IDEs

What's All the Fuss About?

TypeScript has gained a lot of traction in the past few years. In the 2019 Stack Overflow Developer Survey, TypeScript was rated as the #3 top-loved programming language (https://insights.stackoverflow.com/survey/2019#most-loved-dreaded-and-wanted)!

Why do developers love it so much?

From my own experience, it's because JavaScript (due to its dynamic nature) allows for some strange kinds of code. Also, because it's compiled at runtime, most bugs are discovered at runtime (in certain production scenarios, this can be too late to catch bugs!).

With TypeScript, on the other hand, you can define solid contracts by using types (classes, interfaces, types, implicit method return types, and so on). This enables the IDE you are using to immediately detect certain kinds of bugs as you type your code! It also makes your code more predictable and less error-prone since you have guaranteed method return types, for example.

Note

I remember the first time that I introduced TypeScript into a real-world project – it increased my productivity tons! I discovered bugs that I had no idea existed, either.

TypeScript versus JavaScript

I'd like to make a quick comparison between some vanilla JavaScript and TypeScript to give you an idea of what I've been talking about.

Let's take some valid code in JavaScript:

const myData = getMyData();

How do I know what the getMyData method will return? Will it return an object? A Boolean?

If it does return an object, how can I find out what the properties of the object are?

Other than digging into the source code for that method, I can't.

Inside that method, we could even do something strange, like this:

function getMyData(kind) {
    if(!kind)
        return false;
    else
        return { data: "hi" };
}

So... sometimes, this function returns a Boolean and other times it returns an object?

I've seen code like this in real-world production code bases. And yes – it's very hard to understand, debug, and test and is very prone to errors.

Using TypeScript, you can lock down the return type explicitly:

function getMyData(kind) : object {
    if(!kind)
        return false;
    else
        return { data: "hi" };
}

This would not compile since the method signature says that the method should always return an object, but the code can return a Boolean and an object.

Let's look at another example:

const user = {
    emailAddress: "[email protected]"
};
emailUser(user.emailAddress);
user.emailAddress = 2;
emailUser(user.emailAddress);

The second time we call emailUser, we are passing it a number instead of a string. That's what I mean by strange code.

In TypeScript, this would throw an error at compilation time (and in your IDE as you type).

You would find this issue immediately as you type. However, in JavaScript, you wouldn't know about this until you tried to send an email to a user at runtime.

What if this bug ended up only happening in certain production scenarios? In this case, by using TypeScript, you could avoid this error before you even commit the code in the first place!

Why I Chose TypeScript for This Book

I chose TypeScript as the language to use for this book because it has much in common with dynamic languages such as JavaScript, yet it also has common features from object-oriented type-safe languages such as Java and C#.

It has a good blend of object-oriented tools, functional tools, and the ability to still harness the dynamic nature of JavaScript if needed.

Most of the techniques in this book are generic and can be applied to most other programming languages. TypeScript just happens to be a good middle ground to use to showcase these problems and solutions!

 

What Is Refactoring?

Let's Define It

Refactoring is just a fancy term that means improving your code without changing how it behaves.

If improving the quality of your code introduces more bugs or changes how the system worked before, then is it really improving your code? Nope!

With refactoring, the best approach is to apply small targeted changes to a code base. Instead of making a huge sweeping change to your code, refactoring is better as a long-term, continuous enterprise.

Why? Applying larger changes all at once presents more risk and more time to implement.

We don't want that.

We want to improve the health of our code while maintaining control of our code/software.

Note

It's important to have your code under test (unit, integration, and so on) as this will give you a safety net to ensure any code changes won't also change its behavior and cause bugs.

While we won't look at building tests in this book, it's important to remember the importance of having tests.

Our Approach

I've found that many refactoring resources are hard to follow and easily overwhelming. They also tend to start at the wrong end by telling you what a pattern is before explaining what problem it solves.

Each category/section in this book represents some kind of code smell. A code smell is some indication that a part of your code is rotting and becoming unhealthy.

The first section of each category will introduce how to identify a specific code smell and why it is considered unhealthy. Then, we'll look at techniques that can be used to address the code issue – after we've explored the problem first!

Design Patterns

When learning about design patterns (https://en.wikipedia.org/wiki/Software_design_pattern), it's important to realize that these patterns are a form of refactoring tool.

Design patterns are meant to address issues around the fact that your code is not flexible enough, hard to maintain, and so on.

As you move through this book, the emphasis will be on looking at and solving specific code issues. Some of those issues just happen to be solvable using design patterns!

 

Why Refactor at All?

Slow Development

Ever work in a software system where your business asked you to build a new feature but once you started digging into the existing code, you discovered that it wasn't going to be so easy to implement?

Often, this is because our existing code is not flexible enough to handle the new behaviors the business wants to include in your application.

Why?

Well, sometimes, we take shortcuts and hack stuff in.

Perhaps we don't have the knowledge and skills to know how to write healthy code (this book will help!).

Other times, timelines need to be met at the cost of introducing these shortcuts.

This is why refactoring is so important:

Refactoring can help your currently restrictive code become flexible and easy to extend once again.

Code is like a living organism (https://meltingasphalt.com/a-codebase-is-an-organism/) – like a garden. Sometimes, you just need to get rid of the weeds!

Note

I've been involved in a software project where adding a checkbox to a screen was not possible given the system's setup at the time! Adding a button to a screen took days to figure out! And this was as a senior developer with a good number of years under my belt. Sadly, some systems are just very convoluted and hacked together.

This is what happens when we don't keep our code healthy!

Saving Money

It's a practical reality that you need to meet deadlines and get a functioning product out to customers. This could mean having to take shortcuts from time to time, depending on the context. Bringing value to your customers is what makes money for your company, after all.

In the long term, however, these quick-fixes or shortcuts lead to code that can be rigid, hard to understand, more prone to contain bugs, and so on.

Improving and keeping code quality high leads to the following:

  • Fewer bugs
  • The ability to add new features faster
  • The ability to keep changes to existing code isolated
  • Code that's easier to reason about

All of these benefits lead to less time spent on debugging, fixing problems, developers trying to understand how the code works, and so on.

It saves your company real money!

Navy SEALS Get It

There's an adage that comes from the Navy SEALs that many have noticed also applies to the creation of software:

Slow is smooth. Smooth is fast.

Taking time to build quality code upfront will help your company move faster in the long term. But even then, we don't anticipate all future changes that need to be made to the code and still need to refactor from time to time.

Being a Craftsman

Software development is a critical part of our society.

Developers build code that controls the following:

  • Vehicles
  • Power grids
  • Government secrets
  • Home security
  • Weapons
  • Bank accounts
  • And more!

I'm sure you can think of more cases where the software a developer creates is tied to the security and well-being of an individual or group of people.

Would you expect your doctor to haphazardly prescribe you medication without them carefully ensuring that they know what your medical condition is?

Wouldn't you want to have a vehicle mechanic who takes the time to ensure your vehicle's tires won't fall off while you are driving?

Being a craftsman is just another way of saying that we should be professional and care about our craft.

We should value quality software that will work as intended!

I've had it happen before that my car's axel was replaced and, while I was driving away, the new axel fell right out of my car! Is that the kind of mechanic I can trust my business with? Nope!

Likewise, the quality of software that we build can directly impact people's lives in real ways.

Case Study #1

You might be familiar with an incident from 2018 where a Boeing 737 crashed and killed all people on board.  It was found that Boeing had outsourced its software development to developers who were not experienced in this particular industry.  Also, these developers were having to redo improperly written code over and over again.

It is clear from this example how it can be inefficient and even dangerous when a group of developers are lacking the knowledge or tools to build quality software in such critical systems.

For Boeing in general, what did this overall lack of quality and craftsmanship lead to?

The company's stocks took a huge dip a couple of days after the crash.

Oh, and don't forget – people died. No one can undo or fix this.

After this was all said and done, Boeing did not benefit from cutting costs, trying to rush their software development, and focusing on speed rather than quality.

As software development professionals, we should seek to do our part and value being software craftsmen and craftswomen who focus on creating quality software.

Note

You can find the full article here: https://www.bloomberg.com/news/articles/2019-06-28/boeing-s-737-max-software-outsourced-to-9-an-hour-engineers.

Case Study #2

Do you still think that because airplanes can potentially kill people that the software that's built is going to be quality? Nope.

Here's another example of software quality issues in the aviation field: a $300 million Airbus software bug solved by turning it off and on again every 149 hours (https://gizmodo.com/turn-it-off-and-on-again-every-149-hours-is-a-concernin-1836818094).

Sounds kind of like a memory leak, right? You know, when you have a web application that starts getting slow and clunky after keeping it open for a while? Just refresh the page and voila! Everything's fine again!

Sadly, we are building airplanes like that too.

Quoting the article:

"Airlines who haven't performed a recent software update on certain models of the Airbus A350 are being told they must completely power cycle the aircraft every 149 hours or risk "...partial or total loss of some avionics systems or functions," according to the EASA."

Do you want to fly on those planes?

Quality matters. And the fact is, many developers are not writing quality software.

I hope that this book will help developers get just a little bit better at building quality software.

 

When Should I Refactor?

It's already been mentioned that refactoring is best done in smaller chunks rather than in big sweeping changes.

Again, this avoids riskier and error-prone changes. You can also ship your product to your customers in a more iterative way and get feedback from your users earlier.

Then, the question arises: When should I refactor?

The Boy Scout Rule

There's a programming principle called The Boy Scout Rule (http://www.informit.com/articles/article.aspx?p=1235624&seqNum=6) which states:

"Leave the code cleaner than you found it."

This applies whether you are fixing a bug, adding a new feature, and so on. Just do something that improves the code you are working with.

Note

It could be as simple as adjusting the name of an ambiguous variable name.

It could be reorganizing the structure of your code's files.

It could be introducing design patterns to solve specific issues.

Repetitive Work

Ever run into a situation where you need to write code that you've already written before? Maybe the same code already exists somewhere else in the system?

If you find that you've had to write the same (exact) code over and over, then you might want to consider consolidating that code into a shareable resource.

That way, you don't have to change 12 different files to fix a bug or add a new piece of logic.

Difficulty Adding Features

As we mentioned previously, sometimes, you are faced with the task of adding new features to your code. However, perhaps the existing code is making it really difficult to just add that new feature or behavior.

In these cases, refactoring can help you mold the existing code into a place where it is easy to add new behaviors!

Note

This also applies to architectural issues. However, this book will focus on more code-based issues.

In the End

In the end, refactoring should be a continuous and habitual activity that you have chosen to engage in.

Martin Fowler, on the topic of refactoring (https://www.refactoring.com/), said:

"Refactoring isn't a special task that would show up in a project plan. Done well, it's a regular part of programming activity."

You shouldn't have to ask to refactor. Just do it when it makes sense.

About the Author

  • James Hickey

    With a background in creative arts, philosophy, and software development, James Hickey has been helping developers become software artisans and navigate their careers. He has worked professionally in web and mobile-based projects mentoring development teams and leading business-critical projects. His technical interests focus on software design and architecture.

    Browse publications by this author
Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial