Book Image

Refactoring TypeScript

By : James Hickey
Book Image

Refactoring TypeScript

By: James Hickey

Overview of 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.
Table of Contents (11 chapters)

Null Object Pattern

Empty Collections

Imagine you work for a company that writes software for dealing with legal cases.

As you are working on a feature, you discover some code:

const legalCases: LegalCase[] = await fetchCasesFromAPI();
for (const legalCase of legalCases) {
    if(legalCase.documents != null) {
        uploadDocuments(legalCase.documents);
    }
}

Remember that we should be wary of null checks? What if some other part of the code forgot to check for a null array?

The Null Object pattern can help: you create an object that represents an empty or null object.

Fixing It Up

Let's look at the fetchCasesFromAPI() method. We'll apply a version of this pattern that's a very common practice in JavaScript and TypeScript when dealing with arrays:

const fetchCasesFromAPI = async function() {
    const legalCases: LegalCase[] = await $http.get('legal-cases/');
    for (const legalCase of legalCases) {
        // Null Object Pattern...