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)

Identification

A Little Bit of This, a Little Bit of That

If you work as a professional software developer, then you must have seen code like this before. Truth be told... we've all written code like this before:

if(user.role === "admin" 
    && user.isActive 
    && user.permissions.some(p => p === "edit")) {
    
    // Do stuff
}

I know you've seen this before – and versions of this that are much worse and more complex!

These long lists of conditionals we find inside our if statements can be called verbose conditionals:

  • They are hard to read.
  • They are hard to understand once you've read them.
  • They are hard to modify.
  • They are hard to test (well... you can't really directly test them at all).

Misbehaving Conditionals

These lengthy conditionals often lead to software that will misbehave and not work the way you would want it to.

More often than not, when we find bugs in these...