首页 > > > O'Reilly - Beautiful Code - Jun.2007.pdf

O'Reilly - Beautiful Code - Jun.2007.pdf

O'Reilly - Beautiful Code - Jun…

上传者: xiegeng0586_cn 2011-04-24 评分1 评论0 下载55 收藏10 阅读量287 暂无简介 简介 举报

简介:本文档为《O'Reilly - Beautiful Code - Jun.2007pdf》,可适用于IT书籍领域,主题内容包含BeautifulCodeOtherresourcesfromO’ReillyRelatedtitlesAppliedSoftwareProject符等。

Beautiful Code Other resources from O’Reilly Related titles Applied Software Project Management The Art of Project Management Database in Depth Essential Business Process Modeling Head First Design Patterns Head First Object-Oriented Analysis & Design Mastering Regular Expressions The Myths of Innovation Prefactoring Process Improvement Essentials oreilly.com oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new plat- forms, programming languages, and operating systems. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in documenting the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit conferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online reference library for programmers and IT professionals. Conduct searches across more than 1,000 books. Sub- scribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or simply flip to the page you need. Try it today for free. Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo Beautiful Code Edited by Andy Oram and Greg Wilson Beautiful Code Edited by Andy Oram and Greg Wilson Copyright 2007 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc. 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Production Editor: Marlowe Shaeffer Copyeditor: Sanders Kleinfeld Proofreader: Sohaila Abdulali Indexer: Ellen Troutman Zaig Cover Designer: Randy Comer Interior Designer: Marcia Friedman Illustrator: Jessamyn Read Printing History: June 2007: First Edition. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Beautiful Code and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover, a durable and flexible lay-flat binding. ISBN-10: 0-596-51004-7 ISBN-13: 978-0-596-51004-6 [C] [8/07] All royalties from this book will be donated to Amnesty International. vii C O N T E N T S C H A P T E R 0 FOREWORD xv by Greg Wilson PREFACE xvii 1 A REGULAR EXPRESSION MATCHER 1 by Brian Kernighan The Practice of Programming 2 Implementation 3 Discussion 4 Alternatives 5 Building on It 6 Conclusion 8 2 SUBVERSION’S DELTA EDITOR: INTERFACE AS ONTOLOGY 11 by Karl Fogel Version Control and Tree Transformation 12 Expressing Tree Differences 16 The Delta Editor Interface 17 But Is It Art? 23 Abstraction As a Spectator Sport 25 Conclusions 27 3 THE MOST BEAUTIFUL CODE I NEVER WROTE 29 by Jon Bentley The Most Beautiful Code I Ever Wrote 30 More and More with Less and Less 31 Perspective 36 What Is Writing? 38 Conclusion 39 Acknowledgments 40 4 FINDING THINGS 41 by Tim Bray On Time 41 Problem: Weblog Data 42 Problem: Who Fetched What, When? 50 Search in the Large 55 Conclusion 57 viii C O N T E N T S 5 CORRECT, BEAUTIFUL, FAST (IN THAT ORDER): LESSONS FROM DESIGNING XML VERIFIERS 59 by Elliotte Rusty Harold The Role of XML Validation 59 The Problem 60 Version 1: The Naïve Implementation 62 Version 2: Imitating the BNF Grammar O(N) 63 Version 3: First Optimization O(log N) 64 Version 4: Second Optimization: Don’t Check Twice 66 Version 5: Third Optimization O(1) 68 Version 6: Fourth Optimization: Caching 72 The Moral of the Story 74 6 FRAMEWORK FOR INTEGRATED TEST: BEAUTY THROUGH FRAGILITY 75 by Michael Feathers An Acceptance Testing Framework in Three Classes 76 The Challenge of Framework Design 78 An Open Framework 79 How Simple Can an HTML Parser Be? 80 Conclusion 83 7 BEAUTIFUL TESTS 85 by Alberto Savoia That Pesky Binary Search 87 Introducing JUnit 89 Nailing Binary Search 90 Conclusion 102 8 ON-THE-FLY CODE GENERATION FOR IMAGE PROCESSING 105 by Charles Petzold 9 TOP DOWN OPERATOR PRECEDENCE 129 by Douglas Crockford JavaScript 130 Symbol Table 131 Tokens 132 Precedence 133 Expressions 134 Infix Operators 134 Prefix Operators 136 Assignment Operators 137 Constants 138 Scope 138 Statements 140 C O N T E N T S ix Functions 143 Array and Object Literals 144 Things to Do and Think About 145 10 THE QUEST FOR AN ACCELERATED POPULATION COUNT 147 by Henry S. Warren, Jr. Basic Methods 148 Divide and Conquer 149 Other Methods 151 Sum and Difference of Population Counts of Two Words 152 Comparing the Population Counts of Two Words 153 Counting the 1-Bits in an Array 154 Applications 158 11 SECURE COMMUNICATION: THE TECHNOLOGY OF FREEDOM 161 by Ashish Gulhati The Heart of the Start 162 Untangling the Complexity of Secure Messaging 163 Usability Is the Key 165 The Foundation 167 The Test Suite 172 The Functioning Prototype 172 Clean Up, Plug In, Rock On. . . 173 Hacking in the Himalayas 177 The Invisible Hand Moves 182 Speed Does Matter 184 Communications Privacy for Individual Rights 185 Hacking the Civilization 185 12 GROWING BEAUTIFUL CODE IN BIOPERL 187 by Lincoln Stein BioPerl and the Bio::Graphics Module 188 The Bio::Graphics Design Process 192 Extending Bio::Graphics 210 Conclusions and Lessons Learned 214 13 THE DESIGN OF THE GENE SORTER 217 by Jim Kent The User Interface of the Gene Sorter 218 Maintaining a Dialog with the User over the Web 219 A Little Polymorphism Can Go a Long Way 221 Filtering Down to Just the Relevant Genes 224 Theory of Beautiful Code in the Large 225 Conclusion 228 x C O N T E N T S 14 HOW ELEGANT CODE EVOLVES WITH HARDWARE: THE CASE OF GAUSSIAN ELIMINATION 229 by Jack Dongarra and Piotr Luszczek The Effects of Computer Architectures on Matrix Algorithms 230 A Decompositional Approach 232 A Simple Version 233 LINPACK’s DGEFA Subroutine 235 LAPACK DGETRF 237 Recursive LU 240 ScaLAPACK PDGETRF 243 Multithreading for Multi-Core Systems 247 A Word About the Error Analysis and Operation Count 250 Future Directions for Research 251 Further Reading 252 15 THE LONG-TERM BENEFITS OF BEAUTIFUL DESIGN 253 by Adam Kolawa My Idea of Beautiful Code 253 Introducing the CERN Library 254 Outer Beauty 255 Inner Beauty 261 Conclusion 266 16 THE LINUX KERNEL DRIVER MODEL: THE BENEFITS OF WORKING TOGETHER 267 by Greg Kroah-Hartman Humble Beginnings 268 Reduced to Even Smaller Bits 273 Scaling Up to Thousands of Devices 276 Small Objects Loosely Joined 277 17 ANOTHER LEVEL OF INDIRECTION 279 by Diomidis Spinellis From Code to Pointers 280 From Function Arguments to Argument Pointers 282 From Filesystems to Filesystem Layers 285 From Code to a Domain-Specific Language 287 Multiplexing and Demultiplexing 289 Layers Forever? 290 C O N T E N T S xi 18 PYTHON’S DICTIONARY IMPLEMENTATION: BEING ALL THINGS TO ALL PEOPLE 293 by Andrew Kuchling Inside the Dictionary 295 Special Accommodations 296 Collisions 298 Resizing 299 Iterations and Dynamic Changes 300 Conclusion 301 Acknowledgments 301 19 MULTIDIMENSIONAL ITERATORS IN NUMPY 303 by Travis E. Oliphant Key Challenges in N-Dimensional Array Operations 304 Memory Models for an N-Dimensional Array 305 NumPy Iterator Origins 307 Iterator Design 307 Iterator Interface 313 Iterator Use 314 Conclusion 318 20 A HIGHLY RELIABLE ENTERPRISE SYSTEM FOR NASA’S MARS ROVER MISSION 319 by Ronald Mak The Mission and the Collaborative Information Portal 320 Mission Needs 321 System Architecture 322 Case Study: The Streamer Service 325 Reliability 328 Robustness 336 Conclusion 338 21 ERP5: DESIGNING FOR MAXIMUM ADAPTABILITY 339 by Rogerio Atem de Carvalho and Rafael Monnerat General Goals of ERP 340 ERP5 340 The Underlying Zope Platform 342 ERP5 Project Concepts 346 Coding the ERP5 Project 347 Conclusion 351 xii C O N T E N T S 22 A SPOONFUL OF SEWAGE 353 by Bryan Cantrill 23 DISTRIBUTED PROGRAMMING WITH MAPREDUCE 371 by Jeffrey Dean and Sanjay Ghemawat A Motivating Example 371 The MapReduce Programming Model 374 Other MapReduce Examples 375 A Distributed MapReduce Implementation 377 Extensions to the Model 380 Conclusion 381 Further Reading 381 Acknowledgments 382 Appendix: Word Count Solution 382 24 BEAUTIFUL CONCURRENCY 385 by Simon Peyton Jones A Simple Example: Bank Accounts 386 Software Transactional Memory 388 The Santa Claus Problem 396 Reflections on Haskell 404 Conclusion 404 Acknowledgments 406 25 SYNTACTIC ABSTRACTION: THE SYNTAX-CASE EXPANDER 407 by R. Kent Dybvig Brief Introduction to syntax-case 411 Expansion Algorithm 413 Example 425 Conclusion 428 26 LABOR-SAVING ARCHITECTURE: AN OBJECT-ORIENTED FRAMEWORK FOR NETWORKED SOFTWARE 429 by William R. Otte and Douglas C. Schmidt Sample Application: Logging Service 431 Object-Oriented Design of the Logging Server Framework 433 Implementing Sequential Logging Servers 439 Implementing Concurrent Logging Servers 444 Conclusion 450 27 INTEGRATING BUSINESS PARTNERS THE RESTFUL WAY 451 by Andrew Patzer Project Background 452 Exposing Services to External Clients 452 Routing the Service Using the Factory Pattern 456 Exchanging Data Using E-Business Protocols 457 Conclusion 462 C O N T E N T S xiii 28 BEAUTIFUL DEBUGGING 463 by Andreas Zeller Debugging a Debugger 464 A Systematic Process 466 A Search Problem 467 Finding the Failure Cause Automatically 468 Delta Debugging 470 Minimizing Input 472 Hunting the Defect 473 A Prototype Problem 475 Conclusion 476 Acknowledgments 476 Further Reading 476 29 TREATING CODE AS AN ESSAY 477 by Yukihiro Matsumoto 30 WHEN A BUTTON IS ALL THAT CONNECTS YOU TO THE WORLD 483 by Arun Mehta Basic Design Model 484 Input Interface 487 Efficiency of the User Interface 500 Download 500 Future Directions 500 31 EMACSPEAK: THE COMPLETE AUDIO DESKTOP 503 by T. V. Raman Producing Spoken Output 504 Speech-Enabling Emacs 505 Painless Access to Online Information 516 Summary 522 Acknowledgments 525 32 CODE IN MOTION 527 by Laura Wingerd and Christopher Seiwald On Being “Bookish” 528 Alike Looking Alike 529 The Perils of Indentation 530 Navigating Code 531 The Tools We Use 532 DiffMerge’s Checkered Past 534 Conclusion 536 Acknowledgments 536 Further Reading 536 xiv C O N T E N T S 33 WRITING PROGRAMS FOR “THE BOOK” 539 by Brian Hayes The Nonroyal Road 540 Warning to Parenthophobes 540 Three in a Row 541 The Slippery Slope 544 The Triangle Inequality 545 Meandering On 547 “Duh!”—I Mean “Aha!” 548 Conclusion 550 Further Reading 550 AFTERWORD 553 by Andy Oram CONTRIBUTORS 555 INDEX 565 xv Chapter Foreword Greg Wilson I GOT MY FIRST JOB AS A PROGRAMMER IN THE SUMMER OF 1982. Two weeks after I started, one of the system administrators loaned me Kernighan and Plauger’s The Elements of Programming Style (McGraw-Hill) and Wirth’s Algorithms + Data Structures = Programs (Prentice Hall). They were a revelation—for the first time, I saw that programs could be more than just instructions for computers. They could be as elegant as well-made kitchen cabinets, as graceful as a suspension bridge, or as eloquent as one of George Orwell’s essays. Time and again since that summer, I have heard people bemoan the fact that our profes- sion doesn’t teach students to see this. Architects are taught to look at buildings, and com- posers study one another’s scores, but programmers—they look at each other’s work only when there’s a bug to fix; even then, they try to look at as little as possible. We tell stu- dents to use sensible variable names, introduce them to some basic design patterns, and then wonder why so much of what they write is so ugly. This book is our attempt to fix this. In May 2006, I asked some well-known (and not so well-known) software designers to dissect and discuss the most beautiful piece of code they knew. As this book shows, they have found beauty in many different places. For xvi F O R E W O R D some, it lives in the small details of elegantly crafted software. Others find beauty in the big picture—in how a program’s structure allows it to evolve gracefully over time, or in the techniques used to build it. Wherever they find it, I am grateful to our contributors for taking time to give us a tour. I hope that you enjoy reading this book as much as Andy and I have enjoyed editing it, and that it inspires you to create something beautiful, too. xvii Chapter Preface BEAUTIFUL CODE WAS CONCEIVED BY GREG WILSON IN 2006 as a way to elicit insights from lead- ing software developers and computer scientists. Together, he and his co-editor, Andy Oram, approached experts with diverse backgrounds from all over the world. They received a flood of responses, partly because royalties from the book are being donated to Amnesty International. The results of the project appear in this volume. As wide-ranging as this book is, it represents just a small fraction of what is happening in this most exciting of fields. Thousand of other projects, equally interesting and educa- tional, are being moved forward every day by other programmers whom we did not con- tact. Furthermore, many excellent practitioners who were asked for chapters do not appear in this book because they were too busy at the time, preferred not to contribute to Amnesty International, or had conflicting obligations. To benefit from the insights of all these people, we hope to do further books along similar lines in the future. How This Book Is Organized Chapter 1, A Regular Expression Matcher, by Brian Kernighan, shows how deep insight into a language and a problem can lead to a concise and elegant solution. xviii P R E F A C E Chapter 2, Subversion’s Delta Editor: Interface As Ontology, by Karl Fogel, starts with a well- chosen abstraction and demonstrates its unifying effects on the system’s further development. Chapter 3, The Most Beautiful Code I Never Wrote, by Jon Bentley, suggests how to measure a procedure without actually executing it. Chapter 4, Finding Things, by Tim Bray, draws together many strands in Computer Science in an exploration of a problem that is fundamental to many computing tasks. Chapter 5, Correct, Beautiful, Fast (in That Order): Lessons from Designing XML Verifiers, by Elliotte Rusty Harold, reconciles the often conflicting goals of thoroughness and good performance. Chapter 6, Framework for Integrated Test: Beauty Through Fragility, by Michael Feathers, presents an example that breaks the rules and achieves its own elegant solution. Chapter 7, Beautiful Tests, by Alberto Savoia, shows how a broad, creative approach to test- ing can not only eliminate bugs but turn you into a better programmer. Chapter 8, On-the-Fly Code Generation for Image Processing, by Charles Petzold, drops down a level to improve performance while maintaining portability. Chapter 9, Top Down Operator Precedence, by Douglas Crockford, revives an almost forgotten parsing technique and shows its new relevance to the popular JavaScript language. Chapter 10, The Quest for an Accelerated Population Count, by Henry S. Warren, Jr., reveals the impact that some clever algorithms can have on even a seemingly simple problem. Chapter 11, Secure Communication: The Technology Of Freedom, by Ashish Gulhati, discusses the directed evolution of a secure messaging application that was designed to make sophisticated but often confusing cryptographic technology intuitively accessible to users. Chapter 12, Growing Beautiful Code in BioPerl, by Lincoln Stein, shows how the combina- tion of a flexible language and a custom-designed module can make it easy for people with modest programming skills to create powerful visualizations for their data. Chapter 13, The Design of the Gene Sorter, by Jim Kent, combines simple building blocks to produce a robust and valuable tool for gene researchers. Chapter 14, How Elegant Code Evolves with Hardware: The Case of Gaussian Elimination, by Jack Dongarra and Piotr Luszczek, surveys the history of LINPACK and related major soft- ware packages to show how assumptions must constantly be re-evaluated in the face of new computing architectures. Chapter 15, The Long-Term Benefits of Beautiful Design, by Adam Kolawa, explains how attention to good design principles many decades ago helped CERN’s widely used mathe- matical library (the predecessor of LINPACK) stand the test of time. P R E F A C E xix Chapter 16, The Linux Kernel Driver Model: The Benefits of Working Together, by Greg Kroah- Hartman, explains how many efforts by different collaborators to solve different problems led to the successful evolution of a complex, multithreaded system. Chapter 17, Another Level of Indirection, by Diomidis Spinellis, shows how the flexibility and maintainability of the FreeBSD kernel is promoted by abstracting operations done in com- mon by many drivers and filesystem modules. Chapter 18, Python’s Dictionary Implementation: Being All Things to All People, by Andrew Kuchling, explains how a careful design combined with accommodations for a few special cases allows a language feature to support many different uses. Chapter 19, Multidimensional Iterators in NumPy, by Travis E. Oliphant, takes you through the design steps that succeed in hiding complexity under a simple interface. Chapter 20, A Highly Reliable Enterprise System for NASA’s Mars Rover Mission, by Ronald Mak, uses industry standards, best practices, and Java technologies to meet the require- ments of a NASA expedition where reliability cannot be in doubt. Chapter 21, ERP5: Designing for Maximum Adaptability, by Rogerio Atem de Carvalho and Rafael Monnerat, shows how a powerful ERP system can be developed with free software tools and a flexible architecture. Chapter 22, A Spoonful of Sewage, by Bryan Cantrill, lets the reader accompany the author through a hair-raising bug scare and a clever solution that violated expectations. Chapter 23, Distributed Programming with MapReduce, by Jeff Dean and Sanjay Ghemawat, describes a system that provides an easy-to-use programming abstraction for large-scale distributed data processing at Google that automatically handles many difficult aspects of distributed computation, including automatic parallelization, load balancing, and failure handling. Chapter 24, Beautiful Concurrency, by Simon Peyton Jones, removes much of the difficulty of parallel programs through Software Transactional Memory, demonstrated here using Haskell. Chapter 25, Syntactic Abstraction: The syntax-case Expander, by R. Kent Dybvig, shows how macros—a key feature of many languages and systems—can be protected in Scheme from producing erroneous output. Chapter 26, Labor-Saving Architecture: An Object-Oriented Framework for Networked Software, by William R. Otte and Douglas C. Schmidt, applies a range of standard object-oriented design techniques, such as patterns and frameworks, to distributed logging to


  • 名称/格式
  • 评分
  • 下载次数
  • 资料大小
  • 上传时间





/ 619
所需积分:2 立即下载