Page
1
1 Download from BookDL (http://bookdl.com)
Page
2
ii Download from BookDL (http://bookdl.com)
Page
3
Table of Contents Foreword ...................................................................................................................9 Preface . ....................................................................................................................13 Introduction. ............................................................................................................1 Ruby meets the real world. .........................................................................................2 Confident code . ..........................................................................................................2 A good story, poorly told. ...........................................................................................3 Code as narrative . ......................................................................................................4 The four parts of a method . .......................................................................................5 How this book is structured . ......................................................................................9 3.times { rejoice! } . .....................................................................................11 Performing Work . ...................................................................................................13 Sending a strong message. ....................................................................................15 Collecting Input. .....................................................................................................25 Introduction to collecting input . ..........................................................................26 Use built-in conversion protocols . ........................................................................34 Conditionally call conversion methods. ................................................................47 Define your own conversion protocols . .................................................................53 Define conversions to user-defined types . ............................................................56 Table of Contents iii Download from BookDL (http://bookdl.com)
Page
4
Use built-in conversion functions . ...........................................................................61 Use the Array() conversion function to array-ify inputs . .........................................67 Define conversion functions . ...................................................................................70 Replace "string typing" with classes. ........................................................................78 Wrap collaborators in Adapters. ...............................................................................91 Use transparent adapters to gradually introduce abstraction . .................................97 Reject unworkable values with preconditions.........................................................101 Use #fetch to assert the presence of Hash keys ....................................................107 Use #fetch for defaults .........................................................................................116 Document assumptions with assertions .................................................................125 Handle special cases with a Guard Clause...............................................................132 Represent special cases as objects ..........................................................................136 Represent do-nothing cases as null objects ............................................................149 Substitute a benign value for nil ...........................................................................162 Use symbols as placeholder objects ........................................................................167 Bundle arguments into parameter objects..............................................................176 Yield a parameter builder object.............................................................................187 Receive policies instead of data ..............................................................................198 Delivering Results . ...............................................................................................207 Write total functions...............................................................................................209 Call back instead of returning.................................................................................215 Represent failure with a benign value.....................................................................219 Represent failure with a special case object............................................................222 Return a status object .............................................................................................224 Yield a status object................................................................................................229 Signal early termination with throw......................................................................237 Handling Failure . .................................................................................................245 Prefer top-level rescue clause . ............................................................................247 Use checked methods for risky operations. .........................................................249 iv Download from BookDL (http://bookdl.com)
Page
5
Use bouncer methods. .........................................................................................253 Refactoring for Confidence. .................................................................................259 MetricFu..................................................................................................................260 Stringer ...................................................................................................................271 Parting Words . ......................................................................................................275 Colophon . ..............................................................................................................277 Table of Contents v Download from BookDL (http://bookdl.com)
Page
6
Copyright © 2013 Avdi Grimm. All rights reserved. Download from BookDL (http://bookdl.com)
Page
7
To Walter Grimm, who showed me the joy of building beautiful things. Download from BookDL (http://bookdl.com)
Page
8
viii Download from BookDL (http://bookdl.com)
Page
9
Foreword I met Avdi in 2011 at RubyConf in New Orleans. I was no one special, just an anonymous nerd who'd been browbeat into giving a talk or two. Jim Weirich had seen one of these talks and was determined that Avdi and I should meet. His introduction led to one of those arm-waving, session-skipping hallway conversations that expand minds and change lives. The three of us were so animated I'm surprised we weren't roundly shushed and permanently banned from the foyer. Writing today, that moment floods back. Our island of conversation, the conference swirling around us, Jim's infectious enthusiasm and Avdi's earnest intensity. I could not believe I was standing there. It did not seem possible to be that lucky. I thought I'd died and gone to programmer's heaven. I confessed that I was working on a book, "Practical Object-Oriented Design in Ruby", and Avdi graciously offered to read it. The word "read" vastly understates his efforts. Not only did he give feedback about the ideas but he went through the Ruby, line by line, correcting errors and improving code. When I thank him he makes Foreword ix Download from BookDL (http://bookdl.com)
Page
10
excuses that dismiss his efforts, but happily, here I have the floor and can tell you how kind he is without fear of interruption. And so, it is my great pleasure to introduce "Confident Ruby". Avdi's clarity of thought shines throughout this book. His vision of how methods should be organized provides a clear structure in which to think about code, and his recipes give straightforward and unambiguous guidance about how to write it. He has a gift for illustrating the rigorously technical with the delightfully whimsical. In this book there are bank accounts, certainly, but there's also a bibliophile meet- up named "Bookface", and, deep inside, just when you might need a break, you'll find "emergency kittens". Indeed. His genius is to make the lighthearted example both useful and plausible. Writing a book is hard work and motivations to do so run deep. In some fundamental way the drive to teach, to explain, to improve oneself and thereby the world, underlies all. I asked Avdi what made him write this book and he answered me with an email containing a number of reasons, two of which I'll share. He said "Explaining things is fun" but he also said "The truth is, this community has been so good to me that I live in a constant state of wondering why they are so nice, and wishing I could do more". A sense of fun and a feeling of obligation; that's it, now you know him. Avdi writes code that is easy to understand; in Confident Ruby he teaches us how to do the same. Among programmers, there is no higher praise. Enjoy the book. x Download from BookDL (http://bookdl.com)
Page
11
Sandi Metz March, 28, 2014 Foreword xi Download from BookDL (http://bookdl.com)
Page
12
xii Download from BookDL (http://bookdl.com)
Page
13
Preface In January of 2010 I gave the first tech talk of my life to a roomful of Ruby hackers in Baltimore, MD. I called the talk "Confident Code", and it distilled some notes I'd collected from my experience working on established Ruby codebases. Since then I've given variations on that presentation at least half a dozen times at various conferences and meet-ups. To this day it is the talk that I receive the most positive feedback on. For years I've wanted to revisit, revise, and expand on that material in a longer format. The book you're reading is the realization of that desire. There are so many people who have helped make this book a reality that it's hard to know where to begin. First of all, thank you to all the people who saw the talk and encouraged me to turn it into a book in the first place. I don't remember everyone who did, but Mike Subelsky was almost certainly the first. A huge thank you to Sandi Metz and Noel Rappin for reading early drafts and playing editor. The book is substantially more readable thanks to their feedback. Preface xiii Download from BookDL (http://bookdl.com)
Page
14
Also to Dave Copeland, whose technical insights helped clarify a number of the patterns. To my fellow Ruby Rogues Chuck Wood, James Gray, David Brady, Josh Susser, and Katrina Owen: some of you provided feedback, and all of you gave me moral support and a ready sounding board for my ideas. Thank you. To all the many, many people who read beta versions of the book and gave me feedback and errata both large and small: if this book looks like a professional effort rather than the jottings of an absent-minded hacker, it's because of you. In no particular order: Dennis Sutch, George Hemmings, Gerry Cardinal III, Evgeni Dzhelyov, Hans Verschooten, Kevin Burleigh, Michael Demazure, Manuel Vidaurre, Richard McGain, Michael Sevestre, Jake Goulding, Yannick Schutz, Mark Ijbema, John Ribar, Tom Close, Dragos .M, Brent Nordquist, Samnang Chhun, Dwayne R. Crooks, Thom Parkin, and Nathan Walls. I am certain I have missed some names, and if yours is one of them I sincerely apologize. Know that your contribution is greatly valued. Many thanks to Ryan Biesemeyer and Grant Austin, who donated e-reader hardware so that I could make sure the book looks good on all platforms. Thanks to Benjamin Fleischer and Matt Swanson for volunteering their projects as refactoring guinea pigs. Finally, thank you as always to Stacey for inspiring and encouraging me every day. And to Lily, Josh, Kashti, Ebba and Ylva, who daily teach me the meaning of joy. xiv Download from BookDL (http://bookdl.com)
Page
15
Chapter 1 Introduction Ruby is designed to make programmers happy. – Yukhiro "Matz" Matsumoto This is a book about Ruby, and about joy. If you are anything like me, the day you first discovered the expressive power of Ruby was a very happy day. For me, I think it was probably a code example like this which made it "click": 3.times do puts "Hello, Ruby world!" end To this day, that's still the most succinct, straightforward way of saying "do this three times" I've seen in any programming language. Not to mention that after Chapter 1: Introduction 1 Download from BookDL (http://bookdl.com)
Page
16
using several supposedly object-oriented languages, this was the first one I'd seen where everything, including the number "3", really was an object. Bliss! Ruby meets the real world Programming in Ruby was something very close to a realization of the old dream of programming in pseudocode. Programming in short, clear, intent-revealing stanzas. No tedious boilerplate; no cluttered thickets of syntax. The logic I saw in my head, transferred into program logic with a minimum of interference. But my programs grew, and as they grew, they started to change. The real world poked its ugly head in, in the form of failure modes and edge cases. Little by little, my code began to lose its beauty. Sections became overgrown with complicated nested if/then/else logic and && conditionals. Objects stopped feeling like entities accepting messages, and started to feel more like big bags of attributes. begin/rescue/end blocks started sprouting up willy-nilly, complicating once obvious logic with necessary failure-handling. My tests, too, became more and more convoluted. I wasn't as happy as I once had been. Confident code If you've written applications of substantial size in Ruby, you've probably experienced this progression from idealistic beginnings to somewhat less satisfying daily reality. You've noticed a steady decline in how much fun a project is the larger and older it becomes. You may have even come to accept it as the inevitable trajectory of any software project. In the following pages I introduce an approach to writing Ruby code which, when practiced dilligently, can help reverse this downward spiral. It is not a brand new set Confident Ruby 2 Download from BookDL (http://bookdl.com)
Page
17
of practices. Rather, it is a collection of time-tested techniques and patterns, tied together by a common theme: self confidence. This book's focus is on where the rubber meets the road in object-oriented programming: the individual method. I'll seek to equip you with tools to write methods that tell compelling stories, without getting lost down special-case rabbit holes or hung up on tedious type-checking. Our quest to write better methods will sometimes lead us to make improvements to our overall object design. But we'll continually return to the principal task at hand: writing clear, uncluttered methods. So what, exactly do I mean when I say that our goal is to write methods which tell a story? Well, let me start with an example of a story that isn't told very well. A good story, poorly told Have you ever read one of those "choose your own adventure" books? Every page would end with a question like this: If you fight the angry troll with your bare hands, turn to page 137. If you try to reason with the troll, turn to page 29. If you don your invisibility cloak, turn to page 6. You'd pick one option, turn to the indicated page, and the story would continue. Did you ever try to read one of those books from front to back? It's a surreal experience. The story jumps forward and back in time. Characters appear out of nowhere. One page you're crushed by the fist of an angry troll, and on the next you're just entering the troll's realm for the first time. Chapter 1: Introduction 3 Download from BookDL (http://bookdl.com)
Page
18
What if each individual page was this kind of mish-mash? What if every page read like this: You exit the passageway into a large cavern. Unless you came from page 59, in which case you fall down the sinkhole into a large cavern. A huge troll, or possibly a badger (if you already visited Queen Pelican), blocks your path. Unless you threw a button down the wishing well on page 8, in which case there nothing blocking your way. The [troll or badger or nothing at all] does not look happy to see you. If you came here from chapter 7 (the Pool of Time), go back to the top of the page and read it again, only imagine you are watching the events happen to someone else. If you already received the invisibility cloak from the aged lighthouse- keeper, and you want to use it now, go to page 67. Otherwise, forget you read anything about an invisibility cloak. If you are facing a troll (see above), and you choose to run away, turn to page 84. If you are facing a badger (see above), and you choose to run away, turn to page 93… Not the most compelling narrative, is it? The story asks you to carry so much mental baggage for it that just getting through a page is exhausting. Code as narrative What does this have to do with software? Well, code can tell a story as well. It might not be a tale of high adventure and intrigue. But it's a story nonetheless; one about Confident Ruby 4 Download from BookDL (http://bookdl.com)
Page
19
a problem that needed to be solved, and the path the developer(s) chose to accomplish that task. A single method is like a page in that story. And unfortunately, a lot of methods are just as convoluted, equivocal, and confusing as that made-up page above. In this book, we'll take a look at many examples of the kind of code that unnecessarily obscures the storyline of a method. We'll also explore a number of techniques for minimizing distractions and writing methods that straightforwardly convey their intent. The four parts of a method I believe that if we take a look at any given line of code in a method, we can nearly always categorize it as serving one of the following roles: 1. Collecting input 2. Performing work 3. Delivering output 4. Handling failures (There are two other categories that sometimes appear: "diagnostics", and "cleanup". But these are less common.) Let's test this assertion. Here's a method taken from the MetricFu project. Chapter 1: Introduction 5 Download from BookDL (http://bookdl.com)
Page
20
def location(item, value) sub_table = get_sub_table(item, value) if(sub_table.length==0) raise MetricFu::AnalysisError, "The #{item.to_s} '#{value.to_s}' "\ "does not have any rows in the analysis table" else first_row = sub_table[0] case item when :class MetricFu::Location.get(first_row.file_path, first_row.class_name, nil) when :method MetricFu::Location.get(first_row.file_path, first_row.class_name, first_row.method_name) when :file MetricFu::Location.get(first_row.file_path, nil, nil) else raise ArgumentError, "Item must be :class, :method, or :file" end end end Don't worry too much right now about what this method is supposed to do. Instead, let's see if we can break the method down according to our four categories. First, it gathers some input: sub_table = get_sub_table(item, value) Immediately, there is a digression to deal with an error case, when sub_table has no data. Confident Ruby 6 Download from BookDL (http://bookdl.com)