Page
1
M A N N I N G Christian Clausen Foreword by Robert C. Martin How and when to refactor
Page
2
Quick overview of refactoring patterns EXTRACT METHOD (P3.2.1)—Takes part of one method and extracts it into its own method. REPLACE TYPE CODE WITH CLASSES (P4.1.3)—Transforms an enum into an inter- face, and the enums’ values become classes. PUSH CODE INTO CLASSES (P4.1.5)—Is a natural continuation of REPLACE TYPE CODE WITH CLASSES (P4.1.3), as it moves functionality into classes. INLINE METHOD (P4.1.7)—Removes methods that no longer add readability to our program. SPECIALIZE METHOD (P4.2.2)—Removes unnecessary and problematic general- ity from methods. TRY DELETE THEN COMPILE (P4.5.1)—Removes unused methods from interfaces and classes when we know their entire scope. UNIFY SIMILAR CLASSES (P5.1.1)—Unifies two or more classes that differ from each other in a set of constant methods. COMBINE ifS (P5.2.1)—Reduces duplication by joining consecutive ifs that have identical bodies. INTRODUCE STRATEGY PATTERN (P5.4.2)—Replaces variance through if by instead instantiating classes. EXTRACT INTERFACE FROM IMPLEMENTATION (P5.4.4)—Replaces dependencies on a class with an interface. ELIMINATE GETTER OR SETTER (P6.1.3)—Eliminates getters and setters by mov- ing the functionality closer to the data. ENCAPSULATE DATA (P6.2.3)—Localizes invariants related to variables and makes cohesion clearer. ENFORCE SEQUENCE (P6.4.1)—Makes the compiler guarantee things happen in a specific order.
Page
4
(This page has no text content)
Page
5
Five Lines of Code HOW AND WHEN TO REFACTOR CHRISTIAN CLAUSEN FOREWORD BY ROBERT C. MARTIN MANN I NG SHELTER ISLAND
Page
6
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2021 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Development editor: Helen Stergius Technical development editor: Mark Elston Manning Publications Co. Review editor: Mihaela Batinić 20 Baldwin Road Production editor: Keri Hales PO Box 761 Copy editor: Tiffany Taylor Shelter Island, NY 11964 Proofreader: Katie Tennant Technical proofreader: Jean François Morin Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617298318 Printed in the United States of America
Page
7
To my university mentors, who told me The key to being consistently brilliant is hard work every day. —Olivier Danvy and You’re missing the point. —Mayer Goldberg Thank you for teaching me to stop trying to do the right thing, and do the right thing.
Page
8
(This page has no text content)
Page
9
brief contents 1 ■ Refactoring refactoring 1 2 ■ Looking under the hood of refactoring 13 PART 1 LEARN BY REFACTORING A COMPUTER GAME ................21 3 ■ Shatter long functions 23 4 ■ Make type codes work 44 5 ■ Fuse similar code together 84 6 ■ Defend the data 135 PART 2 TAKING WHAT YOU HAVE LEARNED INTO THE REAL WORLD . .....................................................171 7 ■ Collaborate with the compiler 173 8 ■ Stay away from comments 194 9 ■ Love deleting code 200 10 ■ Never be afraid to add code 221 11 ■ Follow the structure in the code 235 12 ■ Avoid optimizations and generality 254 13 ■ Make bad code look bad 270 14 ■ Wrapping up 285vii
Page
10
(This page has no text content)
Page
11
contents foreword xvii preface xix acknowledgments xxiii about the author xxv about the cover illustration xxvi 1 Refactoring refactoring 1 1.1 What is refactoring? 2 1.2 Skills: What to refactor? 3 An example code smell 4 ■ An example rule 4 1.3 Culture: When to refactor? 5 Refactoring in a legacy system 6 ■ When should you not refactor? 6 1.4 Tools: How to refactor (safely) 7 1.5 Tools you need to get started 7 Programming language: TypeScript 8 ■ Editor: Visual Studio Code 8 ■ Version control: Git 9 1.6 Overarching example: A 2D puzzle game 9 Practice makes perfect: A second codebase 11 1.7 A note on real-world software 11ix
Page
12
CONTENTSx2 Looking under the hood of refactoring 13 2.1 Improving readability and maintainability 13 Making code better 14 ■ Maintaining code . . . without changing what it does 16 2.2 Gaining speed, flexibility, and stability 17 Favoring composition over inheritance 17 ■ Changing code by addition rather than modification 18 2.3 Refactoring and your daily work 19 Refactoring as a method for learning 19 2.4 Defining the “domain” in a software context 20 PART 1 LEARN BY REFACTORING A COMPUTER GAME ......21 3 Shatter long functions 23 3.1 Establishing our first rule: Why five lines? 24 Rule: FIVE LINES 24 3.2 Introducing a refactoring pattern to break up functions 27 Refactoring pattern: EXTRACT METHOD 31 3.3 Breaking up functions to balancing abstraction 35 Rule: EITHER CALL OR PASS 35 ■ Applying the rule 36 3.4 Properties of a good function name 37 3.5 Breaking up functions that are doing too much 39 Rule: IF ONLY AT THE START 40 ■ Applying the rule 41 4 Make type codes work 44 4.1 Refactoring a simple if statement 45 Rule: NEVER USE IF WITH ELSE 45 ■ Applying the rule 47 Refactoring pattern: REPLACE TYPE CODE WITH CLASSES 49 Pushing code into classes 52 ■ Refactoring pattern: PUSH CODE INTO CLASSES 54 ■ Inlining a superfluous method 58 Refactoring pattern: INLINE METHOD 59 4.2 Refactoring a large if statement 62 Removing generality 65 ■ Refactoring pattern: SPECIALIZE METHOD 67 ■ The only switch allowed 69 ■ Rule: NEVER USE SWITCH 71 ■ Eliminating the if 72
Page
13
CONTENTS xi4.3 Addressing code duplication 74 Couldn’t we use an abstract class instead of the interface? 76 Rule: ONLY INHERIT FROM INTERFACES 77 ■ What is up with all this code duplication? 78 4.4 Refactoring a pair of complex if statements 78 4.5 Removing dead code 81 Refactoring pattern: TRY DELETE THEN COMPILE 82 5 Fuse similar code together 84 5.1 Unifying similar classes 85 Refactoring pattern: UNIFY SIMILAR CLASSES 93 5.2 Unifying simple conditions 99 Refactoring pattern: COMBINE IFS 101 5.3 Unifying complex conditions 103 Using arithmetic rules for conditions 104 ■ Rule: USE PURE CONDITIONS 104 ■ Applying condition arithmetic 107 5.4 Unifying code across classes 108 Introducing UML class diagrams to depict class relations 113 Refactoring pattern: INTRODUCE STRATEGY PATTERN 115 Rule: NO INTERFACE WITH ONLY ONE IMPLEMENTATION 122 Refactoring pattern: EXTRACT INTERFACE FROM IMPLEMENTATION 123 5.5 Unifying similar functions 126 5.6 Unifying similar code 129 6 Defend the data 135 6.1 Encapsulating without getters 136 Rule: DO NOT USE GETTERS OR SETTERS 136 ■ Applying the rule 138 ■ Refactoring pattern: ELIMINATE GETTER OR SETTER 140 ■ Eliminating the final getter 142 6.2 Encapsulating simple data 146 Rule: NEVER HAVE COMMON AFFIXES 146 ■ Applying the rule 147 ■ Refactoring pattern: ENCAPSULATE DATA 152 6.3 Encapsulating complex data 155 6.4 Eliminating a sequence invariant 162 Refactoring pattern: ENFORCE SEQUENCE 163
Page
14
CONTENTSxii6.5 Eliminating enums another way 165 Enumeration through private constructors 166 ■ Remapping numbers to classes 167 PART 2 TAKING WHAT YOU HAVE LEARNED INTO THE REAL WORLD ............................................171 7 Collaborate with the compiler 173 7.1 Getting to know the compiler 174 Weakness: The halting problem limits compile-time knowledge 174 Strength: Reachability ensures that methods return 175 ■ Strength: Definite assignment prevents accessing uninitialized variables 176 Strength: Access control helps encapsulate data 176 ■ Strength: Type checking proves properties 177 ■ Weakness: Dereferencing null crashes our application 178 ■ Weakness: Arithmetic errors cause overflows or crashes 178 ■ Weakness: Out-of-bounds errors crash our application 179 ■ Weakness: Infinite loops stall our application 179 ■ Weakness: Deadlocks and race conditions cause unintended behavior 180 7.2 Using the compiler 181 Making the compiler work 182 ■ Don’t fight the compiler 184 7.3 Trusting the compiler 189 Teach the compiler invariants 190 ■ Pay attention to warnings 192 7.4 Trusting the compiler exclusively 192 8 Stay away from comments 194 8.1 Deleting outdated comments 196 8.2 Deleting commented-out code 196 8.3 Deleting trivial comments 197 8.4 Transforming comments into method names 197 Using comments for planning 198 8.5 Keeping invariant-documenting comments 198 Invariants in the process 199
Page
15
CONTENTS xiii9 Love deleting code 200 9.1 Deleting code may be the next frontier 201 9.2 Deleting code to get rid of incidental complexity 202 Technical ignorance from inexperience 202 ■ Technical waste from time pressure 203 ■ Technical debt from circumstances 204 Technical drag from growing 204 9.3 Categorizing code based on intimacy 205 9.4 Deleting code in a legacy system 205 Using the strangler fig pattern to get insight 206 ■ Using the strangler fig pattern to improve the code 208 9.5 Deleting code from a frozen project 209 Making the desired outcome the default 209 ■ Minimizing waste with spike and stabilize 209 9.6 Deleting branches in version control 210 Minimizing waste by enforcing a branch limit 211 9.7 Deleting code documentation 212 Algorithm to determine how to codify knowledge 212 9.8 Deleting testing code 213 Deleting optimistic tests 213 ■ Deleting pessimistic tests 213 Fixing or deleting flaky tests 213 ■ Refactoring the code to get rid of complicated tests 214 ■ Specializing tests to speed them up 214 9.9 Deleting configuration code 215 Scoping configuration in time 215 9.10 Deleting code to get rid of libraries 216 Limiting our reliance on external libraries 218 9.11 Deleting code from working features 219 10 Never be afraid to add code 221 10.1 Accepting uncertainty: Enter the danger 222 10.2 Using spikes to overcome the fear of building the wrong thing 222 10.3 Overcoming the fear of waste or risk with a fixed ratio 223 10.4 Overcoming the fear of imperfection by embracing gradual improvement 225 10.5 How copy and paste effects change velocity 225
Page
16
CONTENTSxiv10.6 Modification by addition through extensibility 226 10.7 Modification by addition enables backward compatibility 227 10.8 Modification by addition through feature toggles 229 10.9 Modification by addition through branch by abstraction 232 11 Follow the structure in the code 235 11.1 Categorizing structure based on scope and origin 236 11.2 Three ways that code mirrors behavior 237 Expressing behavior in the control flow 237 ■ Expressing behavior in the structure of the data 239 ■ Expressing behavior in the data 242 11.3 Adding code to expose structure 243 11.4 Observing instead of predicting, and using empirical techniques 244 11.5 Gaining safety without understanding the code 245 Gaining safety through testing 245 ■ Gaining safety through mastery 245 ■ Gaining safety through tool assistance 246 Gaining safety through formal verification 246 ■ Gaining safety through fault tolerance 246 11.6 Identifying unexploited structures 246 Exploiting whitespace with extraction and encapsulation 247 Exploiting duplication with unification 248 ■ Exploiting common affixes with encapsulation 251 ■ Exploiting the runtime type with dynamic dispatch 252 12 Avoid optimizations and generality 254 12.1 Striving for simplicity 255 12.2 When and how to generalize 257 Building minimally to avoid generality 257 ■ Unifying things of similar stability 258 ■ Eliminating unnecessary generality 258 12.3 When and how to optimize 258 Refactoring before optimizing 259 ■ Optimizing according to the theory of constraints 261 ■ Guiding optimization with metrics 263 ■ Choosing good algorithms and data structures 264 Using caching 265 ■ Isolating optimized code 267
Page
17
CONTENTS xv13 Make bad code look bad 270 13.1 Signaling process issues with bad code 271 13.2 Segregating into pristine and legacy code 272 The broken window theory 272 13.3 Approaches to defining bad code 273 The rules in this book: Simple and concrete 273 ■ Code smells: Complete and abstract 273 ■ Cyclomatic complexity: Algorithmic (objective) 274 ■ Cognitive complexity: Algorithmic (subjective) 275 13.4 Rules for safely vandalizing code 275 13.5 Methods for safely vandalizing code 276 Using enums 276 ■ Using ints and strings as type codes 277 Putting magic numbers in the code 277 ■ Adding comments to the code 278 ■ Putting whitespace in the code 279 ■ Grouping things based on naming 279 ■ Adding context to names 280 Creating long methods 281 ■ Giving methods many parameters 282 ■ Using getters and setters 283 14 Wrapping up 285 14.1 Reflecting on the journey of this book 285 Introduction: Motivation 286 ■ Part 1: Making it concrete 286 Part 2: Widening the horizon 286 14.2 Exploring the underlying philosophy 286 Searching for ever-smaller steps 286 ■ Searching for the underlying structure 287 ■ Using the rules for collaboration 288 Prioritizing the team over individuals 288 ■ Prioritize simplicity over completeness 288 ■ Using objects or higher-order functions 289 14.3 Where to go from here? 290 Micro-architecture route 290 ■ Macro-architecture route 290 Software quality route 291 appendix Installing the tools for part 1 293 index 297
Page
18
(This page has no text content)
Page
19
foreword Have you ever read a book on software and thought that the author was talking over your head? Did the book use unfamiliar vocabulary and overly complex concepts to make its points? Did it make you feel as though it was written for some elite inner cir- cle of know-it-alls that didn’t include you? This is not that book. This book is down to earth, focused, and right on point. Neither is this book a primer. It doesn’t start at the atom and bore you with the basics of programming and languages. It doesn’t try to coddle you and keep you safe. I guarantee that this book will challenge you. But it will challenge you without intimi- dating you and without insulting your intelligence. Refactoring is the discipline of transforming bad code into good code without breaking it. When we consider that our entire civilization now depends on software for its further existence, it seems unlikely that there is a topic more worthy of study. Perhaps you think that’s hyperbolic. It’s not. Look around you. How many pro- cessors running software are currently on your body? Your watch, your phone, your car keys, your headphones . . . how many are within 30 meters of you? Your microwave, your stove, your dishwasher, your thermostat, your clothes washer . . . and how about your car? These days, nothing happens in our society without software. You can’t buy or sell anything, or drive or fly anywhere, or cook a hot dog, or watch TV, or call some- one on the phone without software.xvii
Page
20
FOREWORDxviii And how much of that software is actually good code? Think of the systems you are working on right now. Are they clean? Or are they, like most, a mess in desper- ate need of refactoring? This book does not present the kind of sterile and simplistic refactoring you may have heard or read about before. This book talks about real refactoring. Refac- toring in real projects. Refactoring in legacy systems. Refactoring in the kinds of environments that we all face virtually every day. What’s more, this book won’t make you feel guilty for not having automated tests. The author realizes that most inherited systems grew and evolved over time, and we are not so fortunate as to have such test suites. This book lays down a set of simple rules that you can follow to reliably refactor complex, messy, tangled, untested systems. By learning and following these rules, you can make a real difference in the quality of the systems you maintain. Don’t get me wrong—it’s not a silver bullet. Refactoring old, crufty, untested code is never easy. But armed with the rules and examples in this book, you will be able to make inroads against the cruft and tangle of systems that have bedeviled you for too long. So I advise you to read this book carefully. Study the examples. Think hard about the abstractions and intentions the author presents. Get the codebase he offers, and refactor it along with him. Follow his refactoring journey from beginning to end. It will take time. It will be frustrating. It will challenge you. But you’ll come out the other side with a set of skills that will serve you well for the rest of your career. You’ll also come out with a new intuition and understanding of what separates good code from bad code, and just what it is that makes code clean. —Robert C. Martin (aka Uncle Bob)