Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
$9.99 | ALL EBOOKS & VIDEOS
Over 7,000 tech titles at $9.99 each with AI-powered learning assistants on new releases
Refactoring TypeScript
Refactoring TypeScript

Refactoring TypeScript: Keeping your code healthy

By James Hickey
$20.99 $9.99
Book Oct 2019 120 pages 1st Edition
eBook
$20.99 $9.99
Print
$69.99
Subscription
$15.99 Monthly
eBook
$20.99 $9.99
Print
$69.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Refactoring TypeScript

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: "test@test.com"
};
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.

Left arrow icon Right arrow icon

Key benefits

  • Learn all about refactoring - why it is important and how to do it
  • Discover easy ways to refactor code with examples
  • Explore techniques that can be applied to most other programming languages

Description

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.

What you will learn

Spot and fix common code smells to create code that is easier to read and understand Discover ways to identify long methods and refactor them Create objects that keep your code flexible, maintainable, and testable Apply the Single Responsibility Principle to develop less-coupled code Discover how to combine different refactoring techniques Learn ways to solve the issues caused by overusing primitives

Product Details

Country selected

Publication date : Oct 18, 2019
Length 120 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781839218040
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Oct 18, 2019
Length 120 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781839218040
Category :

Table of Contents

11 Chapters
Preface Chevron down icon Chevron up icon
1. Introduction Chevron down icon Chevron up icon
2. Null Checks Everywhere! Chevron down icon Chevron up icon
3. Wordy Conditionals Chevron down icon Chevron up icon
4. Nested Conditionals Chevron down icon Chevron up icon
5. Primitive Overuse Chevron down icon Chevron up icon
6. Lengthy Method Signatures Chevron down icon Chevron up icon
7. Methods That Never End Chevron down icon Chevron up icon
8. Dumping Grounds Chevron down icon Chevron up icon
9. Messy Object Creation Chevron down icon Chevron up icon
10. Conclusion Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.