don't repeat yourself

31 results back to index


pages: 292 words: 62,575

97 Things Every Programmer Should Know by Kevlin Henney

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

A Pattern Language, active measures, business intelligence, commoditize, continuous integration, crowdsourcing, database schema, deliberate practice, domain-specific language, don't repeat yourself, Donald Knuth, fixed income, general-purpose programming language, Grace Hopper, index card, inventory management, job satisfaction, loose coupling, Silicon Valley, sorting algorithm, The Wisdom of Crowds

ripple loading, Interprocess Communication Affects Application Response Time Rising, A Message to the Future, A Message to the Future, A Message to the Future A Message to the Future, A Message to the Future, A Message to the Future, A Message to the Future Robinson, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools Know How to Use Command-Line Tools, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools Rose, Act with Prudence, Act with Prudence, Act with Prudence Act with Prudence, Act with Prudence, Act with Prudence, Act with Prudence S Saariste, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern Sage, Reinvent the Wheel Often, Reinvent the Wheel Often, Reinvent the Wheel Often Reinvent the Wheel Often, Reinvent the Wheel Often, Reinvent the Wheel Often, Reinvent the Wheel Often schedules, Act with Prudence, Act with Prudence, Act with Prudence, The Professional Programmer, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs dirty code, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs professional programmers, The Professional Programmer technical debt, Act with Prudence, Act with Prudence, Act with Prudence shared memory, Message Passing Leads to Better Scalability in Parallel Systems, Message Passing Leads to Better Scalability in Parallel Systems, Message Passing Leads to Better Scalability in Parallel Systems simplicity, Beauty Is in Simplicity single binary, One Binary, One Binary, One Binary single responsibility principle, The Single Responsibility Principle, The Single Responsibility Principle, The Single Responsibility Principle singletons, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern, Resist the Temptation of the Singleton Pattern Smalltalk, Distinguish Business Exceptions from Technical Smith, Don't Repeat Yourself, Don't Repeat Yourself, Don't Repeat Yourself Don't Repeat Yourself, Don't Repeat Yourself, Don't Repeat Yourself, Don't Repeat Yourself soak test, Test While You Sleep (and over Weekends) software metrics, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs solutions, The Longevity of Interim Solutions Sommerlad, Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth source control, Don't Touch That Code!

A acceptance test-driven development (ATDD), When Programmers and Testers Collaborate Ada, Know Well More Than Two Programming Languages, Prefer Domain-Specific Types to Primitive Types Adams, Make the Invisible More Visible algorithms, Interprocess Communication Affects Application Response Time, Know Your Limits limits, Know Your Limits performance, Interprocess Communication Affects Application Response Time Allison, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real analysis tools, Take Advantage of Code Analysis Tools APIs, Convenience Is Not an -ility, Convenience Is Not an -ility, Convenience Is Not an -ility, Domain-Specific Languages, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design API design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design internal DSLs, Domain-Specific Languages Asproni, Choose Your Tools with Care, Choose Your Tools with Care, Choose Your Tools with Care, Learn to Estimate, Learn to Estimate, Learn to Estimate Choose Your Tools with Care, Choose Your Tools with Care, Choose Your Tools with Care, Choose Your Tools with Care Learn to Estimate, Learn to Estimate, Learn to Estimate, Learn to Estimate Attapattu, Before You Refactor, Before You Refactor, Before You Refactor, Test While You Sleep (and over Weekends), Test While You Sleep (and over Weekends), Test While You Sleep (and over Weekends) Before You Refactor, Before You Refactor, Before You Refactor, Before You Refactor Test While You Sleep (and over Weekends), Test While You Sleep (and over Weekends), Test While You Sleep (and over Weekends), Test While You Sleep (and over Weekends) automation, Automate Your Coding Standard, Automate Your Coding Standard, Automate Your Coding Standard, Step Back and Automate, Automate, Automate, Step Back and Automate, Automate, Automate, Step Back and Automate, Automate, Automate automating coding standard, Automate Your Coding Standard, Automate Your Coding Standard, Automate Your Coding Standard B Baden-Powell, The Boy Scout Rule Baker, Install Me, Install Me, Install Me Install Me, Install Me, Install Me, Install Me beautiful code, Beauty Is in Simplicity, A Message to the Future Begbie, Don't Be Cute with Your Test Data, Don't Be Cute with Your Test Data, Don't Be Cute with Your Test Data Don't Be Cute with Your Test Data, Don't Be Cute with Your Test Data, Don't Be Cute with Your Test Data, Don't Be Cute with Your Test Data Berczuk, Deploy Early and Often, Deploy Early and Often, Deploy Early and Often, Deploy Early and Often Deploy Early and Often, Deploy Early and Often, Deploy Early and Often, Deploy Early and Often, Deploy Early and Often Berg, Read Code, Read Code, Read Code Read Code, Read Code, Read Code, Read Code binary, One Binary blaming others, How to Use a Bug Tracker bottlenecks, Code Reviews, Interprocess Communication Affects Application Response Time, WET Dilutes Performance Bottlenecks, WET Dilutes Performance Bottlenecks, WET Dilutes Performance Bottlenecks performance, Interprocess Communication Affects Application Response Time, WET Dilutes Performance Bottlenecks, WET Dilutes Performance Bottlenecks, WET Dilutes Performance Bottlenecks process, Code Reviews Boy Scout rule, The Boy Scout Rule, The Boy Scout Rule, The Boy Scout Rule Braithwaite, Don't Be Afraid to Break Things, The Linker Is Not a Magical Program, The Linker Is Not a Magical Program, The Linker Is Not a Magical Program, Read the Humanities, Read the Humanities, Read the Humanities, Write Small Functions Using Examples breaking code, Don't Be Afraid to Break Things Read the Humanities, Read the Humanities, Read the Humanities, Read the Humanities The Linker Is Not a Magical Program, The Linker Is Not a Magical Program, The Linker Is Not a Magical Program, The Linker Is Not a Magical Program Write Small Functions Using, Write Small Functions Using Examples Examples, Write Small Functions Using Examples Brodwall, Keep the Build Clean, Keep the Build Clean, Keep the Build Clean Keep the Build Clean, Keep the Build Clean, Keep the Build Clean, Keep the Build Clean Brush, Code Is Design, Code Is Design, Code Is Design, The Guru Myth, The Guru Myth, The Guru Myth Code Is Design, Code Is Design, Code Is Design, Code Is Design The Guru Myth, The Guru Myth, The Guru Myth, The Guru Myth bug tracker, How to Use a Bug Tracker, How to Use a Bug Tracker, How to Use a Bug Tracker build scripts, Own (and Refactor) the Build, Own (and Refactor) the Build, Own (and Refactor) the Build builds, Keep the Build Clean keeping clean, Keep the Build Clean C C#, Distinguish Business Exceptions from Technical, Don't Just Learn the Language, Understand Its Culture, The Golden Rule of API Design C++, Don't Nail Your Program into the Upright Position, Know Well More Than Two Programming Languages caller breaking method contract, Distinguish Business Exceptions from Technical COBOL, Code Layout Matters, Don't Rely on "Magic Happens Here" code, The Boy Scout Rule, Check Your Code First Before Looking to Blame Others, Check Your Code First Before Looking to Blame Others, Check Your Code First Before Looking to Blame Others, Code Is Design, Code Layout Matters, Code Reviews, Coding with Reason, Coding with Reason, Coding with Reason, Comment Only What the Code Cannot Say, Domain-Specific Languages, Don't Repeat Yourself, Don't Repeat Yourself, Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth, Read Code, Read Code, Read Code, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, Take Advantage of Code Analysis Tools, Take Advantage of Code Analysis Tools, Take Advantage of Code Analysis Tools, Test While You Sleep (and over Weekends), Testing Is the Engineering Rigor of Software Development, Write Code As If You Had to Support It for the Rest of Your Life, Write Code As If You Had to Support It for the Rest of Your Life, Write Code As If You Had to Support It for the Rest of Your Life, You Gotta Care About the Code, You Gotta Care About the Code, You Gotta Care About the Code analysis tools, Take Advantage of Code Analysis Tools, Take Advantage of Code Analysis Tools, Take Advantage of Code Analysis Tools as design, Code Is Design, Testing Is the Engineering Rigor of Software Development caring about, You Gotta Care About the Code, You Gotta Care About the Code, You Gotta Care About the Code checking code before blaming others, Check Your Code First Before Looking to Blame Others, Check Your Code First Before Looking to Blame Others, Check Your Code First Before Looking to Blame Others clear information, Only the Code Tells the Truth, Only the Code Tells the Truth, Only the Code Tells the Truth comments, Comment Only What the Code Cannot Say, Only the Code Tells the Truth dirty, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs domain concepts, Domain-Specific Languages duplication, Don't Repeat Yourself libraries of shared code, The Boy Scout Rule reading, Code Layout Matters, Read Code, Read Code, Read Code reasoning semiformally about correctness, Coding with Reason, Coding with Reason, Coding with Reason repetition, Don't Repeat Yourself process calls, Don't Repeat Yourself reviews, Code Reviews running tests before committing code, Test While You Sleep (and over Weekends) writing and supporting, Write Code As If You Had to Support It for the Rest of Your Life, Write Code As If You Had to Support It for the Rest of Your Life, Write Code As If You Had to Support It for the Rest of Your Life codebase, Keep the Build Clean coding practices, Coding with Reason, Coding with Reason, Coding with Reason Colborne, Ask, "What Would the User Do?"

(You Are Not the User) Prevent Errors, Prevent Errors, Prevent Errors, Prevent Errors collaboration, Two Heads Are Often Better Than One, Two Heads Are Often Better Than One, Two Heads Are Often Better Than One, When Programmers and Testers Collaborate, When Programmers and Testers Collaborate, When Programmers and Testers Collaborate testers and programmers, When Programmers and Testers Collaborate, When Programmers and Testers Collaborate, When Programmers and Testers Collaborate Colvin, Know Your Limits, Know Your Limits, Know Your Limits Know Your Limits, Know Your Limits, Know Your Limits, Know Your Limits command-line build tools, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools, Know How to Use Command-Line Tools comments, A Comment on Comments, Comment Only What the Code Cannot Say, Only the Code Tells the Truth, Write Code As If You Had to Support It for the Rest of Your Life committing code, Test While You Sleep (and over Weekends) communicating with peers, Learn Foreign Languages, Learn Foreign Languages, Learn Foreign Languages compiler bugs, Check Your Code First Before Looking to Blame Others components, Choose Your Tools with Care concurrency, Message Passing Leads to Better Scalability in Parallel Systems, Message Passing Leads to Better Scalability in Parallel Systems, Message Passing Leads to Better Scalability in Parallel Systems continuous learning, Continuous Learning, Continuous Learning, Continuous Learning contradictions in code, Two Wrongs Can Make a Right (and Are Difficult to Fix), Two Wrongs Can Make a Right (and Are Difficult to Fix), Two Wrongs Can Make a Right (and Are Difficult to Fix) correctness of code, Coding with Reason, Coding with Reason, Coding with Reason CVS, Put Everything Under Version Control D Dahan, Beware the Share, Beware the Share, Beware the Share Beware the Share, Beware the Share, Beware the Share, Beware the Share data structures, Interprocess Communication Affects Application Response Time using caches, Interprocess Communication Affects Application Response Time deliberate practice, Do Lots of Deliberate Practice, Do Lots of Deliberate Practice, Do Lots of Deliberate Practice deployment process, Deploy Early and Often, Deploy Early and Often, Deploy Early and Often design, Code Is Design, Code Is Design, Code Is Design dirty code, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs, The Road to Performance Is Littered with Dirty Code Bombs Doar, How to Use a Bug Tracker, How to Use a Bug Tracker, How to Use a Bug Tracker How to Use a Bug Tracker, How to Use a Bug Tracker, How to Use a Bug Tracker, How to Use a Bug Tracker domain-specific languages (DSLs), Domain-Specific Languages, Domain-Specific Languages, Domain-Specific Languages domain-specific typing, Prefer Domain-Specific Types to Primitive Types, Prefer Domain-Specific Types to Primitive Types, Prefer Domain-Specific Types to Primitive Types DRY (Don't Repeat Yourself), Don't Repeat Yourself, WET Dilutes Performance Bottlenecks duplication, Don't Repeat Yourself, Own (and Refactor) the Build E encapsulation, Encapsulate Behavior, Not Just State, Encapsulate Behavior, Not Just State, Encapsulate Behavior, Not Just State Erlang, Message Passing Leads to Better Scalability in Parallel Systems errno, Don't Ignore That Error! errors, Code Reviews, Don't Ignore That Error!, Don't Ignore That Error!

Python Web Development With Django by Jeff Forcier

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

create, read, update, delete, database schema, Debian, don't repeat yourself, en.wikipedia.org, Firefox, full text search, Guido van Rossum, loose coupling, MVC pattern, revision control, Ruby on Rails, Silicon Valley, slashdot, web application

As we see in the example application chapters in Part III,“Django Applications by Example,” many Django conventions, methods, and design decisions are Pythonic or strive to be.This makes the framework easier to pick up for programmers with Python experience and also helps to ingrain good programming practices in less experienced developers. Don’t Repeat Yourself (DRY) One Pythonic attribute that deserves its own section is a principle common to almost all programming: DRY, or Don’t Repeat Yourself. DRY is perhaps the simplest programming idiom of all because it’s just plain old common sense: If you have information in more than one place and it needs to change, you’ve just made twice as much (or more) work for yourself. As an example of DRY, consider the need to perform a simple calculation on a few pieces of data, such as the sum of a collection of bank accounts associated with a given individual.

—Wesley Chun ❖ Table of Contents Introduction 1 Where Web Frameworks Come From 1 A Better Way 2 We’re Not in Kansas Anymore 2 Web Development Is Better with Python and Django 3 I: Getting Started 1 Practical Python for Django Python Skills Are Django Skills Getting Started: Python’s Interactive Interpreter Python Basics 7 7 8 10 Comments 10 Variables and Assignment 10 Operators Python Standard Types 11 11 Object Boolean Values 12 Numbers 12 Numeric Operators 13 Numeric Built-in and Factory Functions 14 Sequences and Iterables 14 Lists 17 Strings 19 Sequence Built-ins and Factory Functions 25 Mapping Type: Dictionaries 26 Standard Type Summary 28 Flow Control 28 Conditionals 29 Loops 29 Exception Handling 30 The finally Clause 31 Throwing Exceptions with raise 32 Files 33 Functions 34 Declaring and Calling Functions 34 Functions Are First-Class Objects 36 Anonymous Functions 38 *args and **kwargs 40 Decorators 42 Object-Oriented Programming 44 Class Definitions 44 Instantiation 45 Subclassing 46 Inner Classes 46 Regular Expressions 47 The re module 47 Searching Versus Matching 48 Common Gotchas 48 Single-Item Tuples 48 Modules 48 Mutability 50 Constructor Versus Initializer 52 Coding Style (PEP 8 and Beyond) 53 Indent Four Spaces 53 Use Spaces and Not Tabs 53 Don’t Write Single-Line Suites on the Same Line as the Header 54 Create Documentation Strings (aka “docstrings”) 54 Summary 2 Django for the Impatient: Building a Blog 55 57 Creating the Project 58 Running the Development Server 59 Creating the Blog Application 61 Designing Your Model 62 Setting Up the Database 62 Using a Database Server 63 Using SQLite 63 Creating the Tables Setting Up the Automatic admin Application 64 65 Trying Out the admin 66 Making Your Blog’s Public Side 70 Creating a Template 70 Creating a View Function 71 Creating a URL Pattern Finishing Touches 72 73 Template Niceties 73 Date-Based Ordering 74 Timestamp Formatting Via a Template Filter 75 Summary 75 3 Starting Out 77 Dynamic Web Site Basics 77 Communication: HTTP, URLs, Requests, Responses 78 Data Storage: SQL and Relational Databases 78 Presentation: Rendering Templates into HTML and Other Formats 79 Putting It All Together 79 Understanding Models, Views, and Templates 79 Separating the Layers (MVC) 79 Models 80 Views 81 Templates 81 Overall Django Architecture Core Philosophies of Django 82 82 Django Tries to Be Pythonic 84 Don’t Repeat Yourself (DRY) 84 Loose Coupling and Flexibility 84 Rapid Development 85 Summary 86 II: Django in Depth 4 Defining and Using Models Defining Models Why Use an ORM? 89 89 89 Django’s Rich Field Types 91 Relationships Between Models 93 Model Inheritance 97 Meta Inner Class 100 Admin Registration and Options 101 Using Models 102 Creating and Updating Your Database Using manage.py 103 Query Syntax 104 Utilizing SQL Features Django Doesn’t Provide 112 Summary 5 URLs, HTTP Mechanisms, and Views URLs Introduction to URLconfs 116 117 117 117 Replacing Tuples with url 119 Using Multiple patterns Objects 119 Including Other URL Files with include 120 Function Objects Versus Function-Name Strings 121 Modeling HTTP: Requests, Responses, and Middleware 122 Request Objects 123 Response Objects 125 Middleware 126 Views/Logic 127 Just Python Functions 128 Generic Views 128 Semi-generic Views 130 Custom Views 131 Summary 133 6 Templates and Form Processing Templates 135 135 Understanding Contexts 135 Template Language Syntax 136 Forms Defining Forms 142 142 Filling Out Forms 147 Validation and Cleaning 149 Form Display 150 Widgets 152 Summary 154 III: Django Applications by Example 7 Photo Gallery 159 The Model 160 Preparing for File Uploads 161 Installing PIL 162 Testing ImageField 163 Building Our Custom File Field 164 Initialization 166 Adding Attributes to the Field 167 Saving and Deleting the Thumbnail 168 Using ThumbnailImageField 169 Setting Up DRY URLs 169 The Item App’s URL Layout 172 Tying It All Together with Templates 173 Summary 179 8 Content Management System 181 What’s a CMS?

It covers how to display data to your users and get data back from them. Part III, “Django Applications by Example” In Part III, we create four distinct applications, each highlighting a different aspect or component of Django development, both to introduce new general ideas and to expand on the concepts found in Parts I and II. Chapter 7, “Photo Gallery” In Chapter 7, learn how to apply the “Don’t Repeat Yourself ” convention to your URL structure and create a new thumbnail-creating image form field, while you make a simple photo gallery application. Chapter 8, “Content Management System” Chapter 8 contains two related approaches to creating a CMS or CMS-like system and covers the use of a number of “contrib” Django applications. Chapter 9, “Liveblog” Chapter 9 covers writing a “liveblog”—a site that makes use of advanced JavaScript techniques, serves as a backdrop for applying AJAX to a Django project, and shows how easy it is to use any AJAX toolkit you want.


pages: 62 words: 15,274

Sass for Web Designers by Dan Cederholm

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

c2.com, don't repeat yourself, Firefox, Ruby on Rails, web application

There are holes to be plugged, and the life of a stylesheet author should be a lot easier. The DRY principle If we peer into the world of software engineering (and I much prefer to peer than hang out and get comfortable there), we can quickly see how organization, variables, constants, partials, etc., are an ingrained, crucial way of working for folks building complex systems. You may have heard of the “don’t repeat yourself” (DRY) principle. Coined and defined by Andy Hunt and Dave Thomas in their book, The Pragmatic Programmer (http://bkaprt.com/sass/1/), DRY declares: Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. The idea is that duplicating code can cause failure and confusion for developers (http://bkaprt.com/sass/2/). It’s common sense as well: write commonly-repeated patterns once, and reuse those bits throughout the application.

INDEX @content, 75 @extend function, 62 multiple, 75 @import rule, 57 A apps for Sass, 23 B Bolton, Jina, 41 border-radius mixin, 51 Bos, Bert, 13 Bourbon, 61 box-shadow mixin, 52 breakpoints, setting, 75 C color functions, 42 commenting, 39 compact style, 29 Compass framework, 59 compressed style, 30 concatenation, 84 CSS3 gradients, 53 D DRY (don’t repeat yourself) principle, 12 E elevator pitch for Sass, 10 Eppstein, Chris, 60 expanded style, 28 F file organization, 22 H HiDPI images, 80 Hunt, Andy, 12 I indented syntax, 16 installing Sass on a Mac, 19 on Windows, 21 J Jehl, Scott, 80 M media queries, 69 mixins, 44 inside mixins, 87 library of, 56 with arguments, 46 N nested style, 28 nesting CSS rules, 32 media queries, 69 namespaced properties, 35 O output formatting, 27 overrides, inserting, 38 P parent selectors, referencing, 36 Picturefill, 80 placeholder selectors, 66 Pragmatic Programmer, The, 12 R retina screens, 80 retinize mixin, 83 S Sass definition of, 14 syntax, 15 SCSS (“Sassy CSS”), 15 style guides, creating, 41 T Thomas, Dave, 12 thoughtbot, 61 V variables, 40 defining, 40 in CSS, 43 viewports, multiple, 75 W watch command, 22 ABOUT A BOOK APART We cover the emerging and essential topics in web design and development with style, clarity, and above all, brevity—because working designer-developers can’t afford to waste time.


pages: 224 words: 48,804

The Productive Programmer by Neal Ford

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

anti-pattern, business process, c2.com, continuous integration, database schema, domain-specific language, don't repeat yourself, Firefox, general-purpose programming language, knowledge worker, Larry Wall, Ruby on Rails, side project, type inference, web application, William of Occam

The Command Line 197 INDEX Symbols 80-10-10 Rule, 137 A acceptance testing web applications, 58 accidental properties Aristotle on, 136 Alt-Tab viewer (Windows) history, 24 analysis (see byte code analysis; source analysis; static analysis) Angry Monkey and Cargo Cults, 144 Ant non-build tasks, 56 anti-objects, 147 Aristotle on accidental and essential properties, 136 arrays (see zero-based arrays) attributes, xiii (see also sticky attributes) searching by, 42 autocompletion Windows address bar, 20 automation, 52–68 Ant, Nant and Rake, 56 bash shell, 60 batch files, 61 caching locally, 53 deleting downloads in Mac OS X, 62 justifying, 65–67 reinventing wheels, 53 RSS feeds, 54 Selenium with web pages, 58 SqlSplitter, 64 Subversion, 62 web site interaction, 54 yak shaving, 67 Automator (Mac OS X), 62 B background problem solving, 147 balloon tips (Windows), 39 Bash Here context menu, 28 bash shell Cygwin, 28 harvesting exception counts, 60 retrieving files, 56 batch files Automator, 62 retrieving files, 56 behavior generated code, 85 testable code, 185 binaries version control, 71 Bini, Ola on polyglot programming, 173 blogs (see RSS feeds) 199 boat anchor antipattern, 186 build machines, 72 Buildix, 53 bundles TexMate, 78 byte code analysis, 110–112 C caching locally, 53 Calendar (Java) citizenship, 126 calendars “meetings” for quiet time, 40 canonicality, 70–94 build machines, 72 defined, 70 DRY documentation, 88–92 DRY impedance mismatches, 80–88 DRY version control, 70 indirection, 73–80 virtualization, 80 CheckStyle, 114 chere command, 28 citizenship, 120–127 Calendar (Java), 126 constructors, 121 encapsulation, 120 static methods, 121–126 class diagrams, 91 CLCL, 23 clipboard stack software, 23 clipboards accelerators, 21 using batches, 22 code, xiii (see also examples; generated code; reusable code) Cyclomatic Complexity, 103 keeping in sync with schemas, 86 TDD- versus non-TDD code, 102 XML, 183 code coverage SqlSplitter, 183 TDD, 105 code snippets defined, 78 200 INDEX sharing, 79 Colibri application launcher, 11 colors built-in focus, 47 command line, xiii (see also shells) graphical, 15 launching editors from, 177 power of, 194–197 setup for, 47 Subversion, 62 Command Prompt Explorer Bar (Windows) using, 26 Command Prompt Here (Windows), 28 command prompts using, 25 commands, xiii (see also specific command) cut and copy in editors, 178 typing, 34 comments refactoring to methods, 103 compiled languages code coverage, 105 complexitax principle, 186 composed method, xiii (see also refactoring) SLAP, 156–160 concentration maintaining, 38 configuration canonical, 79 constructors citizenship, 121 default, 147 context switching time eater, 22 continuous integration defined, 72 copy command, 178 copying and pasting evils of, 78 creeping featurism, 132 cross-platform support editors, 178 cURL, 54 cut command, 178 Cyclomatic Complexity, 103 Cygwin, xiii, 192 (see also Unix) bash shell, 28 D data mapping impedance mismatches, 81–86 database schemas, 92 dbDeploy impedance mismatches, 87 debugging with Selenium, 60 defaults constructors, 121, 147 deleting downloads in Mac OS X, 62 Demeter, Law of, 140 dependent objects TDD, 98 desktops (see virtual desktops) diagrams, xiii (see also class diagrams) creating, 91 Dietzler’s Law, 137 distractions, 38–40 documentation, xiii (see also living documentation) DRY, 88–92 up-to-date, 88 domain-specific languages polyglot style development, 173 Don’t repeat yourself (see DRY) downloads deleting in Mac OS X, 62 DRY (Don‘t repeat yourself) impedance mismatches, 80–88 version control, 70 duplication (see canonicality) dynamic languages code coverage, 105 static analysis, 116 E E Text Editor, 78 e-commerce JEE example, 160–164 Eclipse keyboard shortcuts, 29 sharing code snippets, 79 Eclipse plug-ins indirection, 73 editors, 176–179 eEditor, 179 80-10-10 Rule, 137 Emacs about, 179 configuration information, 79 Emma, 114 encapsulation breaking, 120 Enso application launcher, 11 entropy defined, 130 essential properties Aristotle on, 136 examples byte code analysis, 111 composed method, 156 data mapping with Groovy, 81 dbDeploy, 87 Flog, 117 fluent interfaces, 146, 152–154 Groovy and XML, 185 initialization in Java, 167 Jaskell, 172 Java versus Groovy, 170 Java’s reflection, 150 JEE e-commerce site, 160–164 launching presentations with Rake, 57 living documentation wiki, 89 logs with bash, 60 opening spreadsheets with Ruby, 52 Rails migration, 86 refactoring SqlSplitter, 180 retrieving files with Ant, 56 singleton design pattern, 122 SLAP, 160 SqlSplitter in Ruby, 64 Struts, 184 TDDing unit tests, 99–105 XML, 184 Excel opening spreadsheets with Ruby example, 52 exception counts bash shell, 60 Explorer (see Windows) expression builders, 147 expressions (see regular expressions) INDEX 201 eye candy value of, 10 F factoring, xiii (see also refactoring) composed method, 156 file hierarchies versus search, 41 find command, 196 find utilities, 43 FindBugs, 110 Finder (Mac OS X) keyboard shortcuts, 20 versus Spotlight, 17 Flog, 117 flow state of, 38 fluent interfaces example, 152–154 using, 145–147 folders, xiii (see also virtual folders) launching pads, 12 foreground problem solving, 147 Frameworks speculative development, 130 Full Screen mode (Microsoft Office), 29 functional languages advantages of, 172 G generated code adding behavior to, 85 global variables creating, 123 GNU/Linux (see Linux; Unix) Google Desktop Search, 41 graphical command line, 15 graphical environments usefulness of, 52 grep command combined with find utilities, 43 origin of, 195 Groovy analysis, 117 GString class, 154 reflection in Java, 152 202 INDEX relationship to Java, 170 testing Java, 151 Growl (Mac OS X) notifications, 39 GString class, 154 H hard target searching, 42–44 hotkeys conflicts with, 15 I IDE, xiii (see also Eclipse; Emacs; IntelliJ; Selenium) IDE (Integrated Development Environment) keyboard shortcuts, 29 impedance mismatches, 80–88 data mapping, 81–86 migrations, 86 indirection, 73 canonical configuration, 79 canonicality, 77 syncing JEdit macros, 75 TextMate bundles, 78 IntelliJ keyboard shortcuts, 30 interfaces (see fluent interfaces) J Jaskell polyglot programming, 171 Java 80-10-10 Rule, 138 naming conventions, 144 polyglot programming, 166–173 primitives, 139 reflection and meta-programming, 150 search versus navigation, 32 testing with Groovy, 151 JavaBeans object validity, 147 JavaScript polyglot programming, 170 JDepend, 114 JEdit editor about, 179 macros, 75 JEE e-commerce example, 160–164 Junction links for Windows, 76 K Key Promoter plug-in (IntelliJ), 30 keyboards using, 29 versus mouse, 29 L Larry’s Any Text File Indexer, 41 launchers, 10–18 about, 10 Linux, 18 Mac OS X, 15 Windows, 12 launching editors from the command line, 177 Launchy application launcher, 11 Law of Demeter, 140 laws (see Dietzler’s Law; Law of Demeter) length versus usefulness, 10 libraries version control, 71 Linux, xiii (see also Unix) launchers, 18 live templates, xiii (see also code snippets) IDEs, 31 living documentation subversion, 88 logs automating with bash example, 60 M Mac OS X, xiii (see also Finder; Spotlight; Unix) command prompts, 26 deleting downloads, 62 killing instances of applications while AppleTabbing, 24 launches, 15 rooted views, 45 virtual desktops, 48 macrco recorders editors, 176 macros JEdit, 75 using, 33 maps (see tree maps) meetings for quiet time, 40 meta-programming, 150–154 fluent interface example, 152–154 Java and reflection, 150 testing Java with Groovy, 151 methods naming conventions for, 144 refactoring comments to, 103 metrics Cyclomatic Complexity, 103 static analysis, 113 mice (see mouse) Microsoft Office Full Screen mode, 29 Microsoft Windows (see Windows) migrations impedance mismatches, 86 mirroring web sites, 53 Monad (see Windows Power Shell) monitors multiple, 48 mouse versus keyboard, 29 versus typing, 18 using, 29 My Documents (Windows) moving folder, 13 N naming conventions test names versus method names, 144 Nant non-build tasks, 56 navigation versus search, 32, 40–42 versus typing, 14 .NET framework, 131 search versus navigation, 33 Windows Power Shell, 61 notifications turning off, 39 INDEX 203 O R objects (see anti-objects; dependent objects) Occam, Sir William of, 137–140 operating systems (see Linux; Mac OS X; Windows; Unix) optimistic revisions, 70 OS X (see Finder; Mac OS X; Spotlight; Unix) Rake common tasks, 57 migrations, 86 non-build tasks, 56 recorder macros, 33 refactoring, xiii (see also composed method) comments to methods, 103 composed method, 156 keyboard shortcuts, 31 SqlSplitter, 180 XML, 183 reflection Java and meta-programming, 150 registers editors, 178 registry (Windows) autocompletion tweak for Windows 2000, 20 folders, 13 regular expressions in search, 43 remember history shell feature, 23 repetition (see canonicality) Resharper search versus navigation, 33 reusable code refactoring to composed method, 159 rooted views using, 44 RSS feeds automating interaction with, 54 Ruby, xiii (see also Rake) SqlSplitter, 64 P PacMan foreground and background problem solving, 148 Panopticode static analysis, 113 pbcopy and pbpaste commands, 27 philosophers, 136–142 Aristotle, 136 Law of Demeter, 140 Occam’s razor, 137–140 pipe command, 194 Pipes (see Yahoo!

It discusses ways to reduce the clutter of your environment (both physical and virtual), how to search efficiently, and how to avoid distractions. 4 CHAPTER 1: INTRODUCTION Getting the computer to perform extra work for you obviously makes you more productive. Chapter 4, Automation, describes coercing your computer to do more work for you. Many of the tasks you perform every day can (and should) be automated. This chapter has examples and strategies to put your computer to work. Canonicality is really just a fancy term for the application of the DRY (Don’t Repeat Yourself) principle, first espoused in The Pragmatic Programmer (Addison-Wesley) by Andy Hunt and Dave Thomas. The DRY principle advises programmers to find places where information is duplicated and create a single source for this information. The Pragmatic Programmer eloquently describes this principle, and in Chapter 5, Canonicality, I show concrete examples of applying it. Part II: Practice (Philosophy) I’ve worked as a consultant for most of my many seasoned years as a developer.

You, Bob, and all your coworkers are suffering because you’re running more than one version of something important, which always gets out of sync. A canonical representation refers to the simplest form without loss of information. Canonicality refers to the practice of eliminating duplication. In the seminal book The Pragmatic Programmer (Addison-Wesley), Andrew Hunt and David Thomas lay down the law: “Don’t repeat yourself” (DRY). This three-word sentence has profound effects on software development. Glenn Vanderburg calls repetition “the single most diminishing force in software development.” Presumably, you already agree. How do you achieve canonicality in software development? It’s hard to even notice the problems in lots of situations, especially if nonDRYness (moistness?) is the status quo. This chapter provides examples of how to achieve canonicality.


Learning Flask Framework by Matt Copperwaite, Charles Leifer

create, read, update, delete, database schema, Debian, DevOps, don't repeat yourself, full text search, place-making, Skype, web application

• Database errors are less common because there are now two layers between your application and the database server: the Python interpreter itself (this will catch the obvious syntax errors), and SQLAlchemy, which has welldefined APIs and its own layer of error-checking. • Your database code may become more efficient, thanks to SQLAlchemy's unit-of-work model that helps reduce unnecessary round-trips to the database. SQLAlchemy also has facilities for efficiently pre-fetching related objects known as eager loading. • Object Relational Mapping (ORM) makes your code more maintainable, an aspiration known as don't repeat yourself, (DRY). Suppose you add a column to a model. With SQLAlchemy it will be available whenever you use that model. If, on the other hand, you had hand-written SQL queries strewn throughout your app, you would need to update each query, one at a time, to ensure that you were including the new column. • SQLAlchemy can help you avoid SQL injection vulnerabilities. • Excellent library support: As you will see in later chapters, there are a multitude of useful libraries that can work directly with your SQLAlchemy models to provide things such as maintenance interfaces and RESTful APIs.

In this chapter we shall: • Learn how to render HTML templates using Jinja2 • Learn how to use loops, control structures, and the filters provided by the Jinja2 template language • Use template inheritance to eliminate repetitive coding • Create a clean URL scheme for our blog app and set up the routing from URLs to views • Render lists of blog entries using Jinja2 templates • Add full-text search to the site [ 47 ] Templates and Views Introducing Jinja2 Jinja2 is a fast, flexible, and secure templating engine. It allows you to define your website in small blocks that are pieced together to form complete pages. On our blog, for instance, we will have blocks for the header, the sidebar, the footer, as well as templates, for rendering blog posts. This approach is DRY (Don't Repeat Yourself), which means that the markup contained in each block should not be copied or pasted elsewhere. Since the HTML for each part of the site exists in only one place, making changes and fixing bugs is much easier. Jinja2 also allows you to embed display logic in the template. For instance, we may wish to display a log out button to users who are logged in, but display a log in form to users browsing anonymously.

[ 219 ] Index A Admin model forms customizing 134-136 admin website authentication mixin, creating 143 authorization mixin, creating 143 custom index page, setting up 144 Flask-Admin templates 145, 146 securing 141, 142 AJAX form submissions 156-158 used, for creating comments 154-156 used, for loading comments 161-163 Ansible tips 219 URL 219 used, for automating deployment 216-218 Apache httpd about 204-206 static files, serving 206 with SSL support 212, 213 asynchronous tasks running, with Celery 196-199 Atom feeds creating 185 B backrefs using 42 base template creating, for blog 57-60 blog app enhancing 73 blog entries author, setting 117 expressions, combining 35, 36 filtering 33, 34 lookups, using 34, 35 retrieving 32, 33 blog project about 14 core skills 14 creating 15, 16 features 14 import flow 19 runnable Flask app, creating 17 spec 15 zooming out 18 built-in filters, Jinja2 about 55 abs() 55 default() 55 dictsort() 55 int() 56 length() 56 reverse() 56 safe() 56 sort() 56 striptags() 56 truncate() 56 URL 55 urlize() 56 built-in logger 180 C caching with Flask-Cache 192, 193 with Redis 192, 193 [ 221 ] Celery about 196 used, for running asynchronous tasks 196-199 columns 26 command line instructions creating, with Flask-Script 199, 200 comments AJAX form submissions 156-158 comment model, creating 147, 148 creating, AJAX used 154-156 data, validating in API 159 loading, AJAX used 161-163 postprocessors, using 160, 161 preprocessors, using 160, 161 retrieving 163-165 schema migration, creating 149 contrib package 126 control structures, Jinja2 51-54 create.html template creating 78-80 Cross-Site Request Forgery (CSRF) protection about 14, 183 adding 184 current user accessing 114 custom index page setting up 144 custom log message creating 181 D data validating, in API 159 database database engine, selecting 25 driver packages 25 SQLAlchemy, connecting to 25, 26 delete view protecting 117, 118 detail view building 66 Django 44 Don't Repeat Yourself (DRY) 23, 48 E eager loading 23 edit.html template creating 86-89 edit view protecting 117, 118 Entry model attributes 28 creating 26-29 entry, deleting 32 Entry table, creating 29 existing entry, modifying 32 form, defining 76, 77 working with 30, 31 entry's author storing 115, 116 error messages displaying 82-85 validating 82-85 error reporting 179, 182 expressions combining 35, 36 negation 36 operator precedence 37 F file uploads processing 97, 98 filter 53 first() method versus one() method 34 flash messages displaying, in template 93 using 91 Flask running, with WSGI server 203, 204 unit testing 171, 172 Flask-Admin adding, to app 125 features 146 installing 123, 124 models, exposing 126-129 static assets, managing 140, 141 URL 146 [ 222 ] Flask app coding 7, 8 creating 6 debugging 11-13 Flask-Admin, adding 125 Flask, installing into virtualenv 6 new file, creating 6, 7 reference link, for securing 219 requests, adding 9 routes, adding 9 SQLAlchemy, using 24 values, reading from request 10, 11 Flask-Bcrypt extension using 108 Flask-Cache used, for caching 192, 193 Flask-Login about 105 implementing 107 installing 105, 106 Flask-Migrate adding, to project 43, 44 Flask-Restless API requests, creating 151-153 installing 149 setting up 150 URL 166 Flask-Script used, for creating command line instructions 199 Flask-SQLAlchemy 24 form creating, with view 77, 78 CSRF protection 183, 184 defining, for Entry model 76, 77 SeaSurf 183, 184 submissions, handling 80-82 submissions, with AJAX 156-158 Frozen-Flask 194, 195 full-text search adding 69, 70 G Gravatar 147 Gunicorn about 210 with SSL support 215, 216 I image uploads file uploads, processing 97, 98 handling 96, 97 template, creating 99 index function 8 index view building 63, 64 initial migration creating, for schema 44 IPython installing 30 J Jinja2 about 48 built-in filters 55, 56 control structures 51-54 homepage, creating 48 loops 51-54 template operations, performing 49-51 template, programming 51-54 URL, for documentation 60 L logging about 179 built-in logger 180 custom log message, creating 181 levels 181 reference link 182 to file 180 login view building 110, 111 template, creating 112, 113 logout view building 110, 111 coding 113 lookups example 35 using 34, 35 loops, Jinja2 51 [ 223 ] M macros about 86 reference link 86 Markdown about 15 URL 190 used, for editing 190-192 mixins 143 mocking, objects 177-179 models about 26 Admin model forms, customizing 134, 135 exposing 126-129 filters, adding to list view 132-134 list views, customizing 129-131 search, adding to list view 132-134 slugs, generating 138-140 User form, enhancing 136, 137 multiple editors synchronizing 195 N negation 36 Nginx about 207, 208 static files, serving 209, 210 with SSL support 214 O Object Relational Mapping (ORM) 23 objects mocking 177-179 one() method versus first() method 34 operator precedence 37 P pagination links adding 71, 72 postprocessors using 160, 161 preprocessors using 160, 161 Pro Git about 16 URL 16 Pygments used, for syntax highlighting 186-189 Python's unit test module 168, 169 R Redis URL 193 used, for caching 192, 193 relational database advantages 22 S schema Flask-Migrate, adding 43, 44 initial migration, creating 44 modifying 43 schema migration, creating 149 status column, adding 45 SeaSurf about 183 adding 184 Secure Socket Layer (SSL) 14 sessions 120, 121 slugs generating 138-140 SQLAlchemy about 22 benefits 23 connecting, to database 25, 26 database engine, selecting 25 installing 24 online resources 24 URL, for documentation 26, 42 using, in Flask app 24 SSL certificate request, generating 211, 212 used, for securing site 210 with Apache httpd 212, 213 with Gunicorn 215, 216 with Nginx 214 static assets managing, via Flask-Admin 140, 141 [ 224 ] static files serving 100 static site commenting 195 creating 194 multiple editors, synchronizing 195 status column adding, to schema 45 syntax highlighting with Pygments 186-189 T tagging system backrefs, using 42 building 37-40 tags, adding from entries 41 tags, removing from entries 41 tags listing 68 modifying, on posts 94-96 saving, on posts 94-96 template, Flask-Admin about 145 blocks 145 using 146 test-driven development (TDD) 169 testing configuration file creating 176, 177 tests, Jinja2 about 54 URL 54 Traceback 13 U unit testing about 167, 168 API, testing 175, 176 example 169-171 page, testing 173-175 Python's unit test module 168, 169 references 182 with Flask 171, 172 URL scheme creating 60, 61 detail view, building 66 entries, listing for given tag 67 full-text search, adding 69, 70 index view, building 63, 64 purpose 61 structure 61 tags, listing 68 URL routes, defining 62 User form enhancing 136, 137 user model active field 104 created_timestamp field 104 creating 104, 105 email (unique) field 104 name field 104 password_hash field 104 slug field 104 user objects creating 108, 109 user's drafts displaying 119, 120 uWSGI 207 V validator 82 view form, creating 77, 78 view access author, setting on blog entries 117 delete view, protecting 118 edit view, protecting 117, 118 entry's author, storing 115, 116 restricting 114 user's drafts, displaying 119, 120 W Web Server Gateway Interface (WSGI) server Apache httpd 204-206 Flask, running 203, 204 Nginx 207, 208 [ 225 ] WTForms about 75 cleaning up 90 create.html template, creating 78-80 edit.html template, creating 86-89 entries, deleting 89 error messages, displaying 82-85 error messages, validating 82-85 existing entries, editing 85, 86 form, creating with view 77, 78 form, defining for Entry model 76, 77 form submissions, handling 80-82 installing 76 [ 226 ] Thank you for buying Learning Flask Framework About Packt Publishing Packt, pronounced 'packed', published its first book, Mastering phpMyAdmin for Effective MySQL Management, in April 2004, and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions.


pages: 509 words: 92,141

The Pragmatic Programmer by Andrew Hunt, Dave Thomas

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

A Pattern Language, Broken windows theory, business process, buy low sell high, c2.com, combinatorial explosion, continuous integration, database schema, domain-specific language, don't repeat yourself, Donald Knuth, general-purpose programming language, George Santayana, Grace Hopper, if you see hoof prints, think horses—not zebras, index card, loose coupling, Menlo Park, MVC pattern, premature optimization, Ralph Waldo Emerson, revision control, Schrödinger's Cat, slashdot, sorting algorithm, speech recognition, traveling salesman, urban decay, Y2K

The problem is that it's easy to duplicate knowledge in the specifications, processes, and programs that we develop, and when we do so, we invite a maintenance nightmare—one that starts well before the application ships. We feel that the only way to develop software reliably, and to make our developments easier to understand and maintain, is to follow what we call the DRY principle: EVERY PIECE OF KNOWLEDGE MUST HAVE A SINGLE, UNAMBIGUOUS, AUTHORITATIVE REPRESENTATION WITHIN A SYSTEM. Why do we call it DRY? Tip 11 DRY—Don't Repeat Yourself The alternative is to have the same thing expressed in two or more places. If you change one, you have to remember to change the others, or, like the alien computers, your program will be brought to its knees by a contradiction. It isn't a question of whether you'll remember: it's a question of when you'll forget. You'll find the DRY principle popping up time and time again throughout this book, often in contexts that have nothing to do with coding.

(In the past, we've named projects after things such as killer parrots that prey on sheep, optical illusions, and mythical cities.) Spend 30 minutes coming up with a zany logo, and use it on your memos and reports. Use your team's name liberally when talking with people. It sounds silly, but it gives your team an identity to build on, and the world something memorable to associate with your work. Don't Repeat Yourself In The Evils of Duplication, page 26, we talked about the difficulties of eliminating duplicated work between members of a team. This duplication leads to wasted effort, and can result in a maintenance nightmare. Clearly good communication can help here, but sometimes something extra is needed. Some teams appoint a member as the project librarian, responsible for coordinating documentation and code repositories.

., 189n Crash, 120 Critical thinking, 16 cron, 231 CSS, see Cascading Style Sheets CVS, see Concurrent Version System Cygwin, 80, 270 D Data blackboard system, 169 caching, 31 dictionary, 144 dynamic data structures, 135 global, 40 language, 60 normalizing, 30 readable vs. understandable, 75 test, 100, 243 views, 160 visualizing, 93 see also Metadata Data Display Debugger (DDD), 93, 268 Database active code generator, 104 schema, 105f, 141, 144 schema maintenance, 100 DBC, see Design by contract DDD, see Data Display Debugger Deadline, 6, 246 Deadlock, 131 Debugging, 90 assertions, 123 binary search, 97 bug location, 96 bug reproduction, 93 checklist, 98 compiler warnings and, 92 corrupt variables, 95 “Heisenbug”, 124 rubber ducking, 95 and source code branching, 87 surprise bug, 97 and testing, 92, 195 time bomb, 192 tracing, 94 view, 164 visualizing data, 93 Decision making, 46 Decoupled code, 38, 40 architecture, 152 blackboard system, 166 Law of Demeter, 140 metadata, 145 minimizing coupling, 138 modular testing, 244 physical decoupling, 142 temporal coupling, 150 workflow, 150 see also Coupled code Defensive coding, 107 Delegation, 304 Delphi, 55 see also Object Pascal Demeter project, 274 Demeter, Law of, 140 Dependency, reducing, see Modular system; Orthogonality Deployment, 156 Deployment descriptor, 148 Design accessor functions, 31 concurrency, 154 context, 174 deployment, 156 design/methodology testing, 242 metadata, 145 orthogonality, 34, 37 physical, 142 refactoring, 186 using services, 154 Design by contract (DBC), 109, 155 and agents, 117 assertions, 113 class invariant, 110 as comments, 113 dynamic contracts, 117 iContract, 268 language support, 114 list insertion example, 110 pre- and postcondition, 110, 113, 114 predicates, 110 unit testing, 190 Design Patterns, 264 observer, 158 singleton, 41 strategy, 41 Destructor, 132 Detectives, 165 Development tree, 87 Development, iterative, 69 Divide-and-conquer algorithm, 180 DOC++ documentation generator, 251, 269 DocBook, 254 Documentation automatic updating, 251 and code, 29, 248 comments, 29, 113, 249, 251 executable, 251 formats, 253 HTML, 101 hypertext, 210 internal/external, 248 invariant, 117 mark-up languages, 254 orthogonality, 42 outline, 18 requirements, 204 technical writers, 252 word processors, 252, 254 writing specifications, 218 see also Comment; Web documentation Dodo, 148 Domain, problem, 58, 66 Don’t repeat yourself, see DRY principle Downloading source code, see Example code Dr. Dobbs Journal, 263 DRY principle, 27, 29, 42 see also Duplication Duck, rubber, see Rubber duck Dumpty, Humpty, xxii, 165 Duplication, 26 code generators avoid, 28 and code reviews, 33 design errors, 30 documentation and code, 29 DRY principle, 27, 29 interdeveloper, 32 in languages, 29 multiple representations, 28 teams, 226 under time pressure, 32 types of, 27 Dynamic configuration, 144 Dynamic data structure, 135 Dynamics of Software Development, 264 E E-mail, 22 address for feedback, xxiii Editor, 82 auto-indenting, 85 cursor movement, 84 features, 83 generating code, 103 how many to learn, 82 template, 84 types of, 266 Windows notepad, 84 Effective C++, 265 Eiffel, 109, 114, 267 EJB, see Enterprise Java Beans elvis editor, 267 Emacs editor, 84, 266 Viper vi emulator, 267 Embedded mini-language, 62, 145 Embellishment, 11 Encapsulation, object, 127, 158 Eno, Brian, 205 Enterprise Java Beans (EJB), 39, 147 Entropy, 4 Error DBC messages, 115 design, 30 domain-specific, 59 early crash, 120 log messages, 196 orthogonality, 41 testing, 240, 247 see also Exception Error handler, 127 Estimating, 64 accuracy, 64 algorithms, 177, 178 iterative, 69 models, 66 problem domain, 66 project schedules, 68 records, 68 testing, 182 Eton College, xxi Event, 157 Event channel, 160 Example code add logging, 40 airline reservations, 164, 296 assert macro, 122 auto_ptr example, 134 bad resource balancing, 129, 130 downloading, xxiii exception error handling, 125 good resource balancing, 131 JavaDoc example, 250 method chaining, 139 normalized class, 31 open password file, 126 open user file, 127 resources and exceptions, 132, 133 side effect, 124 spaghetti error handling, 125 square root, 190 string parsing with StringTokenizer, 156 string parsing with strtok, 155 unnormalized class, 30 Example code by name AOP, 40 Misc.java, 156 assert, 122 bad_balance.c, 129, 130 balance.cc, 134 balance.c, 131–133 class Line, 30, 31 exception, 125 findPeak, 250 interface Flight, 164, 296 misc.c, 155 openpasswd.java, 126 openuserfile.java, 127 plotDate, 139 side_effect, 124 spaghetti, 125 sqrt, 190 Exception, 121 effects of, 127 and error handlers, 127 missing files, 126 resource balancing, 132 when to use, 125 Excuses, 3 Executable document, 251 expect, 269 Expert, see Guru Expiring asset, 12 eXtensible Style Language (XSL), 253 Extinction, 148 eXtreme Programming, 238n, 258, 272 F Feature creep, 10 Feedback, e-mail address, xxiii File exception, 126 header, 29 implementation, 29 log, 196 makefile, 232 source, 103 Final build, 234 Fish, dangers of, 34 Flexibility, 46 Formal methods, 220, 221 Four Posts Puzzle, 213 Fowler, Martin, xxiii, 186, 273 Free Software Foundation, see GNU Project Frog, boiled, see Boiled frog Function accessor, 31 Law of Demeter for ~s, 140 similar, 41 G Gamma, Erich, 194 Garbage collection, 134 Gardening metaphor, 184 Gehrke, Peter, xxiv Glass, Robert, 221, 236 Global variables, 40, 130, 154 Glossary, project, 210 GNU Project, 274 C/C++ compiler, 267 General Public License (GPL), 80 GNU Image Manipulation Program (GIMP), 274 SmallEiffel, 267 “Good-enough software”, see Software, quality Gordian knot, 212 Goto, 127 GUI system vs. command shell, 78 interface, 78 testing, 244 Guru, 17, 198 H Hash, secure, 74 Header file, 29 “Heisenbug”, 124, 289 Helicopter, 34n Hopper, Grace, 8n, 90 “Hot-key” sequence, 196 HTTP Web server, 196 Human factors, 241 Humpty Dumpty, xxii, 165 Hungarian notation, 249 Hungry consumer model, 153 Hypertext document, 210 I iContract, 110, 114, 268 IDE, see Integrated Development Environment IEEE Computer Society, 262 IEEE Computer, 262 IEEE Software, 263 Imperative language, 60 Implementation accidents, 173 coding, 173 specifications, 219 Imposed duplication, 28 Inadvertent duplication, 30 Indentation, automatic, 85 Independence, see Orthogonality Infrastructure, 37 Inheritance, 111 assertions, 113 fan-in/fan-out, 242 Inner tennis, 215 Inspection, code, see Code reviews Insure++, 136 Integrated circuit, 189n Integrated Development Environment (IDE), 72, 232 Integration platform, 50 Integration testing, 239 Interface blackboard system, 168 C/Object Pascal, 101 concurrency, 155 error handler, 128 GUI, 78 prototyping, 55 user, 203 Invariant, 110, 113, 155 loop, 116 semantic, 116, 135 ISO9660 format, 233n Iterative development, 69 J Jacobson, Ivar, 204 Jargon, xxii, 210 Jargon file, 273 Java, 46, 267 code generation, 232 DBC, 114 Enterprise Java Beans, 39, 147 error messages, 115 exceptions, 121 iContract, 110, 114, 268 javaCC, 59, 269 JavaDoc, 248, 251 JavaSpaces, 166, 273 JUnit, 195 multithreaded programming, 154 property access, 100 property files, 145 resource balancing, 134 RMI, 128 string parser, 156 tree view, 161 unit tests, 193 and Windows shells, 81 JavaDoc, see Java K K Desktop Environment, 273 Kaizen, xxi, 14 see also Knowledge portfolio Kernighan, Brian, 99 Keybinding, 82 Kirk, James T., 26 Knowledge producers and consumers, 166 Knowledge portfolio, 12 building, 13 critical thinking, 16 learning and reading, 14 researching, 15 Knuth, Donald, 183, 248 Korn, David, 81 Kramer, Reto, xxiv Kruchten, Phillipe, 227n L Lakos, John, xxiv, 9, 142, 265 Lame excuses, 3 Language, programming conversions, 103, 105 DBC, 114 domain, 57 duplication in, 29 learning, 14 prototypes, 55 scripting, 55, 145 specification, 58, 62 text manipulation, 99 see also Mini-language Large-Scale C++ Software Design, 142, 265 LATEX system, 103 Law of Demeter, 140 Lawns, care of, xxi Layered design, 37 Layered system, see Modular system “lazy” code, 111 Lex and Yacc, 59 Librarian, see Project librarian Library code, 39 Linda model, 167 Linear algorithms, 177 Linux, 15, 254, 265 Liskov Substitution Principle, 111 Listening, 21 Literate programming, 248 Logging, 39, 196 see also Tracing Lookup table, 104 Loop nested, 180 simple, 180 Loop invariant, 116 M Macro, 78, 86 assertions, 122 documentation, 252 error handling, 121 Maintenance, 26 imperative languages, 61 Makefile, 232 recursive, 233 Managing expectations, 256 Mark-up language, 254 Martin, Robert C., 273 McCabe Cyclomatic Complexity Metric, 242 Member variables, see Accessor functions Memory allocation, 135 Metadata, 144, 203 business logic, 146 configuration, 147 controlling transactions, 39 decoupled code, 145 and formal methods, 221 in plain text, 74 Metric, 242 Meyer, Bertrand, 31n, 109, 184, 264 Meyer, Scott, 265 Microsoft Visual C++, 198 Microsoft Windows, 46 Mini-language, 59 data language, 60 embedded, 62 imperative, 60 parsing, 62 stand-alone, 62 Mixing board, 205 MKS Source Integrity, 271 Model, 160 calculations, 67 components and parameters, 66 and estimating, 66 executable documents, 251 view, 162 Model-view-controller (MVC), 38, 160 Modular system, 37 coding, 138 prototyping, 55 resource allocation, 135 reversibility, 45 testing, 41, 190, 244 More Effective C++, 265 Mozilla, 273 Multithreaded programming, 154 MVC, see Model-view-controller The Mythical Man Month, 264 N Name, variable, 249 Nana, 114, 268 Nest allocations, 131 Nested loop, 180 Netscape, 145, 273 Newsgroup, 15, 17, 33 Nonorthogonal system, 34 Normalize, 30 Novobilski, Andrew J., 189n O() notation, 178, 181 Object coupling, 140n destruction, 133, 134 persistence, 39 publish/subscribe protocol, 158 singleton, 41 valid/invalid state, 154 viewer, 163 Object Management Group (OMG), 270 Object Pascal, 29 C interface, 101 Object-Oriented Programming, 189n Object-Oriented Software Construction, 264 Obsolescence, 74 OLTP, see On-Line Transaction Processing system OMG, see Object Management Group On-Line Transaction Processing system (OLTP), 152 Options, providing, 3 Ordering, see Workflow Orthogonality, 34 coding, 34, 36, 40 design, 37 documentation, 42 DRY principle, 42 nonorthogonal system, 34 productivity, 35 project teams, 36, 227 testing, 41 toolkits & libraries, 39 see also Modular system Over embellishment, 11 P Pain management, 185 paint() method, 173 Painting, 11 Papua New Guinea, 16 Parallel programming, 150 Parrots, killer, see Branding Parsing, 59 code generators, 105 log messages, 196 mini-language, 62 strings, 155 Partitioning, 168 Pascal, 29 Passive code generator, 103 Performance testing, 241 Perl, 55, 62, 99 C/Object Pascal interface, 101 database schema generation, 100 home page, 267 Java property access, 100 power tools, 270 test data generation, 100 testing, 197 and typesetting, 100 Unix utilities in, 81 web documentation, 101 Perl Journal, 263 Persistence, 39, 45 Petzold, Charles, 265 Pike, Rob, 99 Pilot landing, handling, etc., 217 who ate fish, 34 Plain text, 73 vs. binary format, 73 drawbacks, 74 executable documents, 251 leverage, 75 obsolescence, 74 and easier testing, 76 Unix, 76 Polymorphism, 111 Post-it note, 53, 55 Powerbuilder, 55 The Practice of Programming, 99 Pragmatic programmer characteristics, xviii e-mail address, xxiii Web site, xxiii Pre- and postcondition, 110, 113, 114 Predicate logic, 110 Preprocessor, 114 Presentation, 20 Problem domain, 58, 66 metadata, 146 Problem solving, 213 checklist for, 214 Productivity, 10, 35 Programming by coincidence, 173 Programming staff expense of, 237 Programming Windows, 265 Project glossary, 210 “heads”, 228 saboteur, 244 schedules, 68 see also Automation; Team, project Project librarian, 33, 226 Prototyping, 53, 216 architecture, 55 disposable code, 56 kinds of, 54 and programming languages, 55 and tracer code, 51 using, 54 Publish/subscribe protocol, 158 Pugh, Greg, 95n Purify, 136 PVCS Configuration Management, 271 Python, 55, 99, 267 Q Quality control, 9 requirements, 11 teams, 225 Quarry worker’s creed, xx Quicksort algorithm, 180 R Rational Unified Process, 227n Raymond, Eric S., 273 RCS, see Revision Control System Real-world data, 243 Refactoring, 5, 185 automatic, 187 and design, 186 testing, 187 time constraints, 185 Refactoring browser, 187, 268 Refinement, excessive, 11 Regression, 76, 197, 232, 242 Relationship has-a, 304 kind-of, 111, 304 Releases, and SCCS, 87 Remote Method Invocation (RMI), 128 exception handling, 39 Remote procedure call (RPC), 29, 39 Repository, 87 Requirement, 11, 202 business problem, 203 changing, 26 creep, 209 DBC, 110 distribution, 211 documenting, 204 in domain language, 58 expressing as invariant, 116 formal methods, 220 glossary, 210 over specifying, 208 and policy, 203 usability testing, 241 user interface, 203 Researching, 15 Resource balancing, 129 C++ exceptions, 132 checking, 135 coupled code, 130 dynamic data structures, 135 encapsulation in class, 132 Java, 134 nest allocations, 131 Response set, 141, 242 Responsibility, 2, 250, 258 Reuse, 33, 36 Reversibility, 44 flexible architecture, 46 Revision Control System (RCS), 250, 271 Risk management, 13 orthogonality, 36 RMI, see Remote Method Invocation Rock-n-roll, 47 RPC, see Remote procedure call Rubber ducking, 3, 95 Rules engine, 169 S Saboteur, 244 Samba, 272 Sample programs, see Example code Sather, 114, 268 SCCS, see Source code control system Schedule, project, 68 Schrödinger, Erwin (and his cat), 47 Scope, requirement, 209 Screen scraping, 61 Scripting language, 55, 145 Secure hash, 74 sed, 99 Sedgewick, Robert, 183 Self-contained components, see Orthogonality; Cohesion Semantic invariant, 116, 135 sendmail program, 60 Sequence diagram, 158 Server code, 196 Services, design using, 154 Shell, command, 77 vs.


pages: 540 words: 103,101

Building Microservices by Sam Newman

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

airport security, Amazon Web Services, anti-pattern, business process, call centre, continuous integration, create, read, update, delete, defense in depth, don't repeat yourself, Edward Snowden, fault tolerance, index card, information retrieval, Infrastructure as a Service, inventory management, job automation, load shedding, loose coupling, platform as a service, premature optimization, pull request, recommendation engine, social graph, software as a service, source of truth, the built environment, web application, WebSocket, x509 certificate

At least one organization I spoke to is so worried about this that it actually copies its service template code manually into each service. This means that an upgrade to the core service template takes longer to be applied across its system, but this is less concerning to it than the danger of coupling. Other teams I have spoken to have simply treated the service template as a shared binary dependency, although they have to be very diligent in not letting the tendency for DRY (don’t repeat yourself) result in an overly coupled system! This is a nuanced topic, so we’ll explore it in more detail in Chapter 4. Technical Debt We are often put in situations where we cannot follow through to the letter on our technical vision. Often, we need to make a choice to cut a few corners to get some urgent features out. This is just one more trade-off that we’ll find ourselves having to make.

The beauty is that I can compose multiple calls together, making handling concurrent calls to downstream services much easier. As you find yourself making more service calls, especailly when making multiple calls to perform a single operation, take a look at the reactive extensions for your chosen technology stack. You may be surprised how much simpler your life can become. DRY and the Perils of Code Reuse in a Microservice World One of the acronyms we developers hear a lot is DRY: don’t repeat yourself. Though its definition is sometimes simplified as trying to avoid duplicating code, DRY more accurately means that we want to avoid duplicating our system behavior and knowledge. This is very sensible advice in general. Having lots of lines of code that do the same thing makes your codebase larger than needed, and therefore harder to reason about. When you want to change behavior, and that behavior is duplicated in many parts of your system, it is easy to forget everywhere you need to make a change, which can lead to bugs.

continuous integration in microservices, Mapping Continuous Integration to Microservices custom images, Custom Images environment definition, Environment Definition environments to consider, Environments immutable servers, Immutable Servers interfaces, A Deployment Interface microservices vs. monolithic systems, Ease of Deployment, Deployment overview of, Summary separating from release, Separating Deployment from Release service configuration, Service Configuration virtualization approach, From Physical to Virtual virtualization, hypervisors, Traditional Virtualization virtualization, traditional, Traditional Virtualization virtualization, type 2, Traditional Virtualization deputy problem, The Deputy Problem design principles, Principles, Bringing It All Together-Highly Observable(see also architectural principles) design/delivery practicesdevelopment of, Practices real-world example, A Real-World Example directory service, Common Single Sign-On Implementations DiRT (Disaster Recovery Test), The Antifragile Organization distributed systemsfallacies of, Local Calls Are Not Like Remote Calls, Failure Is Everywhere key promises of, Composability distributed transactions, Distributed Transactions DNS service, DNS Docker, Docker documentationHAL (Hypertext Application Language), HAL and the HAL Browser importance of, Documenting Services self-describing systems, HAL and the HAL Browser Swagger, Swagger domain-driven design, Microservices Dropwizard, Tailored Service Template DRY (Don't Repeat Yourself), DRY and the Perils of Code Reuse in a Microservice World dummies, Mocking or Stubbing durability, How Much Is Too Much? dynamic service registriesbenefits of, Dynamic Service Registries Consul, Consul Eureka, Eureka launching, Rolling Your Own Zookeeper, Zookeeper E empathy, Summary encryption, Go with the Well Known end-to-end testsappropriate uses for, Test Journeys, Not Stories, So Should You Use End-to-End Tests?


pages: 372 words: 67,140

Jenkins Continuous Integration Cookbook by Alan Berg

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

anti-pattern, continuous integration, Debian, don't repeat yourself, en.wikipedia.org, Firefox, job automation, performance metric, revision control, web application, x509 certificate

The report will then take time to render in your web browser. Consider enabling a long list of rules only if you want to use the volume as an indicator of project maturity. To throttle down, exclude parts of your code, and systematically clean up the areas reported. The "don't repeat yourself" principle Cut-and-paste programming, cloning, and then modifying code makes for a refactoring nightmare. If the code is not properly encapsulated, it is easy to have slightly different pieces scattered across your code base. If you then want to remove known defects, it will require extra effort. PMD supports the Don't Repeat Yourself (DRY) principle by finding duplicate code. The trigger point is configured through the minimumTokens tag. However, the PMD plugin does not pick up the results (stored in cpd.xml). You will need to either install and configure the DRY plugin (https://wiki.jenkins-ci.org/display/JENKINS/DRY+Plugin) or the Violations Jenkins plugin.

If there is a disagreement later, then the debate is about the processes and numbers rather than personality. See the Looking for smelly code through Code coverage recipe in Chapter 5, Using Metrics to Improve Quality. Considering test automation as a software project If you see automated testing as a software project and apply well-known principles, then you will save on maintenance costs and increase the reliability of tests. The Don't Repeat Yourself (DRY) principle is a great example. Under time pressure, it is tempting to cut-and-paste similar tests from one area of the code base to another DON'T. Projects evolve bending the shape of the code base, and the tests need to be re-usable to adapt to that change. Fragile tests push up maintenance costs. One concrete example discussed briefly in Chapter 6, Testing Remotely is the use of page objects with Selenium Webdriver.

Getting Started With Ledger by Rolf Schröder

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

asset allocation, bitcoin, don't repeat yourself

This implies some technical experience and a do-it-yourself attitude on the reader’s side. On the other hand, you will get a working environment to get started with Ledger out-of-the-box. Technical details are not hidden and the code is freely distributed. You may change every aspect of the work flow and code presented throughout the book. You may be surprised how short the book is. This owes to the don’t-repeat-yourself principle consequently followed in this book: Nothing that can be seen with minimum effort in code is repeated in the book. You will always get a hint on where to get the information. This simplifies the author’s life, makes the book less error-prone and gives the reader plenty of opportunity to understand what’s going on behind the curtain. 2 1 An introduction to Ledger This chapter introduces the philosophy of double-entry accounting, Ledger as a command line tool and its basic usage. 1.1 Double-entry Accounting Double-entry accounting is a standard bookkeeping approach.


pages: 462 words: 172,671

Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

continuous integration, database schema, domain-specific language, don't repeat yourself, Donald Knuth, en.wikipedia.org, Eratosthenes, finite state, Ignaz Semmelweis: hand washing, iterative process, place-making, Rubik’s Cube, web application, WebSocket

Blocks and Indenting Do One Thing Sections within Functions One Level of Abstraction per Function Reading Code from Top to Bottom: The Stepdown Rule Switch Statements Use Descriptive Names Function Arguments Common Monadic Forms Flag Arguments Dyadic Functions Triads Argument Objects Argument Lists Verbs and Keywords Have No Side Effects Output Arguments Command Query Separation Prefer Exceptions to Returning Error Codes Extract Try/Catch Blocks Error Handling Is One Thing The Error.java Dependency Magnet Don’t Repeat Yourself Structured Programming How Do You Write Functions Like This? Conclusion SetupTeardownIncluder Bibliography Chapter 4: Comments Comments Do Not Make Up for Bad Code Explain Yourself in Code Good Comments Legal Comments Informative Comments Explanation of Intent Clarification Warning of Consequences TODO Comments Amplification Javadocs in Public APIs Bad Comments Mumbling Redundant Comments Misleading Comments Mandated Comments Journal Comments Noise Comments Scary Noise Don’t Use a Comment When You Can Use a Function or a Variable Position Markers Closing Brace Comments Attributions and Bylines Commented-Out Code HTML Comments Nonlocal Information Too Much Information Inobvious Connection Function Headers Javadocs in Nonpublic Code Example Bibliography Chapter 5: Formatting The Purpose of Formatting Vertical Formatting The Newspaper Metaphor Vertical Openness Between Concepts Vertical Density Vertical Distance Vertical Ordering Horizontal Formatting Horizontal Openness and Density Horizontal Alignment Indentation Dummy Scopes Team Rules Uncle Bob’s Formatting Rules Chapter 6: Objects and Data Structures Data Abstraction Data/Object Anti-Symmetry The Law of Demeter Train Wrecks Hybrids Hiding Structure Data Transfer Objects Active Record Conclusion Bibliography Chapter 7: Error Handling Use Exceptions Rather Than Return Codes Write Your Try-Catch-Finally Statement First Use Unchecked Exceptions Provide Context with Exceptions Define Exception Classes in Terms of a Caller’s Needs Define the Normal Flow Don’t Return Null Don’t Pass Null Conclusion Bibliography Chapter 8: Boundaries Using Third-Party Code Exploring and Learning Boundaries Learning log4j Learning Tests Are Better Than Free Using Code That Does Not Yet Exist Clean Boundaries Bibliography Chapter 9: Unit Tests The Three Laws of TDD Keeping Tests Clean Tests Enable the -ilities Clean Tests Domain-Specific Testing Language A Dual Standard One Assert per Test Single Concept per Test F.I.R.S.T.

So they reuse old error codes instead of adding new ones. 11. Those who felt that they could get away without recompiling and redeploying have been found—and dealt with. When you use exceptions rather than error codes, then new exceptions are derivatives of the exception class. They can be added without forcing any recompilation or redeployment.12 12. This is an example of the Open Closed Principle (OCP) [PPP02]. Don’t Repeat Yourself13 13. The DRY principle. [PRAG]. Look back at Listing 3-1 carefully and you will notice that there is an algorithm that gets repeated four times, once for each of the SetUp, SuiteSetUp, TearDown, and SuiteTearDown cases. It’s not easy to spot this duplication because the four instances are intermixed with other code and aren’t uniformly duplicated. Still, the duplication is a problem because it bloats the code and will require four-fold modification should the algorithm ever have to change.

may help you get the build to succeed, but at the risk of endless debugging sessions. Turning off failing tests and telling yourself you’ll get them to pass later is as bad as pretending your credit cards are free money. G5: Duplication This is one of the most important rules in this book, and you should take it very seriously. Virtually every author who writes about software design mentions this rule. Dave Thomas and Andy Hunt called it the DRY3 principle (Don’t Repeat Yourself). Kent Beck made it one of the core principles of Extreme Programming and called it: “Once, and only once.” Ron Jeffries ranks this rule second, just below getting all the tests to pass. 3. [PRAG]. Every time you see duplication in the code, it represents a missed opportunity for abstraction. That duplication could probably become a subroutine or perhaps another class outright. By folding the duplication into such an abstraction, you increase the vocabulary of the language of your design.

The Art of Readable Code by Dustin Boswell, Trevor Foucher

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Albert Einstein, don't repeat yourself, Donald Knuth, web application

For example, the following JavaScript code has a lot to take in at once: var update_highlight = function (message_num) { if ($("#vote_value" + message_num).html() === "Up") { $("#thumbs_up" + message_num).addClass("highlighted"); $("#thumbs_down" + message_num).removeClass("highlighted"); } else if ($("#vote_value" + message_num).html() === "Down") { $("#thumbs_up" + message_num).removeClass("highlighted"); $("#thumbs_down" + message_num).addClass("highlighted"); } else { $("#thumbs_up" + message_num).removeClass("highighted"); $("#thumbs_down" + message_num).removeClass("highlighted"); } }; The individual expressions in this code aren’t that big, but when placed all together, it forms one giant statement that hits you all at once. Fortunately, a lot of the expressions are the same, which means we can extract them out as summary variables at the top of the function (this is also an instance of the DRY—Don’t Repeat Yourself—principle): var update_highlight = function (message_num) { var thumbs_up = $("#thumbs_up" + message_num); var thumbs_down = $("#thumbs_down" + message_num); var vote_value = $("#vote_value" + message_num).html(); var hi = "highlighted"; if (vote_value === "Up") { thumbs_up.addClass(hi); thumbs_down.removeClass(hi); } else if (vote_value === "Down") { thumbs_up.removeClass(hi); thumbs_down.addClass(hi); } else { thumbs_up.removeClass(hi); thumbs_down.removeClass(hi); } }; The creation of var hi = "highlighted" isn’t strictly needed, but as there were six copies of it, there were compelling benefits: It helps avoid typing mistakes.

goto statement, The Infamous goto nesting, Minimize Nesting, Removing Nesting Inside Loops ConveyorQueue interface, Implementing TrailingBucketCounter, Implementing ConveyorQueue, Implementing ConveyorQueue implementing, Implementing ConveyorQueue, Implementing ConveyorQueue cookies in JavaScript, Simplifying an Existing Interface, Simplifying an Existing Interface copy constructor, default, Example: DISALLOW_EVIL_CONSTRUCTORS corner cases, input/output comment examples to illustrate, Use Input/Output Examples That Illustrate Corner Cases, Use Input/Output Examples That Illustrate Corner Cases crutch comments, Don’t Comment Bad Names—Fix the Names Instead D dashes, names with, Use Name Formatting to Convey Meaning database tables, program to join, Applying This Method to Larger Problems, Applying the Method Recursively De Morgan’s laws, Using De Morgan’s Laws declarations, organized into blocks, Organize Declarations into Blocks, Organize Declarations into Blocks defragmenting code, One Task at a Time deleting unused code, Keeping Your Codebase Small design, vs. aesthetics, Aesthetics development time, sweet spot for, Going Too Far dictionary in Python, Reshaping an Interface to Your Needs, Example: Lists and Sets in Python sensitive information in, Reshaping an Interface to Your Needs DISALLOW_COPY_AND_ASSIGN macro, Example: DISALLOW_EVIL_CONSTRUCTORS DISALLOW_EVIL_CONSTRUCTOR macro, Example: DISALLOW_EVIL_CONSTRUCTORS do-while loops, avoiding, Avoid do/while Loops, Avoid do/while Loops DRY (Don’t Repeat Yourself) principle, Breaking Down Giant Statements duplicated code, eliminating, Use Methods to Clean Up Irregularity E Eclipse, word-completion command, Typing Long Names—Not a Problem Anymore Emacs, word-completion command, Typing Long Names—Not a Problem Anymore end, inclusive/exclusive ranges using, Prefer begin and end for Inclusive/Exclusive Ranges, Prefer begin and end for Inclusive/Exclusive Ranges error messages, Making Error Messages Readable, Hand-Crafted Error Messages, Hand-Crafted Error Messages, Hand-Crafted Error Messages hand-crafted, Hand-Crafted Error Messages, Hand-Crafted Error Messages readability, Making Error Messages Readable, Hand-Crafted Error Messages exceptions, Can You Follow the Flow of Execution?

Sass and Compass for Designers by Ben Frain

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

anti-pattern, don't repeat yourself, Firefox, Steve Jobs

We've created an image sprite, made data URIs, background gradients, shadows, and a whole lot more. Hopefully, you are already realizing how much easier these tools and techniques can make your style sheet authoring. Remember, for the full list of Compass helpers and mixins, you can consult the Compass documentation at http://compass-style.org/reference/compass/. In the next chapter, we'll concentrate on trying to make our existing code DRYer (a programming acronym for Don't Repeat Yourself), focusing on how we can use the programmatic power that Sass affords, to generate repetitive code more easily. We shouldn't let words such as 'programmatic' and 'logic' worry us, though. We can totally do this! The Compass homepage is at http://compass-style.org and you can view the reference documentation for Compass features at http://compass-style.org/reference/ compass/. [ 198 ] Programmatic Logic with Sass In the last chapter, we used Compass to significantly improve the aesthetics of our design.

In our current situation, at first glance the following piece of code may seem more difficult than simply writing the rules out as we would with 'vanilla' CSS (although even with just these 4 items, it reduces 24 lines of code in our Sass to 8). However, what about if we had 10 rules to write? Or 100? Each with a tiny incremental difference. This is where the @for loop technique shines. It lets us make our code DRYer (remember that's an acronym for Don't Repeat Yourself). Enough talk, let's give this control directive a whirl. We'll create our four 'buy' rules (and their PNG equivalent as a fallback for when SVG isn't supported) with one @for loop. To accomplish this little task, first, we'll rename the various SVG and PNG images to have sequential numbers. For example, buy_1.svg, buy_2.svg, and so on. This will make more sense in a moment. We'll also need to rename the HTML classes (for example, from buy-packt to buy_4) in the markup to match


pages: 48 words: 10,481

Instant Ember.JS Application Development: How-To by Marc Bodmer

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

don't repeat yourself, Firefox, Google Chrome, MVC pattern, web application

It will help you to organize all the direct interactions a user may perform on your website. A common use case for Ember.js is when you believe your JavaScript code will become complex; when the code base becomes complex, problems about maintaining and refactoring the code base will arise. MVC stands for model-view-controller. This kind of structure makes it easy to make modifications or refactor changes to any part of your code. It will also allow you to adhere to Don't Repeat Yourself (DRY) principles. The model is responsible for notifying associated views and controllers when there has been a change in the state of the application. The controller sends CRUD requests to the model to notify it of a change in state. It can also send requests to the view to change how the view is representing the current state of the model. The view will then receive information from the model to create a graphical rendering.


pages: 226 words: 17,533

Programming Scala: tackle multicore complexity on the JVM by Venkat Subramaniam

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

augmented reality, continuous integration, domain-specific language, don't repeat yourself, loose coupling, semantic web, type inference, web application

We gathered up the common code into a function, and the differences were rolled into arguments of method calls. Methods that accept function values are commonplace in the Scala library, as you’ll see in Chapter 8, Using Collections, on page 103. Scala makes it easy to pass multiple parameters and define the types of arguments as well, if you desire, as you’ll see soon. See The Pragmatic Programmer [HT00] by Andy Hunt and David Thomas for details about the Don’t Repeat Yourself (DRY) principle. 2. Download at Boykma.Com Report erratum Prepared exclusively for sam kaplan this copy is (P1.0 printing, June 2009) 77 F UNCTION VALUES WITH M UL TIPLE P ARAMETERS 6.3 Function Values with Multiple Parameters You can define and use function values with multiple parameters. Here is an example of a method inject( ) that passes the result of the operation on one element in an array of Int to the operation on the next element.

Let’s look at an example of using beforeEach( ) and afterEach( ): Download UnitTestingWithScala/ShareCodeImperative.scala class ShareCodeImperative extends org.scalatest.Suite with org.scalatest.BeforeAndAfter { var list : java.util.ArrayList[Integer] = _ override def beforeEach() { list = new java.util.ArrayList[Integer] } override def afterEach() { list = null } def testListEmptyOnCreate() { expect(0, "Expected size to be 0" ) { list.size() } } 8. See “Don’t Repeat Yourself” in The Pragmatic Programmer [HT00]. Download at Boykma.Com Report erratum Prepared exclusively for sam kaplan this copy is (P1.0 printing, June 2009) 176 S HARING C ODE B ETWEEN T ESTS def testGetOnEmptyList() { intercept[IndexOutOfBoundsException] { list.get(0) } } } (new ShareCodeImperative).execute() Our ShareCodeImperative mixes in BeforeAndAfter and overrides the beforeEach( ) and afterEach( ) methods.


pages: 485 words: 74,211

Developing Web Applications with Haskell and Yesod by Michael Snoyman

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

create, read, update, delete, database schema, Debian, domain-specific language, don't repeat yourself, full text search, MVC pattern, web application

This typeclass defines a number of functions and some associated types. To review, we have the following correspondence between Persistent and SQL: SQLPersistent Data types (VARCHAR, INTEGER, etc) PersistValue Column PersistField Table PersistEntity Code Generation In order to ensure that the PersistEntity instances match up properly with your Haskell data types, Persistent takes responsibility for both. This is also good from a DRY (don’t repeat yourself) perspective: you only need to define your entities once. Let’s see a quick example: {-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs #-} import Database.Persist import Database.Persist.TH import Database.Persist.Sqlite import Control.Monad.IO.Class (liftIO) mkPersist sqlSettings [persist| Person name String age Int |] We use a combination of Template Haskell and Quasi-Quotation (like when defining routes): persist is a quasi-quoter that converts a whitespace-sensitive syntax into a list of entity definitions.

Specifying Types Since we will be creating a data type out of our message specifications, each parameter to a data constructor must be given a data type. We use a @-syntax for this. For example, to create the data type data MyMessage = MsgHello | MsgSayAge Int, we would write: Hello: Hi there! SayAge age@Int: Your age is: #{show age} But there are two problems with this: It’s not very DRY (don’t repeat yourself) to have to specify this data type in every file. Translators will be confused having to specify these data types. So instead, the type specification is only required in the main language file. This is specified as the third argument in the mkMessage function. This also specifies what the backup language will be, to be used when none of the languages provided by your application match the user’s language list.

Django Book by Matt Behrens

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Benevolent Dictator For Life (BDFL), create, read, update, delete, database schema, distributed revision control, don't repeat yourself, en.wikipedia.org, Firefox, full text search, loose coupling, MVC pattern, revision control, Ruby on Rails, school choice, slashdot, web application

For the previous LatestEntries example, we could have very simple feed templates. latest_title.html contains: {{ obj.title }} and latest_description.html contains: {{ obj.description }} It’s almost too easy... A More Complex Feed The framework also supports more complex feeds, via parameters. For example, say your blog offers an RSS feed for every distinct “tag” you’ve used to categorize your entries. It would be silly to create a separate Feed class for each tag; that would violate the Don’t Repeat Yourself (DRY) principle and would couple data to programming logic. Instead, the syndication framework lets you make generic feeds that return items based on information in the feed’s URL. Your tag-specific feeds could use URLs like this: http://example.com/feeds/tags/python/: Returns recent entries tagged with “python” http://example.com/feeds/tags/cats/: Returns recent entries tagged with “cats” The slug here is "tags".

The idiom of retrieving the Site object for the value of settings.SITE_ID is quite common, so the Site model’s manager (Site.objects) has a get_current() method. This example is equivalent to the previous one: from django.contrib.sites.models import Site def my_view(request): current_site = Site.objects.get_current() if current_site.domain == 'foo.com': # Do something else: # Do something else. Note In this final example, you don’t have to import django.conf.settings. Getting the Current Domain for Display For a DRY (Don’t Repeat Yourself) approach to storing your site’s name and domain name, as explained in “Scenario 2: Storing Your Site Name/Domain in One Place,” just reference the name and domain of the current Site object. For example: from django.contrib.sites.models import Site from django.core.mail import send_mail def register_for_newsletter(request): # Check form values, etc., and subscribe the user. # ... current_site = Site.objects.get_current() send_mail('Thanks for subscribing to %s alerts' % current_site.name, 'Thanks for your subscription.

Like ForeignKey, ManyToManyField can specify related_name. In the preceding example, if the ManyToManyField in Entry had specified related_name='entries', then each Author instance would have an entries attribute instead of entry_set. How Are the Backward Relationships Possible? Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don’t Repeat Yourself) principle, so Django requires you to define the relationship on only one end. But how is this possible, given that a model class doesn’t know which other model classes are related to it until those other model classes are loaded? The answer lies in the INSTALLED_APPS setting. The first time any model is loaded, Django iterates over every model in INSTALLED_APPS and creates the backward relationships in memory as needed.

Scala in Action by Nilanjan Raychaudhuri

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

continuous integration, create, read, update, delete, database schema, domain-specific language, don't repeat yourself, en.wikipedia.org, failed state, fault tolerance, general-purpose programming language, index card, MVC pattern, type inference, web application

databases, for web applications saving to using Squeryl dataflow concurrency dataflow variables DataTables trait Date class DateTime.now() method DB class, 2nd, 3rd db method DB.apply(underlying.getDB(name)) function DB.scala file DB(underlying.getDB(name)) function DBCollection class, 2nd DBCollection.scala file DbConnection DBObject parameter declaring packages decorators def keyword default arguments default constructor default-afcdbe project DefaultHttpClient() method, 2nd DELETE method Delete method dependencies, in SBT DI (dependency injection), 2nd cake pattern implicit parameters in functional style structural typing using Spring framework dispatchers, in Akkaoogle application example distributed computing divide and conquer doctype documentation DogMood trait domain models, in Akkaoogle application example domains domain-specific See language DSL don’t-repeat-yourself code. See DRY. draggable method Driver class DRY (don’t-repeat-yourself) code DSL DTO (data transfer object) dynamic languages, transitioning from Dynamic type dynamic typing E e.hasMoreElements() method e.withFilter efficiency Elem type EmployeePayrollVisitor end-to-end test environment, for test-driven development equals method Erlang error detection errorLogger() method eta-expansion evenFilter event-based actors exception handling overview extensible components challenge of solving expression problem extensible languages, Scala as external load balancer ExternalPriceCalculator, 2nd, 3rd external-price-calculator-actor-dispatcher externalPriceSource externalPriceSourceCalculator, 2nd ExternalVendor, 2nd ExternalVendor.findAll ExternalVendorProxyActor, 2nd Extractor object, 2nd F F[_] type factory pattern fault tolerance File class file.getName() method FileToCount type, 2nd filter method, 2nd find method findAllByPhase method, 2nd findAllStoriesByPhase method findByDescription, 2nd findCalculator function finder method, 2nd findLowestPrice method findOne method, 2nd FindPrice message, 2nd, 3rd firstName parameter flatMap function, 2nd floating-point types foldLeft method, 2nd, 3rd foldRight method, 2nd forAll method for-comprehensions overview using with collections fork-join fullClasspath Function type Function1 trait functional languages, Scala as Functional Object pattern functional objects functional programming, 2nd ADTs advantages of, 2nd defined function composition function currying higher-order functions methods vs. functions monads managing state using methods used with moving from OOP to modeling purely functional programs object-oriented patterns pure vs. impure programming partial functions pure functional programs recursion in functional style, dependency injection Future divide and conquer mixing with actors vs using actors G Gen class, 2nd, 3rd GenTraversableOnce, 2nd GET method Get method getChronologyUsed() method getCount method getEntity() method getName() method getOrElse method getOrElseUpdate method getResource() method gets method getSender() method Global object greet method GreetingsActor H handle method head :: tail head recursion Hewitt, Carl hierarchy of classes of collections of parallel collections higher-kinded types, 2nd higher-order functions, 2nd Hindley-Milner type host parameter HTTP method, 2nd, 3rd http.proxy environment variable HttpClient library HttpGet method HttpServlet HttpServletRequest Hughes, John I I/O monad identifiers immutable collections immutable data, vs. mutable immutable objects implicit conversion implicit keyword implicit parameters dependency injection overview, 2nd implicits import statements importance, of testing impure programming, vs. pure programming InCompleteOrder Infix Operation pattern init() method, 2nd, 3rd, 4th input Int object Int type, 2nd, 3rd integer types Integer.parseInt integration test, 2nd, 3rd interactive mode internal load balancer InternalPriceCalculator, 2nd, 3rd InternalPriceCalculatorActor internal-price-calculator-actor-dispatcher interoperability with Java Java classes in Scala checked exceptions generics static members Scala classes in Java Scala web applications using Java frameworks model, view, controller using Spring configuration inTransaction method, 2nd invariant, 2nd io.monads package IOMonad type IOResource isDefinedAt method isEmpty method isLeft method isolation isRight method Iterable trait J JapanPayroll method JAR file Java byte code Java class Java Database Connectivity.

The combinatory logic is beyond the scope of this book, but I highly recommend To Mock a Mockingbird. I’d like to highlight that once you start thinking in higher-order functions, you’ll see opportunities for extracting reusable code that you never thought possible. Think, for example, about foldRight and foldLeft defined in the Scala collection library, which let you apply any binary function. The application of higher-order functions lets you write don’t-repeat-yourself (DRY) code and you should use it as much as possible. The next section discusses partial functions and how they help in the composition of functions. 8 Reg Braithwaite, “Kestrels,” http://mng.bz/WKns. 5.3.3. Function currying Function currying is a technique for transforming a function that takes multiple parameters into a function that takes a single parameter. Look at the following function definition that takes two parameters: scala> trait TaxStrategy { def taxIt(product: String): Double } defined trait TaxStrategy scala> val taxIt: (TaxStrategy, String) => Double = (s, p) => s.taxIt(p) taxIt: (TaxStrategy, String) => Double = <function2> The taxIt function takes TaxStrategy and String parameters and returns Double value.


pages: 722 words: 90,903

Practical Vim: Edit Text at the Speed of Thought by Drew Neil

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Bram Moolenaar, don't repeat yourself, en.wikipedia.org, fault tolerance, finite state, place-making, QWERTY keyboard, web application

Table of Contents Acknowledgments Foreword Read Me   How This Book Is Structured   A Note on the Examples   Learn to Touch Type, Then Learn Vim Read the Forgotten Manual   Get to Know Vim’s Built-in Documentation   Notation for Simulating Vim on the Page   Downloading the Examples   Use Vim’s Factory Settings   On the Role of Vim Script   On Vim Versions 1. The Vim Way   Tip 1. Meet the Dot Command   Tip 2. Don’t Repeat Yourself   Tip 3. Take One Step Back, Then Three Forward   Tip 4. Act, Repeat, Reverse   Tip 5. Find and Replace by Hand   Tip 6. Meet the Dot Formula I. Modes   2. Normal Mode     Tip 7. Pause with Your Brush Off the Page     Tip 8. Chunk Your Undos     Tip 9. Compose Repeatable Changes     Tip 10. Use Counts to Do Simple Arithmetic     Tip 11. Don’t Count If You Can Repeat     Tip 12.

The Dot Command Is a Micro Macro Later, in Chapter 11, ​Macros​, we’ll see that Vim can record any arbitrary number of keystrokes to be played back later. This allows us to capture our most repetitive workflows and replay them at a keystroke. We can think of the dot command as being a miniature macro, or a “micro” if you prefer. We’ll see a few applications of the dot command throughout this chapter. We’ll also learn a couple of best practices for working with the dot command in Tip 9, and Tip 23. Tip 2 Don’t Repeat Yourself For such a common use case as appending a semicolon at the end of a series of lines, Vim provides a dedicated command that combines two steps into one. Suppose that we have a snippet of JavaScript code like this: the_vim_way/2_foo_bar.js ​​var foo = 1​​ ​​var bar = 'a'​​ ​​var foobar = foo + bar​​ We need to append a semicolon at the end of each line. Doing so involves moving our cursor to the end of the line and then switching to Insert mode to make the change.


pages: 108 words: 28,348

Code Simplicity by Max Kanat-Alexander

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

don't repeat yourself, premature optimization, the scientific method

The only parts of your program where you should be concerned about speed are the exact parts that you can show are causing a real performance problem for your users. For the rest of the code, the primary concerns are flexibility and simplicity, not making it go fast. There are infinite ways of violating this rule, but the way to follow it is simple: just get real evidence that a problem is valid before you address it. Don’t Repeat Yourself This is probably the most well known rule in software design. This book is not the first place it’s ever appeared. But it is valid, and so it is included here: In any particular system, any piece of information should, ideally, exist only once. Let’s say you have a field called “Password” that appears on 100 screens of your program’s user interface. What if you want to change the name of the field to “Passcode”?


pages: 136 words: 20,501

Introduction to Tornado by Michael Dory, Adam Parrish, Brendan Berg

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

don't repeat yourself, Firefox, social web, web application, WebSocket

</p> <p class="small"> Follow us on Facebook at {% raw linkify("https://fb.me/burtsbooks", extra_params='ref=website') %}. </p> {% end %} This way, you can make use of the great shorthand of linkify(), but still utilize the benefit of autoescaping elsewhere. UI Modules As we’ve seen, the templating system is lightweight but powerful. In practice, we’d like to follow the software engineering adage, Don’t Repeat Yourself. In order to eliminate redundant code, we can make sections of our templates modular. For example, pages that display lists of items can define a single module that renders the markup for each item. Alternatively, groups of pages that share a common navigation structure could render content from a shared module. Tornado’s UI Modules are especially helpful in these situations. UI Modules are reusable components that encapsulate markup, style, and behavior for inclusion in a template.


pages: 274 words: 58,675

Puppet 3 Cookbook by John Arundel

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Amazon Web Services, cloud computing, continuous integration, Debian, defense in depth, don't repeat yourself, GnuPG, Larry Wall, place-making, Ruby on Rails, web application

But we can add whatever parameters we want, so long as we declare them in the definition, in parentheses after the name, as follows: define tmpfile($greeting) { file { "/tmp/${name}": content => $greeting, } } And pass values to them when we declare an instance of the resource: tmpfile{ 'foo': greeting => "Hello, world\n", } 60 Chapter 3 You can declare multiple parameters as a comma-separated list: define webapp($domain,$path,$platform) { ... } webapp { 'mywizzoapp': domain => 'mywizzoapp.com', path => '/var/www/apps/mywizzoapp', platform => 'Rails', } You can also declare default values for any parameters which aren't supplied, thus making them optional: define tmpfile($greeting,$mode='0644') { ... } This is a powerful technique for abstracting out everything that's common to certain resources, and keeping it in one place so that you Don't Repeat Yourself. In the preceding example, there might be many individual resources contained within webapp: packages, config files, source code checkouts, virtual hosts, and so on. But all of them are the same for every instance of webapp except the parameters we provide. These might be referenced in a template, for example, to set the domain for a virtual host. See also ff Passing parameters to classes, in this chapter Using dependencies To make sure things happen in the right order, you can specify in Puppet that one resource depends on another; for example, you need to install package X before you can start the service it provides, so you would mark the service as dependent on the package.


pages: 420 words: 79,867

Developing Backbone.js Applications by Addy Osmani

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Airbnb, anti-pattern, create, read, update, delete, database schema, don't repeat yourself, Firefox, full text search, Google Chrome, Khan Academy, loose coupling, MVC pattern, node package manager, pull request, Ruby on Rails, side project, single page application, web application

The two key concepts you need to be aware of when using it with a script-loader are the define() method for defining modules and the require() method for loading dependencies. define() is used to define named or unnamed modules using the following signature: define( module_id /*optional*/, [dependencies] /*optional*/, definition function /*function for instantiating the module or object*/ ); As you can tell by the inline comments, the module_id is an optional argument which is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it’s useful too). When this argument is left out, we call the module ‘anonymous’. When working with anonymous modules, RequireJS will use a module’s file path as its module id, so the adage Don’t Repeat Yourself (DRY) should be applied by omitting the module id in the define() invocation. The dependencies argument is an array representing all of the other modules that this module depends on and the third argument is a factory that can either be a function that should be executed to instantiate the module or an object. A barebones module (compatible with RequireJS) could be defined using define() as follows: // A module ID has been omitted here to make the module anonymous define(['foo', 'bar'], // module definition function // dependencies (foo and bar) are mapped to function parameters function ( foo, bar ) { // return a value that defines the module export // (i.e the functionality we want to expose for consumption) // create your module here var myModule = { doStuff:function(){ console.log('Yay!


pages: 323 words: 65,306

Programming in CoffeeScript by Mark Bates

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

don't repeat yourself, en.wikipedia.org, MVC pattern, node package manager, Ruby on Rails, single page application, web application

The total is 212.5 You probably don’t understand everything we just did there, but don’t worry, that’s what this chapter is for. However, even without knowing the specifics of how functions are defined, and work, in CoffeeScript, you can see how much cleaner our code is between the two examples. In the refactored code, we are even able to pass in a different tax rate, should we need to. This also helps us keep our code DRY1: Don’t Repeat Yourself. Not repeating your code makes for an easier-to-manage code base with, hopefully, fewer bugs. Function Basics We’ll start with the very basics on how to define a function in CoffeeScript. The anatomy of a very simple function looks like this: Example: (source: simple_function.coffee) myFunction = ()-> console.log "do some work here" myFunction() Example: (source: simple_function.js) (function() { var myFunction; myFunction = function() { return console.log("do some work here"); }; myFunction(); }).call(this); In that example we gave the function a name, myFunction, and a code block to go with it.


pages: 239 words: 64,812

Geek Sublime: The Beauty of Code, the Code of Beauty by Vikram Chandra

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Alan Turing: On Computable Numbers, with an Application to the Entscheidungsproblem, Apple II, barriers to entry, Berlin Wall, British Empire, business process, conceptual framework, create, read, update, delete, crowdsourcing, don't repeat yourself, Donald Knuth, East Village, European colonialism, finite state, Firefox, Flash crash, glass ceiling, Grace Hopper, haute couture, iterative process, Jaron Lanier, John von Neumann, land reform, London Whale, Norman Mailer, Paul Graham, pink-collar, revision control, Silicon Valley, Silicon Valley ideology, Skype, Steve Jobs, Steve Wozniak, supercomputer in your pocket, theory of mind, Therac-25, Turing machine, wikimedia commons, women in the workforce

Even small systems now divided functionality into hundreds and thousands of objects. Thinking about all these pieces and layers and their interactions became increasingly difficult; subtle bugs arose from what felt like spooky action at a distance—entanglements between objects emerged from their whirling dance. In defense, programmers codified best practices into a smorgasbord of easily abbreviated rubrics: Separation of Concerns, Single Responsibility Principle, Don’t Repeat Yourself, Liskov Substitution Principle. Automated testing of each independent section of code became more crucial than ever, first to ensure that the code was actually doing what you wanted, and later to be sure that it was still doing what you wanted after you made changes in some other section of code—effects sometimes flowed unpredictably from one region to another. In fact, adherents of Test-Driven Design (TDD) would have you write the tests before you ever write the code—that is, you write DoesMyAddTwoNumbersFunctionReallyReturnTheRightSum() before you write AddTwoNumbers(), thus forcing you to design AddTwoNumbers() to be easily testable.


pages: 1,758 words: 342,766

Code Complete (Developer Best Practices) by Steve McConnell

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Ada Lovelace, Albert Einstein, Buckminster Fuller, call centre, choice architecture, continuous integration, data acquisition, database schema, don't repeat yourself, Donald Knuth, fault tolerance, Grace Hopper, haute cuisine, if you see hoof prints, think horses—not zebras, index card, inventory management, iterative process, Larry Wall, late fees, loose coupling, Menlo Park, Perl 6, place-making, premature optimization, revision control, Sapir-Whorf hypothesis, slashdot, sorting algorithm, statistical model, Tacoma Narrows Bridge, the scientific method, Thomas Kuhn: the structure of scientific revolutions, Turing machine, web application

In either case, here are some warning signs —sometimes called "smells" (Fowler 1999)—that indicate where refactorings are needed: Code is duplicated Duplicated code almost always represents a failure to fully factor the design in the first place. Duplicate code sets you up to make parallel modifications—whenever you make changes in one place, you have to make parallel changes in another place. It also violates what Andrew Hunt and Dave Thomas refer to as the "DRY principle": Don't Repeat Yourself (2000). I think David Parnas says it best: "Copy and paste is a design error" (McConnell 1998b). A routine is too long In object-oriented programming, routines longer than a screen are rarely needed and usually represent the attempt to force-fit a structured programming foot into an object-oriented shoe. One of my clients was assigned the task of breaking up a legacy system's longest routine, which was more than 12,000 lines long.

. // [See documentation, comments] abbreviations in algorithms argument against authorship bad code, on blank lines around Book Paradigm for categories of checklists 2nd classes coded meanings control structures 2nd declarations with 2nd 3rd descriptions of code intent distance to code guideline efficient creation of endline comments errors, marking workarounds explanatory files flags, bit level global variables 2nd indentation guidelines individual lines with input data 2nd integrating into development interfaces, class interfaces, routine Javadoc 2nd key points layout guidelines legal notices length of descriptions level of code intent loops maintenance of 2nd 3rd major vs. minor markers non-code essential information numerical data optimum density of output data paragraphs of code with 2nd parameter declarations parts of programs performance considerations preceding code rule proportionality of pseudocode, deriving from 2nd 3rd purpose of repeating code with resources on routines with 2nd self-commenting code Socratic dialog about standards, IEEE style differences, managing style violations summaries of code surprises tricky code 2nd undocumented features variables version control why vs. how workarounds commitment delay strategy communication skills, importance of communicational cohesion communications, development team comparisons floating-point equality mixed data types compilers binding during compilation [See executable-code tools, compilers] broken builds data type warnings debugging tools, as 2nd errors, finding in routines line numbers, debugging with messages, treatment of 2nd multiple error messages optimizations by performance tuning considerations project-wide standards for speeds from optimization, table of tools for tricky code optimization validators with warnings 2nd completeness of requirements checklist complex data types complexity abstraction for handling classes for reducing coding conventions for reducing control structure contributions to conventions for managing decision points, counting importance of isolation, classes for live time management 2nd McCabe's metric mental objects held, measure of methods for handling minimization goal patterns, reducing with problem domain, working at reliability correlated with routines for reducing size of projects, effect on span component testing components, buying 2nd Composite pattern compound boundaries compound statements computed-value qualifiers of variable names computer-aided software engineering (CASE) tools conditional statements boolean function calls with [See control structures, conditional flow] boolean variables recommended chained if-then-else statements checklist common cases first guideline comparing performance of covering all cases defined eliminating testing redundancy else clauses equality, branching on error processing examples frequency, testing in order of key points lookup tables, substituting normal case first guideline normal path first guideline null if clauses plain if-then statements refactoring short-circuit evaluation confessional debugging configuration management architectural anticipation of change [See managing construction, change control; managing construction, configuration management] backup plans 2nd boards, change-control bureaucratic considerations checklist code changes cost, estimating defined design changes estimating change costs grouping change requests high change volumes identifying areas of change machine configurations, reproducing purpose of requirements changes 2nd 3rd resources on SCM tool version control version-control software const keyword, C++ 2nd 3rd 4th 5th constants checklist consistency rule declarations using defined emulation by global variables initializing literals, avoiding with naming 2nd 3rd purpose of refactoring simulating in languages lacking construction guidelines percent of total activity, by size of project resources on construction decisions checklist of major construction practices [See construction, decisions] coding practices checklist early-wave environments key points for major construction practices, selecting mature technology environments programming conventions programming into languages quality assurance checklist teamwork checklist technology waves, determining your location in tools checklist construction schedules, estimating approaches to, list of [See construction, schedules, estimating] catching up from behind controlling vs. estimating factors influencing level of detail for multiple techniques with comparisons objectives, establishing optimism overview planning estimation time reduction of scope reestimating requirements specification resources for teams, expanding constructors deep vs. shallow copies exceptions with guidelines for initializing data members refactoring singleton property, enforcing container classes containment 2nd continuation lines continue statements 2nd 3rd continuous integration control structures checklists 2nd 3rd commenting 2nd complexity, contributions to compound statements continuation lines in data types, relationship to documentation double indented begin-end pairs iteration 2nd key points layout styles multiple returns from routines null statements reliability correlated with complexity selective data with sequential data with structured programming unindented begin-end pairs unusual, overview of conventions, coding benefits of [See coding, conventions] checklist hazards, avoiding with predictability benefit converting data types cooperation skills, importance of correctness 2nd costs change estimates collaboration benefits debugging, time consumed by defects contributing to detection of defects error-prone routines estimating 2nd fixing of defects 2nd General Principle of Software Quality 2nd pair programming vs. inspections resources on counted loops coupling base classes to derived classes classes, too tightly design considerations flexibility of goals of loose 2nd object-parameter type semantic type simple-data-parameter type simple-object type size of visibility of coverage monitoring tools structured basis testing CRC (Class, Responsibility, Collaboration) cards creativity, importance of 2nd cross-reference tools curiosity, role in character Currency data types customization, building metaphor for Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] daily build and smoke tests automation of benefits of broken builds 2nd build groups checklist defined diagnosis benefit holding area for additions importance of morning releases pressure pretest requirement revisions smoke tests unsurfaced work data architecture prerequisites bad classes, testing for change, identifying areas of combined states defined state defined-used paths, testing design entered state exited state good classes, testing killed state legacy, compatibility with nominal case errors test, generators for used state data dictionaries data flow testing data literacy test data recorder tools data structures data transformations for code tuning array dimension minimization [See data, code tuning] array reference minimization caching data floating point to integers indexing data purpose of data types "a" prefix convention [See data, types; variables, types of] BCD change, identifying areas of checklist control structures, relationship to Currency definitions iterative data key points for naming 2nd 3rd overloaded primitives refactoring to classes 2nd resources on selective data sequential data t_ prefix convention variables of, differentiating from data-level refactoring 2nd databases performance issues SQL subsystem design days-in-month, determining deallocation goto statements for pointers, of 2nd 3rd Debug.Assert statements debugging binary searches of code [See defects in code, fixing; tools, debugging] blindness, sources of breakpoints breaks, taking brute-force changes, recent checklist comments, misplaced common defects lists compilers as tools for 2nd confessional debugging costs of 2nd debugger tools 2nd 3rd 4th [See also debugging aids] defects as opportunities defined Diff tool execution profilers for expanding suspicious regions experience of programmers, effects of finding defects 2nd fixing defects guessing history of hypothesis testing 2nd incremental approach ineffective approach to key points line numbers from compilers lint tool listing possibilities locating error sources logic checking tools multiple compiler messages narrowing code searches obvious fixes performance variations project-wide compilers settings psychological considerations quality of software, role in quotation marks, misplaced readability improvements recommended approach reexamining defect-prone code resources for Satan's helpers scaffolding for scientific method of self-knowledge from source-code comparators stabilizing errors superstitious approaches symbolic debuggers syntax checking 2nd 3rd system debuggers test case creation testing, compared to time for, setting maximums tools for 2nd 3rd 4th [See also debugging aids] understanding the problems unit tests varying test cases warnings, treating as errors debugging aids C++ preprocessors [See debugging, aids to; debugging, defensive] case statements early introduction recommended offensive programming planning removal of pointers, checking preprocessors production constraints in development versions purpose of stubs version control tools decision tables declarations 2nd 3rd [See variables, declaring] const recommended declare and define near first use rule define near first use rule final recommended formatting implicit declarations multiple on one line numerical data, commenting order of placement of pointers 2nd using all declared Decorator pattern defects in code classes prone to error [See errors, coding] classifications of clerical errors (typos) Code Complete example construction, proportion resulting from cost of detection cost of fixing databases of detection by various techniques, table of distribution of ease of fixing defects error checklists expected rate of finding, checklist intermittent misunderstood designs as sources for opportunities presented by outside of construction domain percentage of, measurement performance issues programmers at fault for readability improvements refactoring after fixing scope of self-knowledge from size of projects, effects on sources of, table stabilizing defensive programming assertions assumptions to check, list of barricades checklist debugging aids defined error handling for exceptions 2nd friendly messages guideline graceful crashing guideline guidelines for production code hard crash errors guideline important errors guideline key points for logging guideline problems caused by quality improvement techniques, other robustness vs. correctness security issues trivial errors guideline validating input defined data state defining variables Delphi, recoding to assembler DeMorgan's Theorems, applying dependencies, code-ordering checker tools [See sequences, code, order of] circular clarifying concept of documentation error checking hidden initialization order naming routines non-obvious organization of code parameters, effective design abstractions, forming consistent accidental problems BDUF beauty bottom-up approach to design business logic subsystem capturing work central points of control change, identifying areas of changes, management of characteristics of high quality checklists 2nd classes, division into collaboration communications among subsystems completion of, determining complexity management construction activity, as contract, by coupling considerations database access subsystem defined diagrams, drawing discussion, summarizing divide and conquer technique documentation overkill documentation, as emergent nature of encapsulation enough, determining essential problems extensibility goal formality of, determining formalizing class contracts goals checklist good practices table for hierarchies for high fan-in goal IEEE standards information hiding 2nd inheritance iteration practice key points leanness goal level of detail needed levels of loose coupling goal low-to-medium fan-out goal maintenance goals mental limitations of humans metrics, warning signs from nondeterministic nature of 2nd object-oriented, resource for objects, real world, finding packages level performance tuning considerations portability goal practices 2nd prioritizing during prototyping resources for restrictive nature of reusability goal routines, of sloppy process nature of software system level standard techniques goal standards, IEEE stratification goal strong cohesion subsystem level system dependencies subsystem testing for implementation tools for top-down approach tradeoffs UML diagrams user interface subsystem visual documentation of wicked problem nature of Wikis, capturing on destructors, exceptions with detailed-design documents developer testing development processes development standards, IEEE diagrams heuristic design use of UML Diff tools 2nd direct access tables advantages of [See table-driven methods, direct access] arrays for case statement approach days-in-month example defined design method for flexible-message-format example fudging keys for insurance rates example keys for object approach transforming keys disassemblers discipline, importance of discourse rules disposing of objects divide and conquer technique division Do loops [See also loops] documentation abbreviation of names ADTs for bad code, of Book Paradigm for capturing work checklists 2nd classes control structures CRC cards for dependencies, clarifying design as 2nd detailed-design documents external Javadoc 2nd key points names as 2nd 3rd organization of data parameter assumptions pseudocode, deriving from resources on routine parameter assumptions routines SDFs self-documenting code size of projects, effects of source code as standards, IEEE style differences, managing UDFs visual, of designs why vs. how dog tag fields dog-and-pony shows DoNothing() macros DRY (Don't Repeat Yourself) principle duplication avoiding with routines code as refactoring indicator Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] early-wave environments ease of maintenance design goal eclecticism editing tools beautifiers [See tools, editing] class-hierarchy generators cross-reference tools Diff tools grep IDEs interface documentation merge tools multiple-file string searches templates efficiency eighty/twenty (80/20) rule else clauses boolean function calls with case statements instead of chains, in common cases first guideline correctness testing default for covering all cases gotos with null embedded life-critical systems emergent nature of design process emulated pure blocks layout style encapsulation assumptions about users checklist classes, role for coupling classes too tightly downcast objects friend class concern heuristic design with minimizing accessibility private details in class interfaces public data members public members of classes public routines in interfaces concern semantic violations of weak endless loops 2nd endline comments endline layout 2nd 3rd enumerated types benefits of [See data types, enumerated types] booleans, alternative to C++ 2nd changes benefit checklist comments substituting for creating for Java defined emulation by global variables explicit value pitfalls first entry invalid trick iterating through Java, creating for languages available in loop limits with naming 2nd 3rd parameters using readability from reliability benefit standard for validation with Visual Basic equality, floating-point equivalence partitioning error codes error detection, doing early error guessing error handling architecture prerequisites [See errors, handling] assertions, compared to barricades buffer overruns compromising closest legal value defensive programming, techniques for error codes, returning error-processing routines, calling high-level design implication local handling logging warning messages messages 2nd 3rd next valid data, returning previous answers, reusing propagation design refactoring returning neutral values robustness 2nd routines, designing along with shutting down validation design error messages codes, returning design displaying friendly messages guideline errors 2nd classifications of dog tag fields goto statements for processing sources of, table essential problems estimating schedules approaches to, list of change costs control, compared to factors influencing inaccuracy, character-based level of detail for multiple techniques with comparisons objectives, establishing optimism overview planning for estimation time redoing periodically reduction of scope requirements specification resources for teams, expanding event handlers evolution Evolutionary Delivery exceptions [See errors, exceptions] abstraction issues alternatives to base classes for, project specific C++ centralized reporters constructors with defensive programming checklist destructors with empty catch blocks rule encapsulation, breaking full information rule Java languages, table comparing level of abstraction rule library code generation of local handling rule non-exceptional conditions purpose of 2nd readability of code using refactoring resources for standardizing use of Visual Basic 2nd executable-code tools build tools code libraries code-generation wizards installation tools linkers preprocessors setup tools execution profilers 2nd Exit Function [See also return statements] Exit statements Exit Sub [See also return statements] exiting loops 2nd experience, personal experimental prototyping experimentation as learning 2nd exponential expressions expressions constants, data types for initializing at compile time layout guidelines precomputing results right shifting strength reduction subexpression elimination system calls, performance of extensibility design goal external audits external documentation Extreme Programming collaboration component of defect detection defined resources on 2nd Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] Facade pattern factorials factoring [See also refactoring] factory methods Factory Method pattern nested ifs refactoring example refactoring to fan-in fan-out farming metaphor fault tolerance feature-oriented integration Fibonacci numbers files ADTs, treating as authorship records for C++ source file order deleting multiple example documenting layout within naming 2nd routines in final keyword, Java finally statements fixing defects checking fixes [See defects in code, fixing] checklist diagnosis confirmation hurrying, impact of initialization defects maintenance issues one change at a time rule reasoning for changes saving unfixed code similar defects, looking for special cases symptoms, fixing instead of problems understand first guideline unit tests for flags change, identifying areas of comments for bit-level meanings enumerated types for gotos, rewriting with names for semantic coupling with flexibility coupling criteria for defined floating-point data types accuracy limitations [See data types, floating-point] BCD checklist costs of operations equality comparisons magnitudes, greatly different, operations with rounding errors Visual Basic types for loops advantages of formatting 2nd indexes purpose of foreach loops 2nd formal inspections author role [See collaboration, formal inspections; collaboration, inspections; defects in code, formal inspections for detecting] benefit summary blame game checklist CMM Code Complete example compared to other collaboration defined egos in error checklists expected results from fine-tuning follow-up stage inspection meetings key points management role moderator role overview stage performance appraisals from planning stage preparation stage procedure for rate of code review reports resources for reviewer role reviews, compared to rework stage roles in scenarios approach scribe role stages of three-hour solutions meeting formal technical reviews formatting code Fortran functional cohesion functional specification functions calculations converted to example [See classes, functions in] defined disallowing key point for naming conventions for 2nd private, overriding return values, setting status as return value when to use Fundamental Theorem of Formatting Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] General Principle of Software Quality collaboration effects costs debugging defined global variables aliasing problems with [See variables, global] alternatives to annotating changes to, inadvertent checklist for class variable alternatives code reuse problems commenting 2nd enumerated types emulation by g_ prefix guideline hiding implementation in classes information hiding problems with initialization problems intermediate results, avoiding key points local first guideline locking modularity damaged by named constants emulation by naming 2nd 3rd 4th 5th 6th objects for, monster overview of persistence of preservation of values with re-entrant code problems refactoring risk reduction strategies routines using as parameters semantic coupling with streamlining data use with tramp data, eliminating with god classes gonzo programming good data, testing goto statements Ada, inclusion in [See control structures, gotos] advantages of alternatives compared with checklist deallocation with disadvantages of duplicate code, eliminating with else clauses with error processing with Fortran's use of forward direction guideline guidelines indentation problem with key points layout guidelines legitimate uses of optimization problem with phony debating about readability issue resources for rewritten with nested ifs rewritten with status variables rewritten with try-finally trivial rewrite example unused labels graphical design tools grep growing a system metaphor GUIs (graphical user interfaces) architecture prerequisites refactoring data from subsystem design Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] habits of programmers hacking approach to design hardware dependencies, changing performance enhancement with has a relationships heuristic design abstractions, forming consistent [See design, heuristic; design, practice heuristics; heuristics, design with] alternatives from patterns avoiding failure binding time considerations bottom-up approach to design brute force capturing work central points of control change, identifying areas of checklist for collaboration communications benefit from patterns completion of, determining coupling considerations diagrams, drawing divide and conquer technique encapsulation error reduction with patterns formality of, determining formalizing class contracts goals checklist guidelines for using hierarchies for information hiding 2nd inheritance interfaces, formalizing as contracts iteration practice key points level of detail needed modularity multiple approach suggestion nature of design process nondeterministic basis for object-oriented, resource for objects, real world, finding patterns 2nd practices 2nd prototyping resources for responsibilities, assigning to objects strong cohesion summary list of rules testing, anticipating top-down approach 2nd heuristics algorithms compared to error guessing hiding hierarchies, benefits of high fan-in design goal human aspects of software development humility, role in character 2nd 3rd Hungarian naming convention hybrid coupling of variables Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] I/O (input/output) architecture prerequisites change, identifying areas of performance considerations IDEs (Integrated Development Environments) IEEE (Institute for Electric and Electrical Engineers) if statements boolean function calls with [See conditional statements, if statements; control structures, if statements] break blocks, simplification with case statements, compared to 2nd case statements, converting to 2nd chains of checklist common cases first guideline continuation lines in covering all cases else clauses 2nd equality, branching on error processing examples factoring to routines flipped frequency, testing in order of gotos rewritten with 2nd if-then-else statements, converting to key points lookup tables, substituting multiple returns nested in negatives in, making positive normal case first guideline normal path first guideline null if clauses plain if-then statements refactoring simplification single-statement layout tables, replacing with types of implicit declarations implicit instancing in keyword, creating incomplete preparation, causes of incremental development metaphor incremental integration benefits of [See integration, incremental] bottom-up strategy classes 2nd customer relations benefit defined disadvantages of top-down strategy errors, locating feature-oriented integration interface specification 2nd progress monitoring benefit resources on results, early risk-oriented integration sandwich strategy scheduling benefits slices approach steps in strategies for, overview stubs 2nd summary of approaches T-shaped integration test drivers top-down strategy for vertical-slice approach indentation 2nd indexed access tables 2nd indexes, loop alterations checklist enumerated types for final values scope of variable names indexes, supplementing data types with infinite loops 2nd informal reviews 2nd information hiding access routines for [See object-oriented programming, hiding information] ADTs for barriers to categories of secrets circular dependencies problem class data mistaken for global data class design considerations class implementation details example excessive distribution problem importance of interfaces, class performance issues privacy rights of classes resources for secrets concept type creation for inheritance access privileges from [See object-oriented programming, inheritance] case statements checklist containment compared to decisions involved in deep trees defined design rule for functions, private, overriding guidelines, list of heuristic design with identifying as a design step is a relationships key points for Liskov Substitution Principle main goal of mixins multiple overridable vs. non-overridable routines parallel modifications refactoring indicator placement of common items in tree private vs. protected data private, avoiding recommended bias against routines overridden to do nothing similar sub and super classes single-instance classes initializing variables accumulators at declaration guideline C++ example checklist for class members compiler settings consequences of failing to const recommended constants counters declare and define near first use rule final recommended first use guideline fixing defects global variables importance of Java example key point loops, variables used in parameter validity pointer problems 2nd 3rd Principle of Proximity reinitialization strings system perturbers, testing with Visual Basic examples initializing working memory inline routines input parameters input/output inspections installation tools instancing objects ADTs factory method singleton 2nd integer data types checklist [See data types, integers] costs of operations division considerations overflows ranges of Integrated Development Environments (IDEs) integration benefits of 2nd big-bang bottom-up strategy broken builds checklist classes 2nd 3rd continuous customer relations daily build and smoke test defined disadvantages of top-down strategy errors, locating feature-oriented strategy importance of approach methods interface specification 2nd key points monitoring phased resources on risk-oriented strategy sandwich strategy scheduling slices approach smoke tests strategies for, overview stubs 2nd summary of approaches T-shaped integration testing 2nd top-down strategy for unsurfaced work vertical-slice approach integrity intellectual honesty intellectual toolbox approach intelligence, role in character interfaces, class abstraction aspect of 2nd 3rd calls to classes, refactoring cohesion consistent level of abstraction delegation vs. inheritance, refactoring documenting 2nd erosion under modification problem evaluating abstraction of extension classes, refactoring with foreign routines, refactoring with formalizing as contracts good abstraction example guidelines for creating inconsistency with members problem inconsistent abstraction, example of information hiding role integration, specification during 2nd key points for layout of mixins objects, designing for opposites, pairs of poor abstraction example private details in programmatic preferred to semantic public routines in interfaces concern read-time convenience rule refactoring 2nd routines, moving to refactor routines, unused semantic violations of encapsulation unrelated information, handling interfaces, graphic interfaces, routine commenting foreign routines, refactoring with pseudocode for public member variables routines, hiding routines, moving to refactor internationalization interoperability interpreted languages, performance of invalid input iteration in development choosing, reasons for [See approaches to development, iterative approach] code tuning design practice Extreme Programming importance of prerequisites 2nd pseudocode component of sequential approach compared iteration, code foreach loops 2nd iterative data iterator loops, defined Iterator pattern structured programming concept of Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] jamming loops Java assertion example in boolean expression syntax description of exceptions layout recommended live time examples naming conventions for 2nd parameters example persistence of variables resources for Javadoc 2nd JavaScript JUnit just in time binding Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] key construction decisions killed data state kinds of software projects Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] languages, programming Law of Demeter layout array references [See coding, style; conventions, coding, formatting; programming conventions, formatting rules; readability, formatting for; style issues, formatting] assignment statement continuations begin-end pairs blank lines 2nd block style brace styles 2nd C++ side effects checklist classes closely related statement elements comments complicated expressions consistency requirement continuing statements control statement continuations control structure styles declarations discourse rules documentation in code double indented begin-end pairs emulating pure blocks endline layout 2nd ends of continuations files, within Fundamental Theorem of Formatting gotos incomplete statements indentation interfaces key points language-specific guidelines logical expressions logical structure, reflecting 2nd mediocre example misleading indentation example misleading precedence modifications guideline multiple statements per line negative examples objectives of parentheses for pointers, C++ pure blocks style readability goal religious aspects of resources on routine arguments routine call continuations routine guidelines self-documenting code single-statement blocks statement continuation statement length structures, importance of styles overview unindented begin-end pairs violations of, commenting Visual Basic blocking style white space 2nd 3rd laziness lazy evaluation leanness design goal legal notices length of variable names, optimum levels of design business logic subsystem classes, divisions into database access subsystem overview of packages routines software system subsystems system dependencies subsystem user interface subsystem libraries, code purpose of using functionality from life-cycle models development standard good practices table for linked lists deleting pointers node insertion pointers, isolating operations of linkers lint tool Liskov Substitution Principle (LSP) literal data 2nd literate programs live time of variables 2nd load time, binding during localization architecture prerequisites string data types locking global data logarithms logging defensive programming guideline tools for testing logic coverage testing logical cohesion logical expressions code tuning comparing performance of eliminating testing redundancy frequency, testing in order of identities layout of lazy evaluation lookup tables, substituting short-circuit evaluation loops abnormal [See conditional statements, looping, conditional; control structures, loops] arrays with bodies of, processing 2nd brackets recommended break statements 2nd 3rd checklist code tuning commenting completion tests, location of compound, simplifying continuation lines in continue statements 2nd 3rd continuously evaluated loops [See also while loops] counted loops [See also for loops] cross talk defined designing, process for do loops empty, avoiding endless loops 2nd endpoint considerations entering, guidelines for 2nd enumerated types for exit guidelines 2nd 3rd for loops 2nd 3rd 4th foreach loops 2nd fusion of goto with housekeeping statements index alterations index checklist index final values index scope index variable names infinite loops 2nd initialization code for 2nd iterative data structures with iterator loops 2nd jamming key points kinds of, generalized labeled break statements language-specific, table of length of minimizing work inside multiple break statements naming variables nested 2nd 3rd null statements, rewriting off-by-one errors one-function guideline order of nesting performance considerations pointers inside problems with, overview of pseudocode method refactoring 2nd repeat until clauses routines in safety counters with scope of indexes sentinel tests for size as refactoring indicator strength reduction switching termination, making obvious testing redundancy, eliminating unrolling unswitching variable guidelines variable initializations variables checklist verifying termination while loops loose coupling design goal, as strategies for low-to-medium fan-out design goal LSP (Liskov Substitution Principle) Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] Macintosh naming conventions macro routines alternatives for [See routines, macro] limitations on multiple statements in naming 2nd parentheses with magazines on programming magic variables, avoiding 2nd 3rd maintenance comments requiring design goal for error-prone routines, prioritizing for fixing defects, problems from maintainability defined readability benefit for structures for reducing major construction practices checklist managing construction code ownership attitudes [See construction, managing] complexity good coding, encouraging inspections, management role in key points managers measurements programmers, treatment of readability standard resources on reviewing all code rewarding good practices schedules, estimating signing off on code standards, authority to set standards, IEEE 2nd two-person teams markers, defects from matrices mature technology environments maximum normal configurations maze recursion example McCabe's complexity metric 2nd measure twice, cut once measurement advantages of arguing against goals for outlier identification resources for side effects of table of useful types of memory allocation, error detection for corruption by pointers fillers initializing working paging operation performance impact pointers, corruption by tools for mentoring merge tools metaphors, software accreting a system algorithmic use of 2nd building metaphor building vs. buying components combining computer-centric vs. data-centric views customization discoveries based on earth centric vs. sun centric views examples of farming growing a system heuristic use of importance of incremental development key points for modeling use for overextension of oyster farming pendulum example power of readability relative merits of 2nd simple vs. complex structures size of projects throwing one away toolbox approach using writing code example methodologies [See also approaches to development] methods metrics reporters minimum normal configurations mission-critical systems mixed-language environments mixins mock objects modeling, metaphors as moderator role in inspections modularity design goal of global variables, damage from modules, coupling considerations multiple inheritance multiple returns from routines multiple-file string search capability Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] named constants naming conventions "a" prefix convention [See declarations, naming; readability, naming variables for] abbreviating names abbreviation guidelines arrays benefits of C language 2nd C++ capitalization 2nd case-insensitive languages characters, hard to read checklist 2nd class member variables class vs. object names common operations, for constants cross-project benefits descriptiveness guideline documentation 2nd enumerated types 2nd 3rd files formality, degrees of function return values global variables 2nd homonyms Hungarian informal input parameters Java 2nd key points kinds of information in names language-independence guidelines length, not limiting Macintosh meanings in names, too similar misleading names misspelled words mixed-language considerations multiple natural languages numbers, differentiating solely by numerals opposites, use of parameters phonic abbreviations prefix standardization procedure descriptions proliferation reduction benefit pronunciation guideline purpose of readability relationships, emphasis of reserved names routines 2nd semantic prefixes short names 2nd similarity of names, too much spacing characters t_ prefix convention thesaurus, using types vs. variables names UDT abbreviations Visual Basic when to use nested if statements 2nd [See if statements, nested] converting to if-then-else statements factoring to routines factory method approach, converting to functional decomposition of object-oriented approach, converting to redesigning simplification by retesting conditions simplification with break blocks summary of techniques for reducing too many levels of nested loops designing 2nd ordering for performance nondeterministic nature of design process 2nd nonstandard language features null objects, refactoring null statements numbers, literal numeric data types BCD [See data types, numeric] checklist comparisons compiler warnings conversions, showing costs of operations declarations, commenting floating-point types 2nd 3rd hard coded 0s and 1s integers literal numbers, avoiding magic numbers, avoiding magnitudes, greatly different, operations with mixed-type comparisons overflows ranges of integers zero, dividing by Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] object-oriented programming resources for 2nd object-parameter coupling objectives, software quality 2nd objects ADTs as [See object-oriented programming, objects] attribute identification class names, differentiating from classes, contrasted to containment, identifying deleting objects factory methods 2nd 3rd identifying inheritance, identifying [See also inheritance] interfaces, designing [See also interfaces, class] operations, identifying parameters, using as 2nd protected interfaces, designing public vs. private members, designing real world, finding refactoring reference objects responsibilities, assigning to singleton property, enforcing steps in designing Observer pattern off-by-one errors boundary analysis fixing, approaches to offensive programming one-in, one-out control constructs operating systems operations, costs of common opposites for variable names optimization, premature [See also performance tuning] oracles, software out keyword creation overengineering overflows, integer overlay linkers overridable routines 2nd oyster farming metaphor Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] packages paging operations pair programming benefits of [See collaboration, pair programming] checklist coding standards support for compared to other collaboration defined inexperienced pairs key points pace, matching personality conflicts resources rotating pairs team leaders visibility of monitor watching when not to use parameters of routines abstraction and object parameters [See routines, parameters] actual, matching to formal asterisk (*) rule for pointers behavior dependence on by reference vs. by value checklist for, 185 C-library order commenting const prefix 2nd 3rd dependencies, clarifying documentation enumerated types for error variables formal, matching to actual global variables for guidelines for use in routines in keyword creation input-modify-output order Java list size as refactoring indicator matching actual to formal naming 2nd 3rd 4th 5th 6th number of, limiting objects, passing order for out keyword creation passing, types of refactoring 2nd status structures as using all of rule variables, using as Visual Basic parentheses balancing technique layout with Pareto Principle passing parameters patterns advantages of [See design, patterns, common] alternatives suggested by communications benefit complexity reduction with disadvantages of error reduction benefit Factory Method resource for table of people first theme performance appraisals performance tuning algorithm choice architecture prerequisites arrays 2nd checklist comments, effects on competing objectives dilemma 2nd compiler considerations 2nd correctness, importance of database indexing defects in code DES example design view feature specific hardware considerations inefficiency, sources of information hiding considerations of input/output interpreted vs. compiled languages key points lines of code, minimizing number of measurement of memory vs. file operations old wives' tales operating system considerations operations, costs of common overview of paging operations premature optimization program requirements view of purpose of quality of code, impact on resource goals resources routine design 2nd 3rd speed, importance of summary of approach for system calls timing issues user view of coding when to tune periodicals on programming Perl persistence of variables 2nd personal character perturbers phased integration phonic abbreviations of names PHP (PHP Hypertext Processor) 2nd physical environment for programmers planning analogy argument for building metaphor for data arguing for good practices table for logical argument for pointers & (pointer reference symbol) 2nd 3rd [See data types, pointers] –> (pointer symbol) address of 2nd allocation of 2nd 3rd alternatives to as function return values asterisk (*) rule auto_ptrs bounds checking tools C language C++ examples 2nd C++ guidelines checking before using 2nd checklist for comparisons with contents, interpretation of cover routines for dangers of 2nd data types pointed to deallocation of 2nd 3rd debugging aids declaring 2nd deleting 2nd diagramming dog tag fields explicit typing of explicitly redundant fields extra variables for clarity hiding operations with routines initializing 2nd 3rd interpretation of address contents isolating operations of key points languages not providing linked lists, deleting in location in memory memory corruption by memory parachutes null, setting to after deleting null, using as warnings overwriting memory with junk parts of passing by reference references, C++ resources for SAFE_ routines for simplifying complicated expressions sizeof() smart string operations in C type casting, avoiding variables referenced by, checking polymorphism case statements, replacing with [See object-oriented programming, polymorphism] defined language-specific rules nested ifs, converting to polynomial expressions portability data types, defining for defined routines for postconditions routine design with verification PPP (Pseudocode Programming Process) algorithms, researching [See pseudocode, PPP] alternates to checking for errors checklist for cleanup steps coding below comments coding routines from data structure for routines declarations from defined designing routines error handling considerations example for routines functionality from libraries header comments for routines high-level comments from iterating key points for naming routines performance considerations prerequisites problem definition refactoring removing errors repeating steps reviewing pseudocode stepping through code testing the code 2nd writing pseudocode step precedence, misleading preconditions routine design with verification prefixes, standardization of premature optimization preparation preprocessors C++ debugging aids, removing with purpose of writing prerequisites, upstream analogy argument for [See construction, prerequisites] boss readiness test checklist for choosing between iterative and sequential approaches coding too early mistake compelling argument for data arguing for error detection, doing early goal of good practices table for importance of incomplete preparation, causes of iterative and sequential mixes iterative methods with 2nd key points for kinds of projects logical argument for manager ignorance problem problem definition risk reduction goal skills required for success time allowed for WIMP syndrome WISCA syndrome Principle of Proximity 2nd private data problem domain, programming at problem-definition prerequisites problem-solving skills development procedural cohesion procedures naming guidelines for when to use processes, development productivity effects of good construction practice industry average size of projects, effects on professional development professional organizations program flow control of sequential program organization prerequisite program size programmers, character of programmers, treatment of overview physical environment privacy of offices religious issues resources on style issues time allocations variations in performance programming conventions choosing coding practices checklist programming into languages 2nd programming language choice Ada [See construction decisions, programming languages] assembly language Basic C C# C++ Cobol expressiveness of concepts familiar vs. unfamiliar languages Fortran higher- vs. lower-level language productivity importance of Java JavaScript Perl PHP productivity from programming into languages 2nd Python ratio of statements compared to C code, table of SQL thinking, effects on Visual Basic programming tools assembler listing tools [See construction, tools for; tools, programming] beautifiers build tools building your own CASE tools checklist class-hierarchy generators code libraries code tuning code-generation wizards compilers cross-reference tools data dictionaries debugging tools 2nd 3rd 4th dependency checkers design tools Diff tools disassemblers editing tools executable-code tools execution profiler tools fantasyland graphical design tools grep IDEs interface documentation key points linkers merge tools metrics reporters multiple-file string searches preprocessors project-specific tools purpose of quality analysis refactoring tools resources on restructuring tools scripts semantics checkers source-code tools syntax checkers templates testing tools tool-oriented environments translators version control tools project types, prerequisites corresponding to protected data prototyping 2nd Proximity, Principle of 2nd pseudocode algorithms, researching bad, example of benefits from changing, efficiency of checking for errors checklist for PPP classes, steps in creating coding below comments coding from comments from 2nd data structure for routines declarations from defined designing routines error handling considerations example for routines functionality from libraries good, example of guidelines for effective use header comments for routines high-level comments from iterative refinement 2nd key points for creating loop design naming routines performance considerations prerequisites problem definition refactoring reviewing routines, steps in creating 2nd testing, planning for Pseudocode Programming Process psychological distance psychological factors psychological set public data members pure blocks layout style Python description of performance issues Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] quality assurance checklist good practices table for prerequisites role in requirements checklist quality gates quality of software accuracy [See construction, quality of] adaptability change-control procedures checklist for correctness costs of finding defects costs of fixing defects debugging, role of 2nd detection of defects by various techniques, table of development process assurance activities efficiency engineering guidelines explicit activity for external audits external characteristics of Extreme Programming flexibility gates General Principle of Software Quality integrity internal characteristics key points maintainability measurement of results multiple defect detection techniques recommended objectives, setting 2nd optimization conflicts percentage of defects measurement portability programmer performance, objectives based prototyping readability recommended combination for relationships of characteristics reliability resources for reusability reviews robustness standards, IEEE 2nd testing 2nd 3rd understandability usability when to do assurance of Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] random-data generators readability as management standard defects exposing lack of defined importance of 2nd maintenance benefit from positive effects from private vs. public programs professional development, importance to structures, importance of warning sign, as a reading as a skill reading plan for software developers records, refactoring recursion alternatives to [See control structures, recursive] checklist defined factorials using Fibonacci numbers using guidelines for key points maze example safety counters for single routine guideline sorting example stack space concerns terminating refactoring 80/20 rule adding routines algorithms arrays backing up old code bidirectional class associations boolean expressions case statements checklists for 2nd checkpoints for class cohesion indicator class interfaces classes 2nd 3rd 4th code tuning, compared to collections comments on bad code complex modules conditional expressions constant values varying among subclass constructors to factory methods data from uncontrolled sources data sets, related, as indicator data types to classes data-level 2nd defects, fixes of defined designing code for future needs Don't Repeat Yourself principle duplicate code indicator error-prone modules expressions global variables GUI data if statements interfaces 2nd 3rd key points listing planned steps literal constants loops 2nd maintenance triggering middleman classes misuse of null objects objects one-at-a-time rule overloaded primitive data types parallel modifications required indicator parameters 2nd 3rd PPP coding step public data members queries reasons not to records redesigning instead of reference objects resources on reviews of risk levels of routines 2nd 3rd 4th safety guidelines 2nd setup code size guideline statement-level 2nd strategies for subclasses 2nd superclasses system-level 2nd takedown code testing to do lists for tools for tramp data ugly code, interfaces to unidirectional class associations unit tests for variables warnings, compiler references (&), C++ regression testing defined diff tools for purpose of reliability cohesive routines defined religious attitude toward programming eclecticism experimentation compared to harmful effects of layout styles becoming managing people software oracles reports requirements benefits of [See prerequisites, upstream, requirements development] business cases for change-control procedures checklists for 2nd coding without communicating changes in completeness, checklist configuration management of 2nd defined development approaches with development process effects on dumping projects errors in, effects of functional, checklist good practices table for importance of key point for nonfunctional, checklist performance tuning quality, checklist rate of change, typical resources on developing stability of 2nd testing for time allowed for resource management architecture for cleanup example restrictive nature of design restructuring tools retesting return statements checklist [See control structures, returns as] guard clauses key points multiple, from one routine readability resources for reusability architecture prerequisites defined reviewer role in inspections reviews code reading dog-and-pony shows educational aspect of every line of code rule formal inspections, compared to formal, quality from informal, defined iteration process, place in refactoring conducting after walk-throughs right shifting risk-oriented integration robustness architecture prerequisites assertions with error handling correctness, balanced against defined 2nd rounding errors routines abstract overridable [See classes, functions in; classes, methods of; classes, procedures in; classes, routines in] abstraction benefit abstraction with object parameters 2nd algorithm selection for 2nd alternates to PPP black-box testing of blank lines in boolean test benefit calculation to function example calls, costs of checking for errors checklists 2nd 3rd classes, converting to, criteria for cleanup steps code tuning coding from pseudocode cohesion coincidental cohesion commenting 2nd communicational cohesion compiling for errors complexity metric complexity reduction benefit construction step for classes continuations in call lines coupling considerations data states data structures for declarations defined descriptiveness guideline for naming design by contract designing 2nd documentation 2nd downcast objects duplication benefit endline layout error handling considerations errors in, relation to length of event handlers fields of objects, passing to files, layout in functional cohesion functionality from libraries functions, special considerations for hacking approach to header comments for high quality, counterexample high-level comments from pseudocode importance of in keyword creation indentation of inline input-modify-output parameter order interface statements internal design iterating pseudocode key points for 2nd layout of 2nd length of, guideline for limitations, documenting logical cohesion low-quality example mentally checking for errors multiple returns from named parameters in naming 2nd 3rd 4th nested deeply objects, passing to 2nd out keyword creation overridable vs. non-overridable routines overridden to do nothing overriding performance considerations 2nd pointer hiding benefit portability benefit postconditions PPP checklist for preconditions prerequisites problem definition procedural cohesion procedure naming guideline pseudocode writing step public, using in interfaces concern queries, refactoring reasons for creating, list of refactoring 2nd 3rd 4th reliability from cohesiveness removing errors repeating steps returns from, multiple reviewing pseudocode sequence hiding benefit sequential cohesion setup code for, refactoring similar parameters, order for similar, refactoring simple, usefulness of size as refactoring indicator small vs. large 2nd specification example stepping through code strength subclassing benefit temporal cohesion test-first development testing 2nd 3rd tramp data in unused, refactoring valid reasons for creating variable names, differentiating from wrong class, indicator for run time, binding during Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] safety counters in loops sandwich integration scaffolding debugging with testing 2nd scalability [See also size of projects] schedules, estimating scientific method, classic steps in SCM (software configuration management) [See also configuration management] scope of variables convenience argument [See variables, scope of] defined global scope, problems with grouping related statements key point language differences live time, minimizing localizing references to variables loop initializations manageability argument minimizing, guidelines for restrict and expand tactic span of variables value assignments variable names, effects on scribe role in inspections scripts programming tools, as slowness of SDFs (software development folders) security selections, code selective data self-documenting code 2nd semantic coupling semantic prefixes semantics checkers sentinel tests for loops sequences, code hiding with routines structured programming concept of sequential approach sequential cohesion Set() routines setup code, refactoring setup tools short-circuit evaluation 2nd side effects, C++ signing off on code simple-data-parameter coupling simple-object coupling single points of control single-statement blocks singleton property, enforcing 2nd size of projects activities, list of fastest growing [See construction, size of projects, effects on; managing construction, size of projects, effects of] activity types, effects on building metaphor for communications between people complexity, effect of defects created, effects on documentation requirements estimation errors formality requirements key points methodology considerations overview productivity, effects on ranges in resources on single product, multiple users single program, single user system products systems sizeof() sloppy processes smart pointers smoke tests software accretion metaphor software construction overview activities excluded from activities in, list of centralness to development process defined documentation by source code guaranteed done nature of importance of key points for main activities of percent of total development process productivity, importance in programming as programming vs.

. // [See documentation, comments] abbreviations in algorithms argument against authorship bad code, on blank lines around Book Paradigm for categories of checklists 2nd classes coded meanings control structures 2nd declarations with 2nd 3rd descriptions of code intent distance to code guideline efficient creation of endline comments errors, marking workarounds explanatory files flags, bit level global variables 2nd indentation guidelines individual lines with input data 2nd integrating into development interfaces, class interfaces, routine Javadoc 2nd key points layout guidelines legal notices length of descriptions level of code intent loops maintenance of 2nd 3rd major vs. minor markers non-code essential information numerical data optimum density of output data paragraphs of code with 2nd parameter declarations parts of programs performance considerations preceding code rule proportionality of pseudocode, deriving from 2nd 3rd purpose of repeating code with resources on routines with 2nd self-commenting code Socratic dialog about standards, IEEE style differences, managing style violations summaries of code surprises tricky code 2nd undocumented features variables version control why vs. how workarounds commitment delay strategy communication skills, importance of communicational cohesion communications, development team comparisons floating-point equality mixed data types compilers binding during compilation [See executable-code tools, compilers] broken builds data type warnings debugging tools, as 2nd errors, finding in routines line numbers, debugging with messages, treatment of 2nd multiple error messages optimizations by performance tuning considerations project-wide standards for speeds from optimization, table of tools for tricky code optimization validators with warnings 2nd completeness of requirements checklist complex data types complexity abstraction for handling classes for reducing coding conventions for reducing control structure contributions to conventions for managing decision points, counting importance of isolation, classes for live time management 2nd McCabe's metric mental objects held, measure of methods for handling minimization goal patterns, reducing with problem domain, working at reliability correlated with routines for reducing size of projects, effect on span component testing components, buying 2nd Composite pattern compound boundaries compound statements computed-value qualifiers of variable names computer-aided software engineering (CASE) tools conditional statements boolean function calls with [See control structures, conditional flow] boolean variables recommended chained if-then-else statements checklist common cases first guideline comparing performance of covering all cases defined eliminating testing redundancy else clauses equality, branching on error processing examples frequency, testing in order of key points lookup tables, substituting normal case first guideline normal path first guideline null if clauses plain if-then statements refactoring short-circuit evaluation confessional debugging configuration management architectural anticipation of change [See managing construction, change control; managing construction, configuration management] backup plans 2nd boards, change-control bureaucratic considerations checklist code changes cost, estimating defined design changes estimating change costs grouping change requests high change volumes identifying areas of change machine configurations, reproducing purpose of requirements changes 2nd 3rd resources on SCM tool version control version-control software const keyword, C++ 2nd 3rd 4th 5th constants checklist consistency rule declarations using defined emulation by global variables initializing literals, avoiding with naming 2nd 3rd purpose of refactoring simulating in languages lacking construction guidelines percent of total activity, by size of project resources on construction decisions checklist of major construction practices [See construction, decisions] coding practices checklist early-wave environments key points for major construction practices, selecting mature technology environments programming conventions programming into languages quality assurance checklist teamwork checklist technology waves, determining your location in tools checklist construction schedules, estimating approaches to, list of [See construction, schedules, estimating] catching up from behind controlling vs. estimating factors influencing level of detail for multiple techniques with comparisons objectives, establishing optimism overview planning estimation time reduction of scope reestimating requirements specification resources for teams, expanding constructors deep vs. shallow copies exceptions with guidelines for initializing data members refactoring singleton property, enforcing container classes containment 2nd continuation lines continue statements 2nd 3rd continuous integration control structures checklists 2nd 3rd commenting 2nd complexity, contributions to compound statements continuation lines in data types, relationship to documentation double indented begin-end pairs iteration 2nd key points layout styles multiple returns from routines null statements reliability correlated with complexity selective data with sequential data with structured programming unindented begin-end pairs unusual, overview of conventions, coding benefits of [See coding, conventions] checklist hazards, avoiding with predictability benefit converting data types cooperation skills, importance of correctness 2nd costs change estimates collaboration benefits debugging, time consumed by defects contributing to detection of defects error-prone routines estimating 2nd fixing of defects 2nd General Principle of Software Quality 2nd pair programming vs. inspections resources on counted loops coupling base classes to derived classes classes, too tightly design considerations flexibility of goals of loose 2nd object-parameter type semantic type simple-data-parameter type simple-object type size of visibility of coverage monitoring tools structured basis testing CRC (Class, Responsibility, Collaboration) cards creativity, importance of 2nd cross-reference tools curiosity, role in character Currency data types customization, building metaphor for Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] daily build and smoke tests automation of benefits of broken builds 2nd build groups checklist defined diagnosis benefit holding area for additions importance of morning releases pressure pretest requirement revisions smoke tests unsurfaced work data architecture prerequisites bad classes, testing for change, identifying areas of combined states defined state defined-used paths, testing design entered state exited state good classes, testing killed state legacy, compatibility with nominal case errors test, generators for used state data dictionaries data flow testing data literacy test data recorder tools data structures data transformations for code tuning array dimension minimization [See data, code tuning] array reference minimization caching data floating point to integers indexing data purpose of data types "a" prefix convention [See data, types; variables, types of] BCD change, identifying areas of checklist control structures, relationship to Currency definitions iterative data key points for naming 2nd 3rd overloaded primitives refactoring to classes 2nd resources on selective data sequential data t_ prefix convention variables of, differentiating from data-level refactoring 2nd databases performance issues SQL subsystem design days-in-month, determining deallocation goto statements for pointers, of 2nd 3rd Debug.Assert statements debugging binary searches of code [See defects in code, fixing; tools, debugging] blindness, sources of breakpoints breaks, taking brute-force changes, recent checklist comments, misplaced common defects lists compilers as tools for 2nd confessional debugging costs of 2nd debugger tools 2nd 3rd 4th [See also debugging aids] defects as opportunities defined Diff tool execution profilers for expanding suspicious regions experience of programmers, effects of finding defects 2nd fixing defects guessing history of hypothesis testing 2nd incremental approach ineffective approach to key points line numbers from compilers lint tool listing possibilities locating error sources logic checking tools multiple compiler messages narrowing code searches obvious fixes performance variations project-wide compilers settings psychological considerations quality of software, role in quotation marks, misplaced readability improvements recommended approach reexamining defect-prone code resources for Satan's helpers scaffolding for scientific method of self-knowledge from source-code comparators stabilizing errors superstitious approaches symbolic debuggers syntax checking 2nd 3rd system debuggers test case creation testing, compared to time for, setting maximums tools for 2nd 3rd 4th [See also debugging aids] understanding the problems unit tests varying test cases warnings, treating as errors debugging aids C++ preprocessors [See debugging, aids to; debugging, defensive] case statements early introduction recommended offensive programming planning removal of pointers, checking preprocessors production constraints in development versions purpose of stubs version control tools decision tables declarations 2nd 3rd [See variables, declaring] const recommended declare and define near first use rule define near first use rule final recommended formatting implicit declarations multiple on one line numerical data, commenting order of placement of pointers 2nd using all declared Decorator pattern defects in code classes prone to error [See errors, coding] classifications of clerical errors (typos) Code Complete example construction, proportion resulting from cost of detection cost of fixing databases of detection by various techniques, table of distribution of ease of fixing defects error checklists expected rate of finding, checklist intermittent misunderstood designs as sources for opportunities presented by outside of construction domain percentage of, measurement performance issues programmers at fault for readability improvements refactoring after fixing scope of self-knowledge from size of projects, effects on sources of, table stabilizing defensive programming assertions assumptions to check, list of barricades checklist debugging aids defined error handling for exceptions 2nd friendly messages guideline graceful crashing guideline guidelines for production code hard crash errors guideline important errors guideline key points for logging guideline problems caused by quality improvement techniques, other robustness vs. correctness security issues trivial errors guideline validating input defined data state defining variables Delphi, recoding to assembler DeMorgan's Theorems, applying dependencies, code-ordering checker tools [See sequences, code, order of] circular clarifying concept of documentation error checking hidden initialization order naming routines non-obvious organization of code parameters, effective design abstractions, forming consistent accidental problems BDUF beauty bottom-up approach to design business logic subsystem capturing work central points of control change, identifying areas of changes, management of characteristics of high quality checklists 2nd classes, division into collaboration communications among subsystems completion of, determining complexity management construction activity, as contract, by coupling considerations database access subsystem defined diagrams, drawing discussion, summarizing divide and conquer technique documentation overkill documentation, as emergent nature of encapsulation enough, determining essential problems extensibility goal formality of, determining formalizing class contracts goals checklist good practices table for hierarchies for high fan-in goal IEEE standards information hiding 2nd inheritance iteration practice key points leanness goal level of detail needed levels of loose coupling goal low-to-medium fan-out goal maintenance goals mental limitations of humans metrics, warning signs from nondeterministic nature of 2nd object-oriented, resource for objects, real world, finding packages level performance tuning considerations portability goal practices 2nd prioritizing during prototyping resources for restrictive nature of reusability goal routines, of sloppy process nature of software system level standard techniques goal standards, IEEE stratification goal strong cohesion subsystem level system dependencies subsystem testing for implementation tools for top-down approach tradeoffs UML diagrams user interface subsystem visual documentation of wicked problem nature of Wikis, capturing on destructors, exceptions with detailed-design documents developer testing development processes development standards, IEEE diagrams heuristic design use of UML Diff tools 2nd direct access tables advantages of [See table-driven methods, direct access] arrays for case statement approach days-in-month example defined design method for flexible-message-format example fudging keys for insurance rates example keys for object approach transforming keys disassemblers discipline, importance of discourse rules disposing of objects divide and conquer technique division Do loops [See also loops] documentation abbreviation of names ADTs for bad code, of Book Paradigm for capturing work checklists 2nd classes control structures CRC cards for dependencies, clarifying design as 2nd detailed-design documents external Javadoc 2nd key points names as 2nd 3rd organization of data parameter assumptions pseudocode, deriving from resources on routine parameter assumptions routines SDFs self-documenting code size of projects, effects of source code as standards, IEEE style differences, managing UDFs visual, of designs why vs. how dog tag fields dog-and-pony shows DoNothing() macros DRY (Don't Repeat Yourself) principle duplication avoiding with routines code as refactoring indicator Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] early-wave environments ease of maintenance design goal eclecticism editing tools beautifiers [See tools, editing] class-hierarchy generators cross-reference tools Diff tools grep IDEs interface documentation merge tools multiple-file string searches templates efficiency eighty/twenty (80/20) rule else clauses boolean function calls with case statements instead of chains, in common cases first guideline correctness testing default for covering all cases gotos with null embedded life-critical systems emergent nature of design process emulated pure blocks layout style encapsulation assumptions about users checklist classes, role for coupling classes too tightly downcast objects friend class concern heuristic design with minimizing accessibility private details in class interfaces public data members public members of classes public routines in interfaces concern semantic violations of weak endless loops 2nd endline comments endline layout 2nd 3rd enumerated types benefits of [See data types, enumerated types] booleans, alternative to C++ 2nd changes benefit checklist comments substituting for creating for Java defined emulation by global variables explicit value pitfalls first entry invalid trick iterating through Java, creating for languages available in loop limits with naming 2nd 3rd parameters using readability from reliability benefit standard for validation with Visual Basic equality, floating-point equivalence partitioning error codes error detection, doing early error guessing error handling architecture prerequisites [See errors, handling] assertions, compared to barricades buffer overruns compromising closest legal value defensive programming, techniques for error codes, returning error-processing routines, calling high-level design implication local handling logging warning messages messages 2nd 3rd next valid data, returning previous answers, reusing propagation design refactoring returning neutral values robustness 2nd routines, designing along with shutting down validation design error messages codes, returning design displaying friendly messages guideline errors 2nd classifications of dog tag fields goto statements for processing sources of, table essential problems estimating schedules approaches to, list of change costs control, compared to factors influencing inaccuracy, character-based level of detail for multiple techniques with comparisons objectives, establishing optimism overview planning for estimation time redoing periodically reduction of scope requirements specification resources for teams, expanding event handlers evolution Evolutionary Delivery exceptions [See errors, exceptions] abstraction issues alternatives to base classes for, project specific C++ centralized reporters constructors with defensive programming checklist destructors with empty catch blocks rule encapsulation, breaking full information rule Java languages, table comparing level of abstraction rule library code generation of local handling rule non-exceptional conditions purpose of 2nd readability of code using refactoring resources for standardizing use of Visual Basic 2nd executable-code tools build tools code libraries code-generation wizards installation tools linkers preprocessors setup tools execution profilers 2nd Exit Function [See also return statements] Exit statements Exit Sub [See also return statements] exiting loops 2nd experience, personal experimental prototyping experimentation as learning 2nd exponential expressions expressions constants, data types for initializing at compile time layout guidelines precomputing results right shifting strength reduction subexpression elimination system calls, performance of extensibility design goal external audits external documentation Extreme Programming collaboration component of defect detection defined resources on 2nd Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] Facade pattern factorials factoring [See also refactoring] factory methods Factory Method pattern nested ifs refactoring example refactoring to fan-in fan-out farming metaphor fault tolerance feature-oriented integration Fibonacci numbers files ADTs, treating as authorship records for C++ source file order deleting multiple example documenting layout within naming 2nd routines in final keyword, Java finally statements fixing defects checking fixes [See defects in code, fixing] checklist diagnosis confirmation hurrying, impact of initialization defects maintenance issues one change at a time rule reasoning for changes saving unfixed code similar defects, looking for special cases symptoms, fixing instead of problems understand first guideline unit tests for flags change, identifying areas of comments for bit-level meanings enumerated types for gotos, rewriting with names for semantic coupling with flexibility coupling criteria for defined floating-point data types accuracy limitations [See data types, floating-point] BCD checklist costs of operations equality comparisons magnitudes, greatly different, operations with rounding errors Visual Basic types for loops advantages of formatting 2nd indexes purpose of foreach loops 2nd formal inspections author role [See collaboration, formal inspections; collaboration, inspections; defects in code, formal inspections for detecting] benefit summary blame game checklist CMM Code Complete example compared to other collaboration defined egos in error checklists expected results from fine-tuning follow-up stage inspection meetings key points management role moderator role overview stage performance appraisals from planning stage preparation stage procedure for rate of code review reports resources for reviewer role reviews, compared to rework stage roles in scenarios approach scribe role stages of three-hour solutions meeting formal technical reviews formatting code Fortran functional cohesion functional specification functions calculations converted to example [See classes, functions in] defined disallowing key point for naming conventions for 2nd private, overriding return values, setting status as return value when to use Fundamental Theorem of Formatting Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] General Principle of Software Quality collaboration effects costs debugging defined global variables aliasing problems with [See variables, global] alternatives to annotating changes to, inadvertent checklist for class variable alternatives code reuse problems commenting 2nd enumerated types emulation by g_ prefix guideline hiding implementation in classes information hiding problems with initialization problems intermediate results, avoiding key points local first guideline locking modularity damaged by named constants emulation by naming 2nd 3rd 4th 5th 6th objects for, monster overview of persistence of preservation of values with re-entrant code problems refactoring risk reduction strategies routines using as parameters semantic coupling with streamlining data use with tramp data, eliminating with god classes gonzo programming good data, testing goto statements Ada, inclusion in [See control structures, gotos] advantages of alternatives compared with checklist deallocation with disadvantages of duplicate code, eliminating with else clauses with error processing with Fortran's use of forward direction guideline guidelines indentation problem with key points layout guidelines legitimate uses of optimization problem with phony debating about readability issue resources for rewritten with nested ifs rewritten with status variables rewritten with try-finally trivial rewrite example unused labels graphical design tools grep growing a system metaphor GUIs (graphical user interfaces) architecture prerequisites refactoring data from subsystem design Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] habits of programmers hacking approach to design hardware dependencies, changing performance enhancement with has a relationships heuristic design abstractions, forming consistent [See design, heuristic; design, practice heuristics; heuristics, design with] alternatives from patterns avoiding failure binding time considerations bottom-up approach to design brute force capturing work central points of control change, identifying areas of checklist for collaboration communications benefit from patterns completion of, determining coupling considerations diagrams, drawing divide and conquer technique encapsulation error reduction with patterns formality of, determining formalizing class contracts goals checklist guidelines for using hierarchies for information hiding 2nd inheritance interfaces, formalizing as contracts iteration practice key points level of detail needed modularity multiple approach suggestion nature of design process nondeterministic basis for object-oriented, resource for objects, real world, finding patterns 2nd practices 2nd prototyping resources for responsibilities, assigning to objects strong cohesion summary list of rules testing, anticipating top-down approach 2nd heuristics algorithms compared to error guessing hiding hierarchies, benefits of high fan-in design goal human aspects of software development humility, role in character 2nd 3rd Hungarian naming convention hybrid coupling of variables Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] I/O (input/output) architecture prerequisites change, identifying areas of performance considerations IDEs (Integrated Development Environments) IEEE (Institute for Electric and Electrical Engineers) if statements boolean function calls with [See conditional statements, if statements; control structures, if statements] break blocks, simplification with case statements, compared to 2nd case statements, converting to 2nd chains of checklist common cases first guideline continuation lines in covering all cases else clauses 2nd equality, branching on error processing examples factoring to routines flipped frequency, testing in order of gotos rewritten with 2nd if-then-else statements, converting to key points lookup tables, substituting multiple returns nested in negatives in, making positive normal case first guideline normal path first guideline null if clauses plain if-then statements refactoring simplification single-statement layout tables, replacing with types of implicit declarations implicit instancing in keyword, creating incomplete preparation, causes of incremental development metaphor incremental integration benefits of [See integration, incremental] bottom-up strategy classes 2nd customer relations benefit defined disadvantages of top-down strategy errors, locating feature-oriented integration interface specification 2nd progress monitoring benefit resources on results, early risk-oriented integration sandwich strategy scheduling benefits slices approach steps in strategies for, overview stubs 2nd summary of approaches T-shaped integration test drivers top-down strategy for vertical-slice approach indentation 2nd indexed access tables 2nd indexes, loop alterations checklist enumerated types for final values scope of variable names indexes, supplementing data types with infinite loops 2nd informal reviews 2nd information hiding access routines for [See object-oriented programming, hiding information] ADTs for barriers to categories of secrets circular dependencies problem class data mistaken for global data class design considerations class implementation details example excessive distribution problem importance of interfaces, class performance issues privacy rights of classes resources for secrets concept type creation for inheritance access privileges from [See object-oriented programming, inheritance] case statements checklist containment compared to decisions involved in deep trees defined design rule for functions, private, overriding guidelines, list of heuristic design with identifying as a design step is a relationships key points for Liskov Substitution Principle main goal of mixins multiple overridable vs. non-overridable routines parallel modifications refactoring indicator placement of common items in tree private vs. protected data private, avoiding recommended bias against routines overridden to do nothing similar sub and super classes single-instance classes initializing variables accumulators at declaration guideline C++ example checklist for class members compiler settings consequences of failing to const recommended constants counters declare and define near first use rule final recommended first use guideline fixing defects global variables importance of Java example key point loops, variables used in parameter validity pointer problems 2nd 3rd Principle of Proximity reinitialization strings system perturbers, testing with Visual Basic examples initializing working memory inline routines input parameters input/output inspections installation tools instancing objects ADTs factory method singleton 2nd integer data types checklist [See data types, integers] costs of operations division considerations overflows ranges of Integrated Development Environments (IDEs) integration benefits of 2nd big-bang bottom-up strategy broken builds checklist classes 2nd 3rd continuous customer relations daily build and smoke test defined disadvantages of top-down strategy errors, locating feature-oriented strategy importance of approach methods interface specification 2nd key points monitoring phased resources on risk-oriented strategy sandwich strategy scheduling slices approach smoke tests strategies for, overview stubs 2nd summary of approaches T-shaped integration testing 2nd top-down strategy for unsurfaced work vertical-slice approach integrity intellectual honesty intellectual toolbox approach intelligence, role in character interfaces, class abstraction aspect of 2nd 3rd calls to classes, refactoring cohesion consistent level of abstraction delegation vs. inheritance, refactoring documenting 2nd erosion under modification problem evaluating abstraction of extension classes, refactoring with foreign routines, refactoring with formalizing as contracts good abstraction example guidelines for creating inconsistency with members problem inconsistent abstraction, example of information hiding role integration, specification during 2nd key points for layout of mixins objects, designing for opposites, pairs of poor abstraction example private details in programmatic preferred to semantic public routines in interfaces concern read-time convenience rule refactoring 2nd routines, moving to refactor routines, unused semantic violations of encapsulation unrelated information, handling interfaces, graphic interfaces, routine commenting foreign routines, refactoring with pseudocode for public member variables routines, hiding routines, moving to refactor internationalization interoperability interpreted languages, performance of invalid input iteration in development choosing, reasons for [See approaches to development, iterative approach] code tuning design practice Extreme Programming importance of prerequisites 2nd pseudocode component of sequential approach compared iteration, code foreach loops 2nd iterative data iterator loops, defined Iterator pattern structured programming concept of Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] jamming loops Java assertion example in boolean expression syntax description of exceptions layout recommended live time examples naming conventions for 2nd parameters example persistence of variables resources for Javadoc 2nd JavaScript JUnit just in time binding Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] key construction decisions killed data state kinds of software projects Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] languages, programming Law of Demeter layout array references [See coding, style; conventions, coding, formatting; programming conventions, formatting rules; readability, formatting for; style issues, formatting] assignment statement continuations begin-end pairs blank lines 2nd block style brace styles 2nd C++ side effects checklist classes closely related statement elements comments complicated expressions consistency requirement continuing statements control statement continuations control structure styles declarations discourse rules documentation in code double indented begin-end pairs emulating pure blocks endline layout 2nd ends of continuations files, within Fundamental Theorem of Formatting gotos incomplete statements indentation interfaces key points language-specific guidelines logical expressions logical structure, reflecting 2nd mediocre example misleading indentation example misleading precedence modifications guideline multiple statements per line negative examples objectives of parentheses for pointers, C++ pure blocks style readability goal religious aspects of resources on routine arguments routine call continuations routine guidelines self-documenting code single-statement blocks statement continuation statement length structures, importance of styles overview unindented begin-end pairs violations of, commenting Visual Basic blocking style white space 2nd 3rd laziness lazy evaluation leanness design goal legal notices length of variable names, optimum levels of design business logic subsystem classes, divisions into database access subsystem overview of packages routines software system subsystems system dependencies subsystem user interface subsystem libraries, code purpose of using functionality from life-cycle models development standard good practices table for linked lists deleting pointers node insertion pointers, isolating operations of linkers lint tool Liskov Substitution Principle (LSP) literal data 2nd literate programs live time of variables 2nd load time, binding during localization architecture prerequisites string data types locking global data logarithms logging defensive programming guideline tools for testing logic coverage testing logical cohesion logical expressions code tuning comparing performance of eliminating testing redundancy frequency, testing in order of identities layout of lazy evaluation lookup tables, substituting short-circuit evaluation loops abnormal [See conditional statements, looping, conditional; control structures, loops] arrays with bodies of, processing 2nd brackets recommended break statements 2nd 3rd checklist code tuning commenting completion tests, location of compound, simplifying continuation lines in continue statements 2nd 3rd continuously evaluated loops [See also while loops] counted loops [See also for loops] cross talk defined designing, process for do loops empty, avoiding endless loops 2nd endpoint considerations entering, guidelines for 2nd enumerated types for exit guidelines 2nd 3rd for loops 2nd 3rd 4th foreach loops 2nd fusion of goto with housekeeping statements index alterations index checklist index final values index scope index variable names infinite loops 2nd initialization code for 2nd iterative data structures with iterator loops 2nd jamming key points kinds of, generalized labeled break statements language-specific, table of length of minimizing work inside multiple break statements naming variables nested 2nd 3rd null statements, rewriting off-by-one errors one-function guideline order of nesting performance considerations pointers inside problems with, overview of pseudocode method refactoring 2nd repeat until clauses routines in safety counters with scope of indexes sentinel tests for size as refactoring indicator strength reduction switching termination, making obvious testing redundancy, eliminating unrolling unswitching variable guidelines variable initializations variables checklist verifying termination while loops loose coupling design goal, as strategies for low-to-medium fan-out design goal LSP (Liskov Substitution Principle) Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] Macintosh naming conventions macro routines alternatives for [See routines, macro] limitations on multiple statements in naming 2nd parentheses with magazines on programming magic variables, avoiding 2nd 3rd maintenance comments requiring design goal for error-prone routines, prioritizing for fixing defects, problems from maintainability defined readability benefit for structures for reducing major construction practices checklist managing construction code ownership attitudes [See construction, managing] complexity good coding, encouraging inspections, management role in key points managers measurements programmers, treatment of readability standard resources on reviewing all code rewarding good practices schedules, estimating signing off on code standards, authority to set standards, IEEE 2nd two-person teams markers, defects from matrices mature technology environments maximum normal configurations maze recursion example McCabe's complexity metric 2nd measure twice, cut once measurement advantages of arguing against goals for outlier identification resources for side effects of table of useful types of memory allocation, error detection for corruption by pointers fillers initializing working paging operation performance impact pointers, corruption by tools for mentoring merge tools metaphors, software accreting a system algorithmic use of 2nd building metaphor building vs. buying components combining computer-centric vs. data-centric views customization discoveries based on earth centric vs. sun centric views examples of farming growing a system heuristic use of importance of incremental development key points for modeling use for overextension of oyster farming pendulum example power of readability relative merits of 2nd simple vs. complex structures size of projects throwing one away toolbox approach using writing code example methodologies [See also approaches to development] methods metrics reporters minimum normal configurations mission-critical systems mixed-language environments mixins mock objects modeling, metaphors as moderator role in inspections modularity design goal of global variables, damage from modules, coupling considerations multiple inheritance multiple returns from routines multiple-file string search capability Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] named constants naming conventions "a" prefix convention [See declarations, naming; readability, naming variables for] abbreviating names abbreviation guidelines arrays benefits of C language 2nd C++ capitalization 2nd case-insensitive languages characters, hard to read checklist 2nd class member variables class vs. object names common operations, for constants cross-project benefits descriptiveness guideline documentation 2nd enumerated types 2nd 3rd files formality, degrees of function return values global variables 2nd homonyms Hungarian informal input parameters Java 2nd key points kinds of information in names language-independence guidelines length, not limiting Macintosh meanings in names, too similar misleading names misspelled words mixed-language considerations multiple natural languages numbers, differentiating solely by numerals opposites, use of parameters phonic abbreviations prefix standardization procedure descriptions proliferation reduction benefit pronunciation guideline purpose of readability relationships, emphasis of reserved names routines 2nd semantic prefixes short names 2nd similarity of names, too much spacing characters t_ prefix convention thesaurus, using types vs. variables names UDT abbreviations Visual Basic when to use nested if statements 2nd [See if statements, nested] converting to if-then-else statements factoring to routines factory method approach, converting to functional decomposition of object-oriented approach, converting to redesigning simplification by retesting conditions simplification with break blocks summary of techniques for reducing too many levels of nested loops designing 2nd ordering for performance nondeterministic nature of design process 2nd nonstandard language features null objects, refactoring null statements numbers, literal numeric data types BCD [See data types, numeric] checklist comparisons compiler warnings conversions, showing costs of operations declarations, commenting floating-point types 2nd 3rd hard coded 0s and 1s integers literal numbers, avoiding magic numbers, avoiding magnitudes, greatly different, operations with mixed-type comparisons overflows ranges of integers zero, dividing by Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] object-oriented programming resources for 2nd object-parameter coupling objectives, software quality 2nd objects ADTs as [See object-oriented programming, objects] attribute identification class names, differentiating from classes, contrasted to containment, identifying deleting objects factory methods 2nd 3rd identifying inheritance, identifying [See also inheritance] interfaces, designing [See also interfaces, class] operations, identifying parameters, using as 2nd protected interfaces, designing public vs. private members, designing real world, finding refactoring reference objects responsibilities, assigning to singleton property, enforcing steps in designing Observer pattern off-by-one errors boundary analysis fixing, approaches to offensive programming one-in, one-out control constructs operating systems operations, costs of common opposites for variable names optimization, premature [See also performance tuning] oracles, software out keyword creation overengineering overflows, integer overlay linkers overridable routines 2nd oyster farming metaphor Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] packages paging operations pair programming benefits of [See collaboration, pair programming] checklist coding standards support for compared to other collaboration defined inexperienced pairs key points pace, matching personality conflicts resources rotating pairs team leaders visibility of monitor watching when not to use parameters of routines abstraction and object parameters [See routines, parameters] actual, matching to formal asterisk (*) rule for pointers behavior dependence on by reference vs. by value checklist for, 185 C-library order commenting const prefix 2nd 3rd dependencies, clarifying documentation enumerated types for error variables formal, matching to actual global variables for guidelines for use in routines in keyword creation input-modify-output order Java list size as refactoring indicator matching actual to formal naming 2nd 3rd 4th 5th 6th number of, limiting objects, passing order for out keyword creation passing, types of refactoring 2nd status structures as using all of rule variables, using as Visual Basic parentheses balancing technique layout with Pareto Principle passing parameters patterns advantages of [See design, patterns, common] alternatives suggested by communications benefit complexity reduction with disadvantages of error reduction benefit Factory Method resource for table of people first theme performance appraisals performance tuning algorithm choice architecture prerequisites arrays 2nd checklist comments, effects on competing objectives dilemma 2nd compiler considerations 2nd correctness, importance of database indexing defects in code DES example design view feature specific hardware considerations inefficiency, sources of information hiding considerations of input/output interpreted vs. compiled languages key points lines of code, minimizing number of measurement of memory vs. file operations old wives' tales operating system considerations operations, costs of common overview of paging operations premature optimization program requirements view of purpose of quality of code, impact on resource goals resources routine design 2nd 3rd speed, importance of summary of approach for system calls timing issues user view of coding when to tune periodicals on programming Perl persistence of variables 2nd personal character perturbers phased integration phonic abbreviations of names PHP (PHP Hypertext Processor) 2nd physical environment for programmers planning analogy argument for building metaphor for data arguing for good practices table for logical argument for pointers & (pointer reference symbol) 2nd 3rd [See data types, pointers] –> (pointer symbol) address of 2nd allocation of 2nd 3rd alternatives to as function return values asterisk (*) rule auto_ptrs bounds checking tools C language C++ examples 2nd C++ guidelines checking before using 2nd checklist for comparisons with contents, interpretation of cover routines for dangers of 2nd data types pointed to deallocation of 2nd 3rd debugging aids declaring 2nd deleting 2nd diagramming dog tag fields explicit typing of explicitly redundant fields extra variables for clarity hiding operations with routines initializing 2nd 3rd interpretation of address contents isolating operations of key points languages not providing linked lists, deleting in location in memory memory corruption by memory parachutes null, setting to after deleting null, using as warnings overwriting memory with junk parts of passing by reference references, C++ resources for SAFE_ routines for simplifying complicated expressions sizeof() smart string operations in C type casting, avoiding variables referenced by, checking polymorphism case statements, replacing with [See object-oriented programming, polymorphism] defined language-specific rules nested ifs, converting to polynomial expressions portability data types, defining for defined routines for postconditions routine design with verification PPP (Pseudocode Programming Process) algorithms, researching [See pseudocode, PPP] alternates to checking for errors checklist for cleanup steps coding below comments coding routines from data structure for routines declarations from defined designing routines error handling considerations example for routines functionality from libraries header comments for routines high-level comments from iterating key points for naming routines performance considerations prerequisites problem definition refactoring removing errors repeating steps reviewing pseudocode stepping through code testing the code 2nd writing pseudocode step precedence, misleading preconditions routine design with verification prefixes, standardization of premature optimization preparation preprocessors C++ debugging aids, removing with purpose of writing prerequisites, upstream analogy argument for [See construction, prerequisites] boss readiness test checklist for choosing between iterative and sequential approaches coding too early mistake compelling argument for data arguing for error detection, doing early goal of good practices table for importance of incomplete preparation, causes of iterative and sequential mixes iterative methods with 2nd key points for kinds of projects logical argument for manager ignorance problem problem definition risk reduction goal skills required for success time allowed for WIMP syndrome WISCA syndrome Principle of Proximity 2nd private data problem domain, programming at problem-definition prerequisites problem-solving skills development procedural cohesion procedures naming guidelines for when to use processes, development productivity effects of good construction practice industry average size of projects, effects on professional development professional organizations program flow control of sequential program organization prerequisite program size programmers, character of programmers, treatment of overview physical environment privacy of offices religious issues resources on style issues time allocations variations in performance programming conventions choosing coding practices checklist programming into languages 2nd programming language choice Ada [See construction decisions, programming languages] assembly language Basic C C# C++ Cobol expressiveness of concepts familiar vs. unfamiliar languages Fortran higher- vs. lower-level language productivity importance of Java JavaScript Perl PHP productivity from programming into languages 2nd Python ratio of statements compared to C code, table of SQL thinking, effects on Visual Basic programming tools assembler listing tools [See construction, tools for; tools, programming] beautifiers build tools building your own CASE tools checklist class-hierarchy generators code libraries code tuning code-generation wizards compilers cross-reference tools data dictionaries debugging tools 2nd 3rd 4th dependency checkers design tools Diff tools disassemblers editing tools executable-code tools execution profiler tools fantasyland graphical design tools grep IDEs interface documentation key points linkers merge tools metrics reporters multiple-file string searches preprocessors project-specific tools purpose of quality analysis refactoring tools resources on restructuring tools scripts semantics checkers source-code tools syntax checkers templates testing tools tool-oriented environments translators version control tools project types, prerequisites corresponding to protected data prototyping 2nd Proximity, Principle of 2nd pseudocode algorithms, researching bad, example of benefits from changing, efficiency of checking for errors checklist for PPP classes, steps in creating coding below comments coding from comments from 2nd data structure for routines declarations from defined designing routines error handling considerations example for routines functionality from libraries good, example of guidelines for effective use header comments for routines high-level comments from iterative refinement 2nd key points for creating loop design naming routines performance considerations prerequisites problem definition refactoring reviewing routines, steps in creating 2nd testing, planning for Pseudocode Programming Process psychological distance psychological factors psychological set public data members pure blocks layout style Python description of performance issues Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] quality assurance checklist good practices table for prerequisites role in requirements checklist quality gates quality of software accuracy [See construction, quality of] adaptability change-control procedures checklist for correctness costs of finding defects costs of fixing defects debugging, role of 2nd detection of defects by various techniques, table of development process assurance activities efficiency engineering guidelines explicit activity for external audits external characteristics of Extreme Programming flexibility gates General Principle of Software Quality integrity internal characteristics key points maintainability measurement of results multiple defect detection techniques recommended objectives, setting 2nd optimization conflicts percentage of defects measurement portability programmer performance, objectives based prototyping readability recommended combination for relationships of characteristics reliability resources for reusability reviews robustness standards, IEEE 2nd testing 2nd 3rd understandability usability when to do assurance of Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] random-data generators readability as management standard defects exposing lack of defined importance of 2nd maintenance benefit from positive effects from private vs. public programs professional development, importance to structures, importance of warning sign, as a reading as a skill reading plan for software developers records, refactoring recursion alternatives to [See control structures, recursive] checklist defined factorials using Fibonacci numbers using guidelines for key points maze example safety counters for single routine guideline sorting example stack space concerns terminating refactoring 80/20 rule adding routines algorithms arrays backing up old code bidirectional class associations boolean expressions case statements checklists for 2nd checkpoints for class cohesion indicator class interfaces classes 2nd 3rd 4th code tuning, compared to collections comments on bad code complex modules conditional expressions constant values varying among subclass constructors to factory methods data from uncontrolled sources data sets, related, as indicator data types to classes data-level 2nd defects, fixes of defined designing code for future needs Don't Repeat Yourself principle duplicate code indicator error-prone modules expressions global variables GUI data if statements interfaces 2nd 3rd key points listing planned steps literal constants loops 2nd maintenance triggering middleman classes misuse of null objects objects one-at-a-time rule overloaded primitive data types parallel modifications required indicator parameters 2nd 3rd PPP coding step public data members queries reasons not to records redesigning instead of reference objects resources on reviews of risk levels of routines 2nd 3rd 4th safety guidelines 2nd setup code size guideline statement-level 2nd strategies for subclasses 2nd superclasses system-level 2nd takedown code testing to do lists for tools for tramp data ugly code, interfaces to unidirectional class associations unit tests for variables warnings, compiler references (&), C++ regression testing defined diff tools for purpose of reliability cohesive routines defined religious attitude toward programming eclecticism experimentation compared to harmful effects of layout styles becoming managing people software oracles reports requirements benefits of [See prerequisites, upstream, requirements development] business cases for change-control procedures checklists for 2nd coding without communicating changes in completeness, checklist configuration management of 2nd defined development approaches with development process effects on dumping projects errors in, effects of functional, checklist good practices table for importance of key point for nonfunctional, checklist performance tuning quality, checklist rate of change, typical resources on developing stability of 2nd testing for time allowed for resource management architecture for cleanup example restrictive nature of design restructuring tools retesting return statements checklist [See control structures, returns as] guard clauses key points multiple, from one routine readability resources for reusability architecture prerequisites defined reviewer role in inspections reviews code reading dog-and-pony shows educational aspect of every line of code rule formal inspections, compared to formal, quality from informal, defined iteration process, place in refactoring conducting after walk-throughs right shifting risk-oriented integration robustness architecture prerequisites assertions with error handling correctness, balanced against defined 2nd rounding errors routines abstract overridable [See classes, functions in; classes, methods of; classes, procedures in; classes, routines in] abstraction benefit abstraction with object parameters 2nd algorithm selection for 2nd alternates to PPP black-box testing of blank lines in boolean test benefit calculation to function example calls, costs of checking for errors checklists 2nd 3rd classes, converting to, criteria for cleanup steps code tuning coding from pseudocode cohesion coincidental cohesion commenting 2nd communicational cohesion compiling for errors complexity metric complexity reduction benefit construction step for classes continuations in call lines coupling considerations data states data structures for declarations defined descriptiveness guideline for naming design by contract designing 2nd documentation 2nd downcast objects duplication benefit endline layout error handling considerations errors in, relation to length of event handlers fields of objects, passing to files, layout in functional cohesion functionality from libraries functions, special considerations for hacking approach to header comments for high quality, counterexample high-level comments from pseudocode importance of in keyword creation indentation of inline input-modify-output parameter order interface statements internal design iterating pseudocode key points for 2nd layout of 2nd length of, guideline for limitations, documenting logical cohesion low-quality example mentally checking for errors multiple returns from named parameters in naming 2nd 3rd 4th nested deeply objects, passing to 2nd out keyword creation overridable vs. non-overridable routines overridden to do nothing overriding performance considerations 2nd pointer hiding benefit portability benefit postconditions PPP checklist for preconditions prerequisites problem definition procedural cohesion procedure naming guideline pseudocode writing step public, using in interfaces concern queries, refactoring reasons for creating, list of refactoring 2nd 3rd 4th reliability from cohesiveness removing errors repeating steps returns from, multiple reviewing pseudocode sequence hiding benefit sequential cohesion setup code for, refactoring similar parameters, order for similar, refactoring simple, usefulness of size as refactoring indicator small vs. large 2nd specification example stepping through code strength subclassing benefit temporal cohesion test-first development testing 2nd 3rd tramp data in unused, refactoring valid reasons for creating variable names, differentiating from wrong class, indicator for run time, binding during Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] safety counters in loops sandwich integration scaffolding debugging with testing 2nd scalability [See also size of projects] schedules, estimating scientific method, classic steps in SCM (software configuration management) [See also configuration management] scope of variables convenience argument [See variables, scope of] defined global scope, problems with grouping related statements key point language differences live time, minimizing localizing references to variables loop initializations manageability argument minimizing, guidelines for restrict and expand tactic span of variables value assignments variable names, effects on scribe role in inspections scripts programming tools, as slowness of SDFs (software development folders) security selections, code selective data self-documenting code 2nd semantic coupling semantic prefixes semantics checkers sentinel tests for loops sequences, code hiding with routines structured programming concept of sequential approach sequential cohesion Set() routines setup code, refactoring setup tools short-circuit evaluation 2nd side effects, C++ signing off on code simple-data-parameter coupling simple-object coupling single points of control single-statement blocks singleton property, enforcing 2nd size of projects activities, list of fastest growing [See construction, size of projects, effects on; managing construction, size of projects, effects of] activity types, effects on building metaphor for communications between people complexity, effect of defects created, effects on documentation requirements estimation errors formality requirements key points methodology considerations overview productivity, effects on ranges in resources on single product, multiple users single program, single user system products systems sizeof() sloppy processes smart pointers smoke tests software accretion metaphor software construction overview activities excluded from activities in, list of centralness to development process defined documentation by source code guaranteed done nature of importance of key points for main activities of percent of total development process productivity, importance in programming as programming vs.


pages: 290 words: 119,172

Beginning Backbone.js by James Sugrue

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Airbnb, continuous integration, don't repeat yourself, Firefox, Google Chrome, loose coupling, MVC pattern, node package manager, single page application, web application, Y Combinator

Tweet = Backbone.Model.extend({   timestamp: null, initialize: function(){ timestamp = new Date(); },   getTimestamp: function(){ var friendly = moment(timestamp).fromNow(); return friendly; }   });   var tweet = new Tweet({text: 'James'});   var tweetView = new com.apress.view.TweetView({tweet: tweet});   Even in cases where you do not need to update parts of the view at specified intervals, splitting up the render function will make your code more readable to others and reduce the risk of the view code becoming unmaintainable. Reduce Template Bloat with Partials As an application grows, there will undoubtedly be some repetition in the definition of your templates as parts of some templates are copied into newer ones. This can lead to maintenance problems and breaks the well-respected Don’t Repeat Yourself (DRY) principle of software development. This section will look at the solutions available in both Handlebars and Underscore. Partials in Handlebars Handlebars provides out-of-the-box support for partials through the registerPartial function. When one template includes another partial template in its definition, the {{> partialname}} helper is used to place it in the correct location. The following timeline template example shows how this would be possible:   <script id='timeline-template' type='text/x-handlebars-template'> {{#each tweetlist}} {{> tweet}} {{/each}} </script>   238 Chapter 11 ■ Best Practices with Backbone The template expects another partial to be registered, with the name tweet.


pages: 761 words: 80,914

Ansible: Up and Running: Automating Configuration Management and Deployment the Easy Way by Lorin Hochstein

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Amazon Web Services, cloud computing, continuous integration, Debian, DevOps, domain-specific language, don't repeat yourself, general-purpose programming language, Infrastructure as a Service, job automation, pull request, side project, smart transportation, web application

Using the file lookup as a loop - name: Add my public key as an EC2 key ec2_key: name=mykey key_material="{{ item }}" with_file: /Users/lorinhochstein/.ssh/id_rsa.pub Typically, you’d only use a lookup plug-in as a looping construct if it returns a list, which is how I was able to separate out the plug-ins into Table 7-5 (return strings) and Table 7-6 (return lists). We covered a lot of ground in this chapter. In the next one, we’ll discuss roles, a convenient mechanism for organizing your playbooks. 1 Thanks to John Jarvis for this tip. 2 Don’t Repeat Yourself, a term popularized by The Pragmatic Programmer: From Journeyman to Master, which is a fantastic book. 3 etcd is a distributed key-value store, and is maintained by the CoreOS project. 4 If this sounds like gibberish, don’t worry about it; it’s just an example of running a command. 5 DNS service providers typically have web interfaces to let you perform DNS-related tasks such as creating TXT records.


pages: 555 words: 119,733

Autotools by John Calcote

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Albert Einstein, card file, Debian, delayed gratification, don't repeat yourself, en.wikipedia.org, Everything should be made as simple as possible, place-making, Richard Feynman, Richard Feynman, Valgrind

Example 6-4. libjup/jup_print.c: The initial contents of the shared-library source file #include <libjupiter.h> #include <jupcommon.h> int jupiter_print(const char * name) { print_routine(name); } Example 6-5. include/libjupiter.h: The initial contents of the shared-library public header file #ifndef LIBJUPITER_H_INCLUDED #define LIBJUPITER_H_INCLUDED int jupiter_print(const char * name); #endif /* LIBJUPITER_H_INCLUDED */ This leads us to another general software engineering principle. I've heard it called by many names, but the one I tend to use the most is the DRY principle—the acronym stands for don't repeat yourself. C function prototypes are very useful because, when used correctly, they enforce the fact that the public's view of a function is identical to the package maintainer's view. All too often, I've seen source files that don't include their corresponding header files. It's easy to make a small change in a function or prototype and then not duplicate it in the other location—unless you've included the public header file within the source file.


pages: 1,201 words: 233,519

Coders at Work by Peter Seibel

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Ada Lovelace, bioinformatics, cloud computing, Conway's Game of Life, domain-specific language, don't repeat yourself, Donald Knuth, fault tolerance, Fermat's Last Theorem, Firefox, George Gilder, glass ceiling, Guido van Rossum, HyperCard, information retrieval, Larry Wall, loose coupling, Marc Andreessen, Menlo Park, Metcalfe's law, Perl 6, premature optimization, publish or perish, random walk, revision control, Richard Stallman, rolodex, Ruby on Rails, Saturday Night Live, side project, slashdot, speech recognition, the scientific method, Therac-25, Turing complete, Turing machine, Turing test, type inference, Valgrind, web application

For whatever reason, I realized even back then that a program has to be readable. And that hasn't changed. Seibel: And what has changed? Bloch: Well, it's hard to make your programs readable when you're restricted to single-character variable names. So I worry more about variable naming now. Obviously, as you use languages with new features, many things change. And things that you vaguely understood over the years really get slammed home. For example, don't repeat yourself. I was freer with the copy-and-paste back then than I am now. Now I really try not to do it at all. That's a little bit of an overstatement, but only a little bit. Generally speaking, if I find myself copying and pasting, I think, ”What's wrong with this design? How can I fix it?” So that's something that took a little while to get right. Basically I've become harder on myself over the years—that's what it takes to write good programs.


pages: 999 words: 194,942

Clojure Programming by Chas Emerick, Brian Carper, Christophe Grand

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

Amazon Web Services, Benoit Mandelbrot, cloud computing, continuous integration, database schema, domain-specific language, don't repeat yourself, en.wikipedia.org, failed state, finite state, Firefox, game design, general-purpose programming language, Guido van Rossum, Larry Wall, mandelbrot fractal, Paul Graham, platform as a service, premature optimization, random walk, Ruby on Rails, Schrödinger's Cat, semantic web, software as a service, sorting algorithm, Turing complete, type inference, web application

Define vars that contain implementation-specific data or functions ^:private (or, private using the defn- convenience form for defining private functions) as much as possible. This keeps clients from unwittingly depending upon things likely to change, while still providing them a back door to access “behind the curtain” functions and data if absolutely necessary via the var special form (or its reader sugar #'). Don’t repeat yourself: define constants only once in a designated namespace, and break common functionality out into utility functions and utility namespaces as warranted. Use the common abstractions of reference types, collections, and sequences when you can, rather than marrying any particular concrete implementation of any of them. Unpure functions should be considered harmful, and implemented only when absolutely necessary.[243] In the large, your Clojure projects will benefit from the same attention to modularity and separation of concerns that yields benefits in projects written in any other language.


pages: 1,606 words: 168,061

Python Cookbook by David Beazley, Brian K. Jones

Amazon: amazon.comamazon.co.ukamazon.deamazon.fr

don't repeat yourself, Firefox, Guido van Rossum, iterative process, p-value, web application

_cache[name] return s Although there are more extreme measures that can be taken to hide the visibility of the Spam class, it’s probably best to not overthink the problem. Using an underscore on the name or defining a class method constructor is usually enough for programmers to get a hint. Caching and other creational patterns can often be solved in a more elegant (albeit advanced) manner through the use of metaclasses. See Recipe 9.13. Chapter 9. Metaprogramming One of the most important mantras of software development is “don’t repeat yourself.” That is, any time you are faced with a problem of creating highly repetitive code (or cutting or pasting source code), it often pays to look for a more elegant solution. In Python, such problems are often solved under the category of “metaprogramming.” In a nutshell, metaprogramming is about creating functions and classes whose main goal is to manipulate code (e.g., modifying, generating, or wrapping existing code).