Refactoring TypeScript

Keeping your code healthy

James Hickey Refactoring TypeScript Copyright © 2019 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Author: James Hickey Managing Editor: Aritro Ghosh Acquisitions Editor: Karan Wadekar Production Editor: Salma Patel Editorial Board: Shubhopriya Banerjee, Bharat Botle, Ewan Buckingham, Megan Carlisle, Simon Cox, Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Dominic Pereira, Shiny Poojary, Abhishek Rane, Erol Staveley, Ankita Thakur, and Jonathan Wray First Published: October 2019 Production Reference: 1181019 ISBN: 978-1-83921-804-0 Published by Packt Publishing Ltd. Livery Place, 35 Livery Street Birmingham B3 2PB, UK Table of Contents

Preface i

Chapter 1: Introduction 1

About TypeScript ...... 1 What Is It? ...... 1 What's All the Fuss About? ...... 2 TypeScript versus JavaScript ...... 2 Why I Chose TypeScript for This Book ...... 4 What Is Refactoring? ...... 4 Let's Defne It ...... 4 Our Approach ...... 5 Design Patterns ...... 5 Why Refactor at All? ...... 5 Slow Development ...... 5 Saving Money ...... 6 Navy SEALS Get It ...... 6 Being a Craftsman ...... 7 Case Study #1 ...... 7 Case Study #2 ...... 8 When Should I Refactor? ...... 9 The Boy Scout Rule ...... 9 Repetitive Work ...... 9 Difculty Adding Features ...... 9 In the End ...... 10 Chapter 2: Null Checks Everywhere! 13

Identifcation ...... 13 Billion-Dollar Mistake ...... 13 Example ...... 14 Is It That Bad? ...... 15 Non-Nullable Types ...... 15 ...... 16 Empty Collections ...... 16 Fixing It Up ...... 16 Take 2 ...... 17 What About Objects? ...... 17 Special Case Pattern ...... 19 Situation ...... 19 An Order Class That Needs to Be Refactored ...... 19 Refactoring the Order Class ...... 20

Chapter 3: Wordy Conditionals 23

Identifcation ...... 23 A Little Bit of This, a Little Bit of That ...... 23 Misbehaving Conditionals ...... 24 Combining Conditionals ...... 24 Situation ...... 24 The Code ...... 25 Guideline ...... 25 Extracting Methods from Conditionals ...... 26 What's Wrong Here? ...... 26 The Fix ...... 26 Extracting Conditional Logic to Explicit Classes ...... 27 Let's Get Classy ...... 27 SRP ...... 28 Using It ...... 28 Pipe Classes ...... 29 Your Classes Might Be Doing Too Much...... 29 Piping Our Logic ...... 29 Bonus Refactor ...... 31

Chapter 4: Nested Conditionals 33

Identifcation ...... 33 A Monster ...... 33 A Closer Look ...... 34 Guard Clauses ...... 34 Scenario ...... 34 Fail Fast ...... 34 Fixing It Up ...... 35 Gate Classes ...... 36 Scenario ...... 37 Gate Classes to the Rescue ...... 37 Useful for Web APIs ...... 38

Chapter 5: Primitive Overuse 41

Identifcation ...... 41 What's Wrong Here? ...... 42 Value Objects ...... 42 Scenario ...... 42 Initial Refactor ...... 43 Addressing Primitives ...... 44 Creating Our Object ...... 44 Moving Along ...... 45 Immediate Validation ...... 46 Deceptive Booleans ...... 47 Scenario ...... 47 New Business Rules ...... 48 More Rules...... 49 Is It Really That Bad? ...... 50 Just Use Enums ...... 50 Strategy Pattern ...... 52

Chapter 6: Lengthy Method Signatures 55

Identifcation ...... 55 The Slippery Slope of Optional Parameters ...... 56 The Issue ...... 56 Guidelines ...... 57 Creating a Reusable Private Method ...... 57 A Simple Example ...... 58 Creating Semantically Meaningful Methods ...... 59 A Brief Look at Some Advanced Solutions ...... 60 Extracting Data Objects ...... 61 Extraction ...... 62

Chapter 7: Methods That Never End 65

Identifcation ...... 65 When Is a Method Too Long? ...... 67 Give It a Name ...... 67 Being Strategic ...... 70 Chapter 8: Dumping Grounds 75

Identifcation ...... 75 Object-Oriented? ...... 76 The Great Debate ...... 76 Coupling ...... 78 Warning Sign ...... 79 One of These Things Is Not Like The Others ...... 79 You Have Mail ...... 80 Breaking It Up ...... 80 Keep Separate Things Separate ...... 82 Speak or Listen ...... 83 CQRS ...... 83 Read and Write ...... 83 Next Steps ...... 85 Commands ...... 86 Queries ...... 86 Conclusion ...... 87 A Word of Caution ...... 87

Chapter 9: Messy Object Creation 89

Identifcation ...... 89 Factory Functions ...... 90 Functions versus Static Methods ...... 91 Combining Refactoring Techniques ...... 92 Complexity Remains...... 94 Building It ...... 95 The Builder Pattern ...... 96 One Last Improvement ...... 96 Chapter 10: Conclusion 99

This Is Just The Beginning! ...... 99

Index 103

> Preface

About

This section briefy introduces the author and the coverage of this book. ii | Preface

About the 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 implementing 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 you 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.

About the Author With a background in creative arts, philosophy, and 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 and architecture.

Learning Objectives • Spot and fx 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 fexible, 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

Audience This book is designed for programmers who are looking to explore various refactoring techniques to develop healthy and maintainable code. Some experience in JavaScript and TypeScript can help you easily grasp the concepts explained in this book. About the Book | iii

Approach Each section in this book represents a ''. A code smell is an indication that a part of your code is rotting and becoming unhealthy. The frst chapter of each section will introduce how to identify a specifc code smell and why it is considered unhealthy. Then, you'll learn techniques that can be used to address the code issue - once you've explored the problem.

1 Introduction

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# , among others).