Page
1
(This page has no text content)
Page
2
99 Bottles of OOP Metz, Sandi;Owen, Katrina;Stankus, TJ Table of Contents Colophon Your Rights As A Reader Dedication Preface What This Book Is About Who Should Read This Book Before You Read This Book How To Read This Book Code Examples Errata About the Authors About the Translators Introduction 1. Rediscovering Simplicity 1.1. Simplifying Code 1.1.1. Incomprehensibly Concise Consistency Duplication Names 1.1.2. Speculatively General
Page
3
1.1.3. Concretely Abstract 1.1.4. Shameless Green 1.2. Judging Code 1.2.1. Evaluating Code Based on Opinion 1.2.2. Evaluating Code Based on Facts Source Lines of Code Cyclomatic Complexity Assignments, Branches and Conditions (ABC) Metric 1.2.3. Comparing Solutions 1.3. Summary 2. Test Driving Shameless Green 2.1. Understanding Testing 2.2. Writing the First Test 2.3. Removing Duplication 2.4. Tolerating Duplication 2.5. Hewing to the Plan 2.6. Exposing Responsibilities 2.7. Choosing Names 2.8. Revealing Intentions 2.9. Writing Cost-Eective Tests 2.10. Avoiding the Echo-Chamber 2.11. Considering Options 2.12. Summary 3. Unearthing Concepts 3.1. Listening to Change
Page
4
3.2. Starting With the Open/Closed Principle 3.3. Recognizing Code Smells 3.4. Identifying the Best Point of Attack 3.5. Refactoring Systematically 3.6. Following the Flocking Rules 3.7. Converging on Abstractions 3.7.1. Focusing on Dierence 3.7.2. Simplifying Hard Problems 3.7.3. Naming Concepts 3.7.4. Making Methodical Transformations 3.7.5. Refactoring Gradually 3.8. Summary 4. Practicing Horizontal Refactoring 4.1. Replacing Dierence With Sameness 4.2. Equivocating About Names 4.3. Deriving Names From Responsibilities 4.4. Choosing Meaningful Defaults 4.5. Seeking Stable Landing Points 4.6. Obeying the Liskov Substitution Principle 4.7. Taking Bigger Steps 4.8. Discovering Deeper Abstractions 4.9. Depending on Abstractions 4.10. Summary 5. Separating Responsibilities 5.1. Selecting the Target Code Smell
Page
5
5.1.1. Identifying Patterns in Code 5.1.2. Spotting Common Qualities 5.1.3. Enumerating Flocked Method Commonalities 5.1.4. Insisting Upon Messages 5.2. Extracting Classes 5.2.1. Modeling Abstractions 5.2.2. Naming Classes 5.2.3. Extracting BottleNumber 5.2.4. Removing Arguments 5.2.5. Trusting the Process 5.3. Appreciating Immutability 5.4. Assuming Fast Enough 5.5. Creating BottleNumbers 5.6. Recognizing Liskov Violations 5.7. Summary 6. Achieving Openness 6.1. Consolidating Data Clumps 6.2. Making Sense of Conditionals 6.3. Replacing Conditionals with Polymorphism 6.3.1. Dismembering Conditionals 6.3.2. Manufacturing Objects 6.3.3. Prevailing with Polymorphism 6.4. Transitioning Between Types 6.5. Making the Easy Change 6.6. Defending the Domain
Page
6
6.7. Summary 7. Manufacturing Intelligence 7.1. Contrasting the Concrete Factory with Shameless Green 7.2. Fathoming Factories 7.3. Opening the Factory 7.4. Supporting Arbitrary Class Names 7.5. Dispersing The Choosing Logic 7.6. Self-registering Candidates 7.7. Auto-registering Candidates 7.8. Summary 8. Developing a Programming Aesthetic 8.1. Appreciating the Mechanical Process 8.2. Clarifying Responsibilities with Pseudocode 8.3. Extracting the Verse 8.4. Coding by Wishful Thinking 8.5. Inverting Dependencies 8.5.1. Injecting Dependencies 8.5.2. Isolating Variants 8.5.3. Grappling with Inversion 8.6. Obeying the Law of Demeter 8.6.1. Understanding the Law 8.6.2. Curing Demeter Violations 8.7. Identifying What The Verse Method Wants 8.8. Pushing Object Creation to the Edge 8.9. Summary
Page
7
9. Reaping the Benets of Design 9.1. Choosing Which Units to Test 9.1.1. Contrasting Unit and Integration Tests 9.1.2. Foregoing Tests 9.2. Reorganizing Tests 9.2.1. Gathering BottleVerse Tests 9.2.2. Revealing Intent 9.3. Seeking Context Independence 9.3.1. Examining Bottles' Responsibilities 9.3.2. Purifying Tests With Fakes 9.3.3. Purging Redundant Tests 9.3.4. Proting from Loose Coupling 9.4. Communicating With the Future 9.4.1. Enriching Code with Signals 9.4.2. Verifying Roles 9.4.3. Obliterating Obsolete Context 9.5. Summary Afterword Appendix A: Initial Exercise Getting the exercise Doing the exercise Test Suite References Acknowledgements
Page
8
Colophon Version: 2.1.1 Version Date: 21-01-20 Published By: Potato Canyon Software, LLC 2nd Edition Copyright: 2021 Cover Design and Art by Lindsey Morris. Edited by Julia Trimmer. Created using Asciidoctor. Ruby Logo: Attribution-ShareAlike 2.5 Generic (CC BY-SA 2.5)
Page
9
Your Rights As A Reader Thank you for buying 99 Bottles of OOP. As the authors of a self- published book, we very much appreciate your purchase. This book is chock-full of lessons, and readers often write asking if they can share them with others. We commend your desire to pass on what you’ve learned, and ask only that while doing so you respect our rights as authors. This means that while we encourage you to spread the underlying ideas of the book, we restrict your use of its actual content (the specific examples, explanations, and descriptions). Our bargain with you is as follows: 1. Your purchase entitles you to a single, non-transferable license for your personal use of the ebook related files. You may read and download the ebook you purchased to your personal devices only. You may not: Sell the book Give it away Distribute it in any way Print it (except for your personal use) 2. You may use 99 Bottles of OOP as curriculum in a public education setting (university, code school, secondary school) as long as every student buys or is provided with a legal copy of the book.
Page
10
Volume discounts are available, and there’s a free-book-for-a- postcard program. Contact human@99bottlesbook.com for information about bulk purchases. 3. You may share one small section (a chapter or less) at a free, public meet-up as long as the material is properly attributed. 4. You may not teach a course based on the entire book, even if this course is free and open to the public. 5. You may not use any part of 99 Bottles of OOP in any endeavor in which you charge for your services.
Page
11
Dedication Sandi To Amy, for everything she is and does, and to Jasper, who taught me that nothing trumps a good walk. Katrina To Sander, whose persistence is out of this world. TJ To those who have encouraged me, especially my parents and teachers. And to Graylyn, who I try to encourage most.
Page
12
Preface It turns out that everything you need to know about Object- Oriented Design (OOD) can be learned from the "99 Bottles of Beer" song. Well, perhaps not everything, but quite certainly a great many things. The song is simultaneously easy to understand and full of hidden complexity, which makes it the perfect skeleton upon which to hang lessons in OOD. The lessons embedded within the song are so useful, and so broad, that over the last three years it has become a core part of the curriculum of Sandi Metz’s Practical Object-Oriented Design course. The thoughts in this book reflect countless hours of discussion and collaboration between Sandi, Katrina Owen, and TJ Stankus. These ideas have been battle-tested by hundreds of students, and refined by a series of deeply thoughtful co-instructors, beginning with Katrina. While none of the authors have the hubris to claim perfect understanding, all have learned a great deal about Object-Oriented Design from teaching this song, and feel compelled to write it all down. Therefore, this book, now in its second edition. We hope that you find it both useful and enjoyable. What This Book Is About
Page
13
This book is about writing cost-effective, maintainable, and pleasing code. Chapter 1 explores how to decide if code is "good enough." This chapter uses metrics to compare several possible solutions to the 99 Bottles problem. It introduces a type of solution known as Shameless Green, and argues that although Shameless Green is neither clever nor changeable, it is the best initial solution to many problems. Chapter 2 is a primer for Test-Driven Development (TDD), which is used to find Shameless Green. This chapter is concerned with deciding what to test, and with creating tests that happily tolerate changes to the underlying code. Chapter 3 introduces a new requirement (six-pack), which leads to a discussion of how to decide where to start when changing code. This chapter examines the Open/Closed Principle, and then explores code smells. The chapter then defines a simple set of Flocking Rules, which guide a step-by-step refactoring of code. Chapter 4 continues the step-by-step refactoring begun in Chapter 3. It iteratively applies the Flocking Rules, eventually stumbles across the need for the Liskov Substitution Principle, and ultimately unearths a deeply hidden abstraction. Chapter 5 inventories the existing code for smells, chooses the most prominent one, and uses it to trigger the creation of a new class. Along the way, it takes a hard look at immutability, performance, and caching.
Page
14
Chapter 6 performs a miracle that not only removes the conditionals, but also allows you to finally implement the new six-pack requirement without altering existing code. Chapter 7 examines the tradeoffs along a continuum of six different styles of Factories. It begins by exploring a simple, hard- coded conditional, and ends with a factory whose candidate objects both self-register, and also supply the logic needed to choose them. Chapter 8 introduces another new requirement—to vary the lyrics. It uses this requirement to introduce the idea of a programming aesthetic, or set of rules to guide you in times of uncertainty. The chapter ends with a list of specific suggestions for deciding when it’s worthwhile to voluntarily improve code. Chapter 9 comes full circle and returns to testing. It takes advantage of the improved design to write better tests, and then uses the new tests as a spur to improve the final design. Who Should Read This Book The lessons in the book have been found useful by programmers with a broad range of experience, from rank novice through grizzled veteran. Despite what one might predict, novices often have an easier time with this material. As they are unencumbered by prior knowledge, their minds are open, and easily absorb these ideas. It’s the veterans who struggle. Their habits are deeply ingrained. They know themselves to be good at programming. They feel
Page
15
quick, and efficient, and so resist new techniques, especially when those techniques temporarily slow them down. This book will be useful if you are a veteran, but it cannot be denied that it teaches programming techniques that likely contradict your current practice. Changing entrenched ideas can be painful. However, you cannot make informed decisions about the value of new ideas unless you thoroughly understand them, and to understand them you must commit, wholeheartedly, to learning them. Therefore, if you are a veteran, it’s best to adopt the novice mindset before reading on. Set aside prior beliefs, and dedicate yourself to what follows. While reading, resist the urge to resist. Read the entire book, work the problems, and only then decide whether to integrate these ideas into your daily practice. Before You Read This Book You’ll learn more from this book if you spend 30 minutes working on the "99 Bottles of Beer" problem before starting to read. See the appendix for instructions. If you just want to read on but you don’t know Ruby, have no fear. Your purchase of this book entitles you to all variants (Ruby, Javascript, and PHP), and each language variant comes in beer and milk flavors. Every combination of variant and flavor was available for download during your purchase, and one of them should suit. Regardless of which version you read, be assured that this book is not about any specific language or beverage; it’s about object-
Page
16
oriented programming and design. The technical content of every version is essentially the same. How To Read This Book The chapters build upon one another, and so should be read in order. While isolated sections may be useful, the whole is more than the sum of its parts. The ideas gain power in relation to one another. To get the most from the book, work the code samples as you read along. With active participation, you’ll learn more, understand better, and retain longer. While reading has value, doing has more. Code Examples The code examples in this version of the book are written in ruby. The source code shown in the book is on GitHub. The majority of code listings are extracted from this repository; and for those, the listing numbers link to the associated code in the repo. The exercises rely on Minitest. Errata A current list of errata is located at sandimetz.com/99bottles- errata. If you find additional errors, please email them to errata@99bottlesbook.com. About the Authors
Page
17
Sandi Metz Sandi is the author of Practical Object-Oriented Design in Ruby. She has thirty years of experience working on large object- oriented applications. She’s spoken about programming, object- oriented design and refactoring at numerous conferences including Agile Alliance Technical Conference, Craft Conf, Øredev, RailsConf, and RubyConf. She believes in simple code and straightforward explanations, and is the proud recipient of a Ruby Hero award for her contribution to the Ruby community. She prefers working software, practical solutions and lengthy bicycle trips (not necessarily in that order). Find out more about Sandi at sandimetz.com. Katrina Owen Katrina works for GitHub as an Advocate on the Open Source team. Katrina has ten years of experience and works primarily in Go and Ruby. She is the creator of exercism.io, a platform for programming skill development in more than 30 languages. She’s spoken about refactoring and open source at international conferences such as NordicRuby, Mix-IT, Software Craftsmanship North America, OSCON, Bath Ruby and RailsConf. She received a Ruby Hero award for her contribution to the Ruby community. When programming, her focus is on automation, workflow optimization, and refactoring. Find out more about Katrina at kytrinyx.com. TJ Stankus TJ works as a software developer for boldfacet LLC and co- instructs software design courses with Sandi. He began his
Page
18
programming career over 20 years ago by accident. By hacking together WordPerfect macros to streamline his job as a proofreader, he discovered he loved programming as much as any creative activity he’d ever pursued. He has worked in mobile applications and back-end web development. He even wrote an SMTP server back when that seemed like a good idea. Today, he works primarily with Elixir and Ruby. His main interests lie not in specific programming languages, but in the essential design ideas that span programming languages and paradigms. Find out more about TJ at tj.stank.us. About the Translators Tom Stuart The JavaScript translation was done by Tom Stuart. Tom is a computer scientist, programmer and technical leader. He’s the former CTO of FutureLearn and Econsultancy. He has lectured on optimising compilers at the University of Cambridge and written about technology for the Guardian. Tom is the proud author of Understanding Computation, which was published by O’Reilly in 2013. Matthew Fonda Matthew Fonda provided deeply thoughtful and extremely helpful guidance about how to think about PHP and OO. Matthew is CTO at eNotes.com, where he has spent the past 15 years building a platform to help students learn. During his time at eNotes, he has learned firsthand the importance of building codebases that are easy to change over time, and is more certain
Page
19
than ever that the answer to every question in software development is "it depends". Matthew is a longtime member of the PHP community and occasional contributor to PHP’s documentation. When not at the computer, you can find Matthew snowboarding in the mountains of the Pacific Northwest. The Stocktons Brothers Dave and Dann Stockton spent countless hours pondering the initial PHP translation of the 1st edition. Theirs was the first attempt at transforming the book to use another programming language, and as such they suffered all the pain one might imagine. We are eternally grateful for their efforts and contributions. The PHP shown in the book was written by Katrina, with the generous input of Matthew, Dave and Dann.
Page
20
Introduction This book creates a simple solution to the "99 Bottles of Beer" song problem, and then applies a series of refactorings to improve the design of the code. Put that way, the topic sounds so painfully obvious that one might reasonably wonder if this entire tome could be replaced by a few samples of code. These refactoring "end points" would be a fraction of the size of this book, and a vastly quicker read. Unfortunately, they would teach you almost nothing about programming. Writing code is the process of working your way to the next stable end point, not the end point itself. You don’t know the answer in advance, but instead, you are seeking it. This book documents every step down every path of code, and so provides a guided-tour of the decisions made along the way. It not only shows how good code looks when it’s done, it reveals the thoughts that produced it. It aims to leave nothing out. It flings back the veil behind which sausage is being made. A few final notes before diving into the book proper. The chapters that follow apply a general, broad solution to a specific, narrow problem. The authors cheerfully stipulate to the fact that you are unlikely to encounter the "99 Bottles of Beer" song in your daily work, and that problems of similar size are best solved very simply. For the purposes of this book, "99 Bottles" is convenient because it’s simultaneously easily understandable and surprisingly complex, and so provides an expedient stand-in for larger problems. Once you understand the