don't repeat yourself

44 results back to index


pages: 292 words: 62,575

97 Things Every Programmer Should Know by Kevlin Henney

A Pattern Language, active measures, Apollo 11, business intelligence, business logic, commoditize, continuous integration, crowdsourcing, database schema, deliberate practice, domain-specific language, don't repeat yourself, Donald Knuth, fixed income, functional programming, general-purpose programming language, Grace Hopper, index card, inventory management, job satisfaction, level 1 cache, loose coupling, machine readable, 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!


Python Web Development With Django by Jeff Forcier

business logic, create, read, update, delete, database schema, Debian, don't repeat yourself, duck typing, en.wikipedia.org, Firefox, full text search, functional programming, Guido van Rossum, loose coupling, MVC pattern, revision control, Ruby on Rails, Silicon Valley, slashdot, SQL injection, 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.

—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?

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.


pages: 262 words: 60,248

Python Tricks: The Book by Dan Bader

anti-pattern, business logic, data science, domain-specific language, don't repeat yourself, functional programming, Hacker News, higher-order functions, linked data, off-by-one error, pattern recognition, performance metric

And, if we can do it without having to copy and paste the original function’s signature, that might be more maintainable: def trace(f): @functools.wraps(f) def decorated_function(*args, **kwargs): print(f, args, kwargs) result = f(*args, **kwargs) print(result) return decorated_function @trace def greet(greeting, name): return '{}, {}!'.format(greeting, name) >>> greet('Hello', 'Bob') <function greet at 0x1031c9158> ('Hello', 'Bob') {} 'Hello, Bob!' With techniques like this one, it’s sometimes difficult to balance the idea of making your code explicit enough and yet adhere to the Don’t Repeat Yourself (DRY) principle. This will always be a tough choice to make. If you can get a second opinion from a colleague, I’d encourage you to ask for one. Key Takeaways *args and **kwargs let you write functions with a variable number of arguments in Python. *args collects extra positional arguments as a tuple.

A trick you can use here to avoid this repetition is to use the object’s __class__.__name__ attribute, which will always reflect the class’ name as a string. The benefit is you won’t have to modify the __repr__ implementation when the class name changes. This makes it easy to adhere to the Don’t Repeat Yourself (DRY) principle: def __repr__(self): return (f'{self.__class__.__name__}(' f'{self.color!r}, {self.mileage!r})') The downside of this implementation is that the format string is quite long and unwieldy. But with careful formatting, you can keep the code nice and PEP 8 compliant. With the above __repr__ implementation, we get a useful result when we inspect the object or call repr() on it directly: >>> repr(my_car) 'Car(red, 37281)' Printing the object or calling str() on it returns the same string because the default __str__ implementation simply calls __repr__: >>> print(my_car) 'Car(red, 37281)' >>> str(my_car) 'Car(red, 37281)' I believe this approach provides the most value with a modest amount of implementation work.

r})' @classmethod def margherita(cls): return cls(['mozzarella', 'tomatoes']) @classmethod def prosciutto(cls): return cls(['mozzarella', 'tomatoes', 'ham']) Note how I’m using the cls argument in the margherita and prosciutto factory methods instead of calling the Pizza constructor directly. This is a trick you can use to follow the Don’t Repeat Yourself (DRY)8 principle. If we decide to rename this class at some point, we won’t have to remember to update the constructor name in all of the factory functions. Now, what can we do with these factory methods? Let’s try them out: >>> Pizza.margherita() Pizza(['mozzarella', 'tomatoes']) >>> Pizza.prosciutto() Pizza(['mozzarella', 'tomatoes', 'ham']) As you can see, we can use the factory functions to create new Pizza objects that are configured just the way we want them.


pages: 224 words: 48,804

The Productive Programmer by Neal Ford

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, Paradox of Choice, 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!

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.

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?)


pages: 62 words: 15,274

Sass for Web Designers by Dan Cederholm

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

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/).

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: 739 words: 174,990

The TypeScript Workshop: A Practical Guide to Confident, Effective TypeScript Programming by Ben Grynhaus, Jordan Hudgens, Rayon Hunte, Matthew Thomas Morgan, Wekoslav Stefanovski

Ada Lovelace, Albert Einstein, business logic, Charles Babbage, create, read, update, delete, don't repeat yourself, Donald Knuth, fault tolerance, Firefox, full stack developer, functional programming, Google Chrome, Hacker News, higher-order functions, inventory management, Kickstarter, loose coupling, node package manager, performance metric, QR code, Ruby on Rails, SQL injection, type inference, web application, WebSocket

Most programs will be made up of many .ts files. Those files will typically export functions, classes, or objects. Other parts of the program will interact with the exported code, typically by calling functions. Functions create patterns for reusing your application logic and allow you to write DRY (don't repeat yourself) code. Before diving into functions, let's perform an exercise to get a glimpse of how functions in general are useful. Don't worry if you do not understand some of the function-related syntax in the exercise. You will be studying all of this later in the chapter. The purpose of the following exercise is only to help you understand the importance of functions.

This is also helpful as regards debugging, as now they know how things are expected to function and can find where the issues are by using the interfaces as a guideline. The next section of this chapter is dedicated to inheritance in TypeScript. TypeScript Inheritance We will now dive into inheritance, which is one of the core principles of object-oriented programming. It allows us to stay DRY (don't repeat yourself). Inheritance also allows us to be polymorphic, by abstracting functionality. Inheritance gives you the ability to extend your classes from the original class to a child class, which allows you to retain the functionality from the parent or original class and add or override what you don't need.

In your application, you find that there is a need for a person type: you want to track the user's name, age, height, and weight. You can intersect type A and B to form a Person type. Why not just create a new type you ask? Well, this takes us back to wanting to be good coders and good coders stay DRY – Don't Repeat Yourself. Unless a type is truly unique in your application, you should reuse as much code as possible. Also, there is centralization. If you need to make changes to any of the type code for Person, you just need to make the changes in A or B. This is also a bit limiting as there may be cases where type A is used by more than one object, and if you make changes, it will break the application.


Learning Flask Framework by Matt Copperwaite, Charles Leifer

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

• 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

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

A Pattern Language, Broken windows theory, business logic, business process, buy low sell high, c2.com, combinatorial explosion, continuous integration, database schema, domain-specific language, don't repeat yourself, Donald Knuth, Ford Model T, Free Software Foundation, general-purpose programming language, George Santayana, Grace Hopper, higher-order functions, if you see hoof prints, think horses—not zebras, index card, Kaizen: continuous improvement, lateral thinking, loose coupling, Menlo Park, MVC pattern, off-by-one error, premature optimization, Ralph Waldo Emerson, revision control, Schrödinger's Cat, slashdot, sorting algorithm, speech recognition, systems thinking, the Cathedral and the Bazaar, traveling salesman, urban decay, Y2K

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.

(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.

., 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

airport security, Amazon Web Services, anti-pattern, business logic, business process, call centre, continuous integration, Conway's law, create, read, update, delete, defense in depth, don't repeat yourself, Edward Snowden, fail fast, fallacies of distributed computing, fault tolerance, index card, information retrieval, Infrastructure as a Service, inventory management, job automation, Kubernetes, load shedding, loose coupling, microservices, MITM: man-in-the-middle, platform as a service, premature optimization, pull request, recommendation engine, Salesforce, SimCity, social graph, software as a service, source of truth, sunk-cost fallacy, systems thinking, the built environment, the long tail, two-pizza team, web application, WebSocket

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.

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.

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

anti-pattern, continuous integration, Debian, don't repeat yourself, en.wikipedia.org, Firefox, information security, job automation, One Laptop per Child (OLPC), performance metric, revision control, web application

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).

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.


pages: 629 words: 83,362

Programming TypeScript by Boris Cherny

billion-dollar mistake, bitcoin, business logic, database schema, don't repeat yourself, duck typing, Firefox, functional programming, Internet of things, pull request, source of truth, SQL injection, type inference, web application

declarationMap (compiler option), Project References declare keyword, Type Declarations, Type Declarations declare module syntax, Ambient Module Declarations decorators, Decorators-Decoratorsexample, @serializable decorator, Decorators expected type signatures for decorator functions, Decorators use by Angular, Components defaultsfor function parameters, Optional and Default Parameters generic type, Generic Type Defaults definite assignment assertions, Definite Assignment Assertions DefinitelyTypedJavaScript with type declarations on, JavaScript That Has Type Declarations on DefinitelyTyped JavaScript without type declarations on, JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped dependency injector (Angular), Services design patterns, Design Patterns-Builder Patternbuilder pattern, Builder Pattern factory pattern, Factory Pattern dialog, closing with nonnull assertions, Nonnull Assertions directivestriple-slash, Triple-Slash Directives-The amd-module Directive, Triple-Slash Directivesamd-module, The amd-module Directive types, The types Directive distributive property of conditional types following, Distributive Conditionals DOM (Document Object Model), PrefaceDOM type declarations, enabling, lib enabling DOM APIs in TSC compiler, Frontend Frameworks events, typed in TypeScript standard library, Event Emitters overloads in browser DOM APIs, Overloaded Function Types dom library for TSC, In the Browser: With Web Workers Don't Repeat Yourself (DRY), Type aliases downlevelIteration TSC flag, Iterators DRY (Don't Repeat Yourself), Type aliases duck typing, Objects(see also structural typing) dynamic imports, Dynamic Imports E editors, When are types checked?autocompletion in, Frontend Frameworks Either type, The Option Type engines (JavaScript), The Compiler enums, Enums-Summary, Simulating Nominal Typesassignability, Assignability avoiding use of, Enums const, Enums naming conventions, Enums preserveConstEnums TSC flag, Enums splitting across multiple declarations, Enums with explicit numeric values, example of, Enums with inferred numeric values, example of, Enums with partially inferred values, example of, Enums errorserror messages in TypeScript, Introduction handling, Handling Errors-Exercisesin Promises, Regaining Sanity with Promises returning exceptions, Returning Exceptions-Returning Exceptions returning null, Returning null throwing exceptions, Throwing Exceptions-Throwing Exceptions using Option type, The Option Type-The Option Type in callbacks, Working with Callbacks in JavaScript, Introduction in Promise implementation, Regaining Sanity with Promises monitoring in TypeScript projects, Error Monitoring surfacing, in JavaScript versus TypeScript, When are errors surfaced?

For example, this code typechecks: let a: {} = {toString() { return 3 }}. But if you change the type annotation to Object, TypeScript complains: let b: Object = {toString() { return 3 }} results in Error TS2322: Type 'number' is not assignable to type 'string'. 4 The acronym DRY stands for “Don’t Repeat Yourself”—the idea that code shouldn’t be repetitive. It was introduced by Andrew Hunt and David Thomas in their book The Pragmatic Programmer: From Journeyman to Master (Addison-Wesley). 5 Jump ahead to “Discriminated union types” to learn how to hint to TypeScript that your union is disjoint and a value of that union’s type has to be one or the other, and not both. 6 The way to think about a bottom type is as a type that has no values.


Mastering Ansible by Jesse Keating

cloud computing, Debian, DevOps, don't repeat yourself, fail fast, microservices, remote working

The following is an outline of what we will cover: • Task, handler, variable, and playbook include concepts • Roles • Designing top level playbooks to utilize roles • Sharing roles across projects [ 95 ] Composing Reusable Ansible Content with Roles Task, handler, variable, and playbook include concepts The first step to understanding how to efficiently organize an Ansible project structure is to master the concept of including files. The act of including files allows content to be defined in a topic specific file that can be included into other files one or more times within a project. This inclusion feature supports the concept of DRY (Don't Repeat Yourself). Including tasks Task files are YAML files that define one or more tasks. These tasks are not directly tied to any particular play or playbook; they exist purely as a list of tasks. These files can be referenced by playbooks or other task files by way of the include operator. This operator takes a path to a task file, and as we learned in Chapter 1, System Architecture and Design of Ansible, the path can be relative from the file referencing it.

[ 208 ] Index A action plugins 198 Ansible about 1 configuration 2 dynamic inventory plugins, developing 199 modules 179 plugins, developing 193 version 2 Ansible Galaxy about 126-131 URL 126 AnsibleModule method 182 any_errors_fatal option 140, 141 B behavioral inventory parameter 5 built-in filters count 69 default 68, 69 random 69 round 69 C callback plugins 196-198 change command family, special handling 90-92 defining 88-90 suppressing 92, 93 check mode, simple module about 191 handling 192 supporting 191 code execution debugging 163 comparisions 79 conditionals about 49-51 inline conditionals 52 connection type plugins 193 connection variables 29 contract strategy 136-139 control machine 28 ControlPersist 25 control structure about 49 conditionals 49-51 inline conditionals 52 loops 53, 54 macros 58, 59 custom modules 180 D data encrypting, at rest 33, 34 disruptions delaying 147-152 destructive tasks, running only once 152, 153 managing 147 dot notation 162 DRY (Don't Repeat Yourself) 96 dynamic inventory plugins about 199, 200 developing 199-205 hosts, listing 201 host variables, listing 201 [ 209 ] E HAProxy behavior 6 encrypted files ansible-playbook, encrypting with Vault-encrypted files 43, 44 decrypting 42, 43 editing 40 existing files, encrypting 38, 39 new encrypted files, creating 35 password file 37 password prompt 36, 37 password rotation 41, 42 password script 38 errors about 139 any_errors_fatal option 140, 141 handlers, forcing 144-147 max_fail_percentage option 142, 143 expand strategy 136-139 extra-vars 29 I F fact caching plugins 194 failure defining 81 error condition, defining 83-87 errors, ignoring 81-83 filter about 67 Base64 encoding 73, 74 basename filter 72 built-in filters 68 content, searching for 75 custom filters 69 dealing, with path names 71 dirname filter 72 expanduser filter 73 plugins 194, 195 shuffle 71 syntax 67 task status related 70 undefined arguments, omitting 76 H handlers including 107, 108 included tasks complex data, passing 101, 102 variable values, passing 99, 100 in-place upgrades 133-136 inventory code, debugging 164-168 dynamic inventories 7, 8 limiting 9-12 parsing 3 run-time inventory additions 9 static inventory 3, 4 variables 26 variable data 4-7 L local code about 164 inventory code, debugging 164-168 Playbook code, debugging 168, 169 runner code, debugging 169-172 logic 79 lookup plugin 28, 193 loops about 53, 54 indexing 55-57 items, filtering 54, 55 M macros about 58, 59 name 60 macros, variables about 59, 60 arguments 61 caller 64-66 catch_kwargs 62 catch_varargs 63 defaults 61 name 60 max_fail_percentage option 142, 143 module arguments 22, 24 [ 210 ] execution 21-24 construct 180 custom modules 180 developing 179 reference 22 simple module 181-183 task performance 25 transport 21-24 P Playbook code, debugging 168, 169 including 115 logging 155, 156 verbosity 156 Playbook parsing about 12, 13 operations, order 13, 14 path assumptions 15-17 Play behavior keys 17 play, names 19-21 plays and tasks, host selecting for 18 task, names 19-21 plugins action plugins 198 callback plugins 196, 197 connection type plugins 193 developing 193 distributing 199 fact caching plugins 194 filter plugins 194, 195 lookup plugins 193 shell plugins 193 vars plugins 194 Python object methods about 77 int and float methods 78 list methods 78 string methods 77, 78 conditionals 120 tags 119 variables 118, 119 roles about 115 and tasks, mixing 123-126 Ansible Galaxy 126-131 application 120-123 default 26 sharing 126 structure 115 variables 26 roles structure about 115 dependencies 117 files and templates 117 handlers 116 modules 116 tasks 116 variables 116 runner code debugging 169-172 S secrets about 33 logged to remote or local files 45, 46 protecting, with operating 44 transmitted, to remote hosts 45 shell plugins 193 simple inventory plugin about 201-205 script performance, optimizing 206, 207 simple module about 181-183 check mode 191 documentation 184-189 fact data, providing 190 static inventory 3, 4 R T remote code action plugins, debugging 176 debugging 172-176 role dependencies about 118 tasks about 96-98 complex data, passing to included tasks 101, 102 conditional task includes 103, 104 [ 211 ] included tasks, tagging 105, 106 variable values, passing to included tasks 99 tests 79, 80 V values, comparing 79 variable dynamic vars_files inclusion 110, 111 external data, accessing 28 extra-vars 114 extra variables 27 fact modules 27 include_vars 111-113 including 109 play variables 27 task variables 27 types 26, 27 vars_files 109, 110 variable introspection about 157-159 variable sub elements 159 variable precedence about 28 connection variables 29 discovered facts variables 30 extra vars 29 hashes, merging 30, 31 inventory variables 30 most everything else 29, 30 order 28 role defaults 30 variable sub elements about 159, 161 versus Python object method 162, 163 variable values passing, to included tasks 99, 100 vars plugins 194 Vault 34 [ 212 ] Thank you for buying Mastering Ansible 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.


The Art of Readable Code by Dustin Boswell, Trevor Foucher

Albert Einstein, business logic, don't repeat yourself, Donald Knuth, off-by-one error, 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?


pages: 462 words: 172,671

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

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

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.

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.

See also bad code; messy code dirty code, cleaning, 200 dirty tests, 123 disinformation, avoiding, 19–20 distance, vertical in code, 80–84 distinctions, making meaningful, 20–21 domain-specific languages (DSLs), 168–169 domain-specific testing language, 127 DoubleArgumentMarshaler class, 238 DRY principle (Don’t Repeat Yourself), 181, 289 DTOs (data transfer objects), 100–101, 160 dummy scopes, 90 duplicate if statements, 276 duplication of code, 48 in code, 289–290 eliminating, 173–175 focusing on, 10 forms of, 173, 290 reduction of, 48 strategies for eliminating, 48 dyadic argument, 40 dyadic functions, 42 dynamic proxies, 161 E e, as a variable name, 22 Eclipse, 26 edit sessions, playing back, 13–14 efficiency, of code, 7 EJB architecture, early as over-engineered, 167 EJB standard, complete overhaul of, 164 EJB2 beans, 160 EJB3, Bank object rewritten in, 165–166 “elegant” code, 7 emergent design, 171–176 encapsulation, 136 of boundary conditions, 304 breaking, 106–107 of conditionals, 301 encodings, avoiding, 23–24, 312–313 entity bean, 158–160 enum(s) changing MonthConstants to, 272 using, 308–309 enumeration, moving, 277 environment, heuristics on, 287 environment control system, 128–129 envying, the scope of a class, 293 error check, hiding a side effect, 258 Error class, 47–48 error code constants, 198–200 error codes implying a class or enum, 47–48 preferring exceptions to, 46 returning, 103–104 reusing old, 48 separating from the Args module, 242–250 error detection, pushing to the edges, 109 error flags, 103–104 error handling, 8, 47–48 error messages, 107, 250 error processing, testing, 238–239 errorMessage method, 250 errors.


Getting Started With Ledger by Rolf Schröder

asset allocation, bitcoin, don't repeat yourself, machine readable

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: 48 words: 10,481

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

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

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.


Sass and Compass for Designers by Ben Frain

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

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/

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.


pages: 226 words: 17,533

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

augmented reality, business logic, continuous integration, domain-specific language, don't repeat yourself, functional programming, higher-order functions, loose coupling, semantic web, type inference, web application

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.

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

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

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.


pages: 779 words: 116,439

Test-Driven Development With Python by Harry J. W. Percival

business logic, continuous integration, database schema, Debian, DevOps, don't repeat yourself, duck typing, Firefox, loose coupling, MVC pattern, off-by-one error, platform as a service, pull request, web application, WebSocket

This whole writing tests thing sounded like it would have taken ages, and besides, I fancied myself, from the full height of my three weeks of adult coding experience, as being a pretty good programmer. I could handle it. Easy. Then came the fearful goddess Complexity. She soon showed me the limits of my experience. The project grew. Parts of the system started to depend on other parts. I did my best to follow good principles like DRY (Don’t Repeat Yourself), but that just led to some pretty dangerous territory. Soon I was playing with multiple inheritance. Class hierarchies 8 levels deep. eval statements. I became scared of making changes to my code. I was no longer sure what depended on what, and what might happen if I changed this code over here, oh gosh, I think that bit over there inherits from it—no, it doesn’t, it’s overriden.

Sure enough, the functional tests return an error: AssertionError: '1: Buy peacock feathers' not found in ['1: Use peacock feathers to make a fly'] Three Strikes and Refactor Before we go further—we’ve got a bad code smell1 in this FT. We have three almost identical code blocks checking for new items in the list table. There’s a principle called don’t repeat yourself (DRY), which we like to apply by following the mantra three strikes and refactor. You can copy and paste code once, and it may be premature to try and remove the duplication it causes, but once you get three occurrences, it’s time to remove duplication. We start by committing what we have so far.

Send email to index@oreilly.com. 443 www.it-ebooks.info code smell, 59, 65, 193, 301 collectstatic, 127–129 comments, 15, 86 commits, 18, 24, 30, 110 configuration management tools, 167 (see also Fabric) context managers, 177 continuous integration (CI), 365–385, cdvii adding required plugins, 368 best practices, 385 configuring Jenkins, 367 debugging with screenshots, 374–378 installing Jenkins, 365 JavaScript tests, 381–384 project setup, 369 Selenium race conditions, 378–381 for staging server test automation, 384 virtual display setup, 372–374 contracts, implicit, 356 cookies, 282, 304 Cross-Site Request Forgery (CSRF) error, 53 CSS (Cascading Style Sheets) framework, 116, 118 (see also Bootstrap) where Bootstrap won’t work, 126 cutting corners, cdvii D data migrations, 428–431 database deployment issues, 132 database location, 141 De-spiking, 251, 285–293 debugging, 21, 52, 249 Ajax, 249 Django debug screen, 146 improving error messages, 57 in continuous integration, 374–378 in JavaScript, 261 staging for, 306–310 switching DEBUG to false, 151 screenshots, for debugging, 374–378 dependencies and deployment, 132 mocking out, 278 virtualenv, 142 deployment, 411 adjusting database location, 141 automating, 152–155, 157–166 danger areas, 132 444 | dependencies and, 132 deploying to live, 163 further reading, 166 key points, 155 to live, 237 migrate, 147 Nginx, 144–146 overview, 152 production-ready, 148–152 vs. provisioning, 140 sample script, 158–161 saving progress, 156 staging, 237, 427 virtualenvs, 142–144 deployment testing, 131–156 domain name for, 135 manual provisioning for hosting, 136–140 overview, 133 design (see layout and style) Django, 4 admin site, 434 apps, 22 authentication in, 245–248, 282 class-based views, 413–421 (see also class-based views) collectstatic, 127–129 custom user model, 293–297 debugging screen, 146, 151 field types, 64 foreign key relationship, 99 forms in (see forms) FormView, 414 functional tests (FT) in (see functional tests/ testing (FT)) and Gunicorn, 148 LiveServerTestCase, 77 management commands, 311–314, 320 migrations, 62–64, 71–74, 237 model adjustment in, 97 model-layer validation, 175–187 Model-View-Controller (MVC), 24 notifications, 433 Object-Relational Mapper (ORM), 60–64 POST requests (see POST requests) as PythonAnywhere app, 410 startproject, 6 static files in, 122 static live server case, 124 template inheritance, 120–121 Index www.it-ebooks.info templates, 69–71, 90 test class in, 93 test client, 88, 93 test fixtures, 304 TestCase, 23 unit testing in, 23 URLs in, 24–30, 88, 94, 96, 102, 106, 108, 110 validation quirk, 178 view functions in, 24, 89, 94, 105–108, 326 and virtualenvs, 142–144 Django-BrowserID, 243 documentation, tests as, 296 domain names, 135 Don’t Test Constants rule, 40 double-loop TDD, 47, 323 DRY (don’t repeat yourself), 59, 396 duplicates, eliminating, 58, 211–221 E encryption, 436 end-to-end test (see functional tests/testing (FT)) error messages, 435 error pages, 434 evaluating third-party systems, 252 expected failure, 16, 19 explicit waits, 253 exploratory coding, 195, 242 (see also spiking) F Fabric, 167, 314, 426 configuration, 163 installing, 157 sample deployment script, 158–161 Fake XMLHttpRequest, 268 fixtures in functional tests, 303 in JavaScript tests, 229 on staging server, 311–317 foreign key relationship, 99 forms advanced, 211–223 autogeneration, 195 customising form field input, 194 experimenting with, 194 ModelForm, 195 save methods, 208 simple, 193–210 thin views, 210 tips for, 210 using in views, 198–207 validation testing and customising, 196 Fuctional Core, Imperative Shell architecture, 403 functional tests/testing (FT), 5, 398 automation of (see continuous integration (CI)) cleanup, 77–80, 95, 387 de-duplication, 320 defining, 14 for de-spiking, 251 for duplicate items, 211–221 isolation in, 77–80, 112 in JavaScript, 232–234 for layout and style, 115–118, 148, 173 multiple users, 387, 393–394 pros and cons, 364 in provisioning, 139 running unit tests only, 80 safeguards with, 317 splitting, 171 for staging sites, 132, 133 unittest module, 13–19 vs. unit tests, 22, 303 in views, 223 G generator expression, 39 GET requests, 198, 205 get_user, 291 Git repository setup, 8–11 reset --hard, 118 tags, 166, 238 global variables, 228 greedy regular expressions, 106 Gunicorn, 148–155, 165, 307, 425 H headless browsers, 372 helper functions/methods, 59, 172, 175, 206, 226, 350, 390–393 hexagonal architecture, 403 hosting options, 136 Index www.it-ebooks.info | 445 hosting, manual provisioning, 136–140 L Idempotency, 167 implicit waits, 18 in-memory model objects, 352 integrated tests, 351–363, 403 vs. integration test, 342 vs. isolated tests, 362, 398 pros and cons, 364 vs. unit tests, 61 integration tests, 342, 398 integrity errors, 217 isolated tests, 337, 403 (see also test isolation) vs. integrated tests, 362, 398 problems with, 400 pros and cons, 364 layout and style, 115–130 Bootstrap for (see Bootstrap) functional tests (FT) for, 173 large inputs, 125 overview, 130 rows and columns, 122 static files, 122, 127–129 table styling, 126 using a CSS framework for, 118 (see also Bootstrap) using our own CSS in, 126 what to functionally test for, 115 list comprehension, 39 LiveServerTestCase, 77 log messages, 320 logging, 307, 320 logging configuration, 318–320 J M I JavaScript, 225 de-spiking in, 251 debug console, 261 functional test (FT) building in, 232–234 jQuery and Fixtures Div, 229–231 linters, 228 MVC frameworks, 435 onload boilerplate and namespacing, 234 QUnit, 227 running tests in continuous integration, 381–384 spiking with, 242–255 (see also spiking) in TDD Cycle, 234 test runner setup, 226 testing notes, 235 Jenkins Security, 365–384 (see also continuous integration (CI)) adding required plugins, 368 configuring, 367 installing, 365 jQuery, 229–231, 234, 235 JSON fixtures, 304, 320 jumbotron, 125 446 | manage.py, 6, 24, 63, 72, 127 Meta, 196 meta-comments, 86 migrate, 147 migrations, 62–64, 71–74, 99, 237, 238 (see also data migrations) database, 427–431 deleting, 99 testing, 427–431 minimum viable application, 13–16, 81 MockMyID, 252 mocks/mocking callbacks, 272–275 checking call arguments, 267 implicit contracts, 356 in JavaScript, 241, 257–275 initialize function test, 258–264 Internet requests, 285–293 for isolation, 338–341 mock library, 301 Mock side_effects, 339 namespacing, 258 in Outside-In TDD, 331 in Python, 278–284 risks, 354 sinon.js, 265 testing Django login, 284 Index www.it-ebooks.info model-layer validation, 175–187 changes to test, 216 enforcing, 186 errors in View, 178–182 integrity errors, 217 POST requests, 183–187 preventing duplicates, 212 refactoring, 175, 184–186 unit testing, 177–178 at views level, 218 Model-View-Controller (MVC), 24, 435 ModelForm, 195 Mozilla Persona, 242 MVC frameworks, 24, 435 N namespacing, 258 Nginx, 138, 144–146, 149, 165, 424 nonroot user creation, 137 notifications, 433 O Q QuerySet, 61, 214–216 QUnit, 227, 235, 263, 268 ORM (Object-Relational Mapper), 60–64 Outside-In TDD, 323–335 advantages, 323 controller layer, 326 defined, 335 vs.


pages: 266 words: 79,297

Forge Your Future with Open Source by VM (Vicky) Brasseur

AGPL, anti-pattern, Benevolent Dictator For Life (BDFL), call centre, continuous integration, Contributor License Agreement, Debian, DevOps, don't repeat yourself, en.wikipedia.org, Firefox, FOSDEM, Free Software Foundation, Guido van Rossum, information security, Internet Archive, Larry Wall, microservices, Perl 6, premature optimization, pull request, Richard Stallman, risk tolerance, Turing machine

This reduces the complexity of any one piece of code, making it shorter and much easier to understand, maintain, and test. Be on the lookout for any piece of code that’s overloaded and trying to do too many things. A good clue for this can be that the code has a complicated or long conditional statement. The DRY Principle: Don’t Repeat Yourself. Is there any code that occurs more than once, even if it’s doing similar but not entirely identical things? If so, it should be refactored out into a separate class, method, or function. Repeated code means changes have to be applied in multiple places, leading to a higher chance of error.

For instance, a knitter has domain knowledge about how to read a knitting pattern, the different types of needles available, and the different types of fibres used in yarns, among other related information. Domain knowledge is important when making judgement calls about the design and implementation of a project for a domain. People who have relevant domain knowledge are known as subject matter experts. DRY Short for Don’t Repeat Yourself. DRY is a best practice in software development. Any time you find yourself in a situation where you might need to reuse a piece of code, design element, or other component, DRY encourages you to pull it out into its own reusable fragment (function, method, file, or whatever makes sense). In this way, if a change is needed, it only needs to be made in a single place rather than in a series of repeated components.


Django Book by Matt Behrens

Benevolent Dictator For Life (BDFL), book value, business logic, create, read, update, delete, database schema, distributed revision control, don't repeat yourself, duck typing, en.wikipedia.org, Firefox, full text search, loose coupling, MITM: man-in-the-middle, MVC pattern, revision control, Ruby on Rails, school choice, slashdot, SQL injection, 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".

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.

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

business logic, continuous integration, create, read, update, delete, database schema, domain-specific language, don't repeat yourself, duck typing, en.wikipedia.org, failed state, fault tolerance, functional programming, general-purpose programming language, higher-order functions, index card, Kanban, 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.

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.


pages: 722 words: 90,903

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

Bram Moolenaar, don't repeat yourself, en.wikipedia.org, fault tolerance, finite state, fizzbuzz, off-by-one error, 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.

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.


Practical Vim, Second Edition (for Stefano Alcazi) by Drew Neil

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

Table of Contents Acknowledgments Foreword to the First Edition Read MeHow This Book Is Structured A Note on the Examples Learn to Touch Type, Then Learn Vim Read the Forgotten ManualGet 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 WayTip 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 Part I. Modes2. Normal ModeTip 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.

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.


Practical Vim by Drew Neil

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

Table of Contents Acknowledgments Foreword to the First Edition Read MeHow This Book Is Structured A Note on the Examples Learn to Touch Type, Then Learn Vim Read the Forgotten ManualGet 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 WayTip 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 Part I. Modes2. Normal ModeTip 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.

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.


pages: 108 words: 28,348

Code Simplicity by Max Kanat-Alexander

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.


pages: 136 words: 20,501

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

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.


pages: 214 words: 14,382

Monadic Design Patterns for the Web by L.G. Meredith

barriers to entry, domain-specific language, don't repeat yourself, finite state, functional programming, Georg Cantor, ghettoisation, higher-order functions, John von Neumann, Kickstarter, semantic web, seminal paper, social graph, type inference, web application, WebSocket

One presentation, called comprehensions (after its counterpart in set theory), could be understood directly in terms of a familiar construct SELECT ... FROM ... WHERE ...; while the other, dubbed do notation by the Haskell community, provided operations that behaved remarkably like sequencing and assignment. Haskell offers syntactic sugar to 1 DRY is the pop culture term for "Don’t repeat yourself.” Cover · Overview · Contents · Discuss · Suggest · Glossary · Index 21 Download from Wow! eBook <www.wowebook.com> Section 1.1 Chapter 1 · Motivation and Background support the latter while the former has been adopted in both XQuery’s FLWOR expressions and Microsoft’s LINQ. Of course, to say that Haskell offers syntactic sugar hides the true nature of how the language supports monads.


pages: 499 words: 144,278

Coders: The Making of a New Tribe and the Remaking of the World by Clive Thompson

"Margaret Hamilton" Apollo, "Susan Fowler" uber, 2013 Report for America's Infrastructure - American Society of Civil Engineers - 19 March 2013, 4chan, 8-hour work day, Aaron Swartz, Ada Lovelace, AI winter, air gap, Airbnb, algorithmic bias, AlphaGo, Amazon Web Services, Andy Rubin, Asperger Syndrome, augmented reality, Ayatollah Khomeini, backpropagation, barriers to entry, basic income, behavioural economics, Bernie Sanders, Big Tech, bitcoin, Bletchley Park, blockchain, blue-collar work, Brewster Kahle, Brian Krebs, Broken windows theory, call centre, Cambridge Analytica, cellular automata, Charles Babbage, Chelsea Manning, Citizen Lab, clean water, cloud computing, cognitive dissonance, computer vision, Conway's Game of Life, crisis actor, crowdsourcing, cryptocurrency, Danny Hillis, data science, David Heinemeier Hansson, deep learning, DeepMind, Demis Hassabis, disinformation, don't be evil, don't repeat yourself, Donald Trump, driverless car, dumpster diving, Edward Snowden, Elon Musk, Erik Brynjolfsson, Ernest Rutherford, Ethereum, ethereum blockchain, fake news, false flag, Firefox, Frederick Winslow Taylor, Free Software Foundation, Gabriella Coleman, game design, Geoffrey Hinton, glass ceiling, Golden Gate Park, Google Hangouts, Google X / Alphabet X, Grace Hopper, growth hacking, Guido van Rossum, Hacker Ethic, hockey-stick growth, HyperCard, Ian Bogost, illegal immigration, ImageNet competition, information security, Internet Archive, Internet of things, Jane Jacobs, John Markoff, Jony Ive, Julian Assange, Ken Thompson, Kickstarter, Larry Wall, lone genius, Lyft, Marc Andreessen, Mark Shuttleworth, Mark Zuckerberg, Max Levchin, Menlo Park, meritocracy, microdosing, microservices, Minecraft, move 37, move fast and break things, Nate Silver, Network effects, neurotypical, Nicholas Carr, Nick Bostrom, no silver bullet, Northpointe / Correctional Offender Management Profiling for Alternative Sanctions, Oculus Rift, off-the-grid, OpenAI, operational security, opioid epidemic / opioid crisis, PageRank, PalmPilot, paperclip maximiser, pattern recognition, Paul Graham, paypal mafia, Peter Thiel, pink-collar, planetary scale, profit motive, ransomware, recommendation engine, Richard Stallman, ride hailing / ride sharing, Rubik’s Cube, Ruby on Rails, Sam Altman, Satoshi Nakamoto, Saturday Night Live, scientific management, self-driving car, side project, Silicon Valley, Silicon Valley ideology, Silicon Valley startup, single-payer health, Skype, smart contracts, Snapchat, social software, software is eating the world, sorting algorithm, South of Market, San Francisco, speech recognition, Steve Wozniak, Steven Levy, systems thinking, TaskRabbit, tech worker, techlash, TED Talk, the High Line, Travis Kalanick, Uber and Lyft, Uber for X, uber lyft, universal basic income, urban planning, Wall-E, Watson beat the top human players on Jeopardy!, WeWork, WikiLeaks, women in the workforce, Y Combinator, Zimmermann PGP, éminence grise

When a particular function—a subroutine in a program—becomes long and labyrinthine, odds are high it could be made more efficient. Often the act of fixing it, refactoring it, involves bits of fractal meta-efficiency: You find places where your code repeats itself, and you remove the duplication. One of the oldest dictums in coding is to be DRY—“Don’t repeat yourself.” Occasionally the high-tech press will report on the mammoth size of a software base; Google’s various services in 2015, for example, consisted of fully 2 billion lines of code. It conveys the idea that size is value—that the bigger the line count, the more impressive the result; and thus a valuable coder is one who adds more, sitting and typing in an ecstatic trance.

., ref1 Dinesh, Akshaya, ref1, ref2 DiResta, Renée, ref1 diversity in software industry, lack of, ref1, ref2 Dodgeball, ref1 Doerr, John, ref1 dogpiling, ref1 Domingos, Pedro, ref1, ref2, ref3 Dorsey, Jack, ref1, ref2, ref3 Drasner, Sarah, ref1 Dropbox, ref1 personal cloud storage project, ref1 Smart Sync project, ref1 DRY (“Don’t repeat yourself”), ref1 Dungeons & Dragons (game), ref1 Duterte, Rodrigo, ref1 eBay, ref1 edge case, ref1 Edison, Thomas, ref1 efficiency, ref1, ref2 act of automating, thrill in, ref1 addictive behavior and, ref1 of code, ref1 computers’ strength in automating repetitive tasks, ref1 on demand services and, ref1 DRY and, ref1 engineering mind-set and, ref1 in everyday life, ref1, ref2 in food preparation, ref1 Franklin and, ref1 Ho, profile of, ref1 inefficient code, effects of, ref1 in leisure activities, ref1 obsession of coders with, ref1 olfactory metaphors for inefficient code, ref1 refactoring and, ref1, ref2 repetition, coders aversion to, ref1 in schoolwork, ref1 side effects of, ref1 size of code base and, ref1 in social and emotional relations, ref1 spending more time writing program than doing manual task would take, ref1 1843, ref1 Eisenman, Bonnie, ref1 ElcomSoft, ref1 Eliot, T.


Learning Ansible 2 - Second Edition by Fabio Alessandro Locati

Amazon Web Services, anti-pattern, business logic, cloud computing, continuous integration, Debian, DevOps, don't repeat yourself, Infrastructure as a Service, inventory management, Kickstarter, revision control, source of truth, web application

We could improve the previous example in the following way: --- hosts: all remote_user: ansible vars: backup: True tasks: - name: Check if the backup_folder is set fail: msg: 'The backup_folder needs to be set' when: backup_folder is not defined - name: Copy the crontab in tmp if the backup variable is true copy: src: /etc/crontab dest: '{{ backup_folder }}/crontab' remote_src: True when: backup As you can see, we have used the fail module that allows us to put the Ansible playbook in a failure state in case the backup_folder variable is not set. Working with include The include feature helps you to reduce duplicity while writing tasks. This also allows us to have smaller playbooks by including reusable code in separate tasks using the Don't Repeat Yourself (DRY) principle. To trigger the inclusion of another file, you need to put the following under the tasks object: - include: FILENAME.yaml You can also pass some variables to the included file. To do so, we can specify them in the following way: - include: FILENAME.yaml variable1="value1" variable2="value2" In addition of passing variables, you can also use conditionals to include a file only when certain conditions are matched, for instance to include the redhat.yaml file only if the machine is running an OS in the Red Hat family using the following code: - name: Include the file only for Red Hat OSes include: redhat.yaml when: ansible_os_family == "RedHat" Working with handlers In many situations, you will have a task or a group of tasks that change certain resources on the remote machines, which need to trigger an event to become effective.


pages: 303 words: 57,177

Hands-On Functional Programming in RUST by Andrew Johnson

anti-pattern, Debian, domain-specific language, don't repeat yourself, Donald Knuth, functional programming, higher-order functions, level 1 cache, premature optimization

How do you declare a structure field as private? Generics and Polymorphism Parameterization, also known as generics or polymorphism, is the third most significant language feature following control flow and data structures. Parameterization addresses the copy-and-paste problem of early languages. This feature permits the don't repeat yourself principle of good program design. In this chapter, we will look at how parameterization can help us design robust programs that evolve with change rather than fight against change. No new project requirements will be introduced. This chapter will be entirely reflective, looking at how the project is currently structured, how can it be improved, and how parameterization can specifically help.


Agile Project Management with Kanban (Developer Best Practices) by Eric Brechner

Amazon Web Services, cloud computing, continuous integration, crowdsourcing, data science, DevOps, don't repeat yourself, en.wikipedia.org, index card, Kaizen: continuous improvement, Kanban, loose coupling, minimum viable product, pull request, software as a service

I recommend that you implement Kanban in the same work-item tracking system as you use for other development work. For example, recording bugs in a defect-tracking system that’s separate from your other work would create inefficiencies and duplication. Most redundancy is evil per the DRY principle—“Don’t Repeat Yourself.” Ideally, the customer-support system and engineering work-item tracking system are integrated such that the original incident and the escalated work item can be tied together. This lets customer support see the state of the work item as the core engineering team works on it, and the core engineering team can see updates made by the support team.


pages: 274 words: 58,675

Puppet 3 Cookbook by John Arundel

Amazon Web Services, cloud computing, continuous integration, Debian, defense in depth, DevOps, don't repeat yourself, Free Software Foundation, 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.


pages: 1,331 words: 163,200

Hands-On Machine Learning With Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems by Aurélien Géron

AlphaGo, Amazon Mechanical Turk, Anton Chekhov, backpropagation, combinatorial explosion, computer vision, constrained optimization, correlation coefficient, crowdsourcing, data science, deep learning, DeepMind, don't repeat yourself, duck typing, Elon Musk, en.wikipedia.org, friendly AI, Geoffrey Hinton, ImageNet competition, information retrieval, iterative process, John von Neumann, Kickstarter, machine translation, natural language processing, Netflix Prize, NP-complete, OpenAI, optical character recognition, P = NP, p-value, pattern recognition, pull request, recommendation engine, self-driving car, sentiment analysis, SpamAssassin, speech recognition, stochastic process

., name="relu2") output = tf.add(relu1, relu2, name="output") Such repetitive code is hard to maintain and error-prone (in fact, this code contains a cut-and-paste error; did you spot it?). It would become even worse if you wanted to add a few more ReLUs. Fortunately, TensorFlow lets you stay DRY (Don’t Repeat Yourself): simply create a function to build a ReLU. The following code creates five ReLUs and outputs their sum (note that add_n() creates an operation that will compute the sum of a list of tensors): def relu(X): w_shape = (int(X.get_shape()[1]), 1) w = tf.Variable(tf.random_normal(w_shape), name="weights") b = tf.Variable(0.0, name="bias") z = tf.add(tf.matmul(X, w), b, name="z") return tf.maximum(z, 0., name="relu") n_features = 3 X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [relu(X) for i in range(5)] output = tf.add_n(relus, name="output") Note that when you create a node, TensorFlow checks whether its name already exists, and if it does it appends an underscore followed by an index to make the name unique.

Pac-Man Using Deep Q-Learning deep Q-network, Approximate Q-Learning deep RNNs, Deep RNNs-The Difficulty of Training over Many Time Stepsapplying dropout, Applying Dropout distributing across multiple GPUs, Distributing a Deep RNN Across Multiple GPUs long sequence difficulties, The Difficulty of Training over Many Time Steps truncated backpropagation through time, The Difficulty of Training over Many Time Steps DeepMind, Reinforcement Learning, Introduction to Artificial Neural Networks, Reinforcement Learning, Approximate Q-Learning degrees of freedom, Overfitting the Training Data, Learning Curves denoising autoencoders, Denoising Autoencoders-TensorFlow Implementation depth concat layer, GoogLeNet depth radius, AlexNet depthwise_conv2d(), ResNet dequeue(), Queues of tuples dequeue_many(), Queues of tuples, PaddingFifoQueue dequeue_up_to(), Closing a queue-PaddingFifoQueue dequeuing data, Dequeuing data describe(), Take a Quick Look at the Data Structure device blocks, Sharding Variables Across Multiple Parameter Servers device(), Simple placement dimensionality reduction, Unsupervised learning, Dimensionality Reduction-Exercises, Autoencodersapproaches toManifold Learning, Manifold Learning projection, Projection-Projection choosing the right number of dimensions, Choosing the Right Number of Dimensions curse of dimensionality, Dimensionality Reduction-The Curse of Dimensionality and data visualization, Dimensionality Reduction Isomap, Other Dimensionality Reduction Techniques LLE (Locally Linear Embedding), LLE-LLE Multidimensional Scaling, Other Dimensionality Reduction Techniques-Other Dimensionality Reduction Techniques PCA (Principal Component Analysis), PCA-Randomized PCA t-Distributed Stochastic Neighbor Embedding (t-SNE), Other Dimensionality Reduction Techniques discount rate, Evaluating Actions: The Credit Assignment Problem distributed computing, Up and Running with TensorFlow distributed sessions, Sharing State Across Sessions Using Resource Containers-Sharing State Across Sessions Using Resource Containers DNNClassifier, Training an MLP with TensorFlow’s High-Level API drop(), Prepare the Data for Machine Learning Algorithms dropconnect, Dropout dropna(), Data Cleaning dropout, Number of Neurons per Hidden Layer, Applying Dropout dropout rate, Dropout dropout(), Dropout DropoutWrapper, Applying Dropout DRY (Don’t Repeat Yourself), Modularity Dual Averaging, Adam Optimization dual numbers, Forward-Mode Autodiff dual problem, The Dual Problem duality, SVM Dual Problem dying ReLUs, Nonsaturating Activation Functions dynamic placements, Dynamic placement function dynamic placer, Placing Operations on Devices Dynamic Programming, Markov Decision Processes dynamic unrolling through time, Dynamic Unrolling Through Time dynamic_rnn(), Dynamic Unrolling Through Time, Distributing a Deep RNN Across Multiple GPUs, An Encoder–Decoder Network for Machine Translation E early stopping, Early Stopping-Early Stopping, Gradient Boosting, Number of Neurons per Hidden Layer, Early Stopping Elastic Net, Elastic Net embedded device blocks, Sharding Variables Across Multiple Parameter Servers Embedded Reber grammars, Exercises embeddings, Word Embeddings-Word Embeddings embedding_lookup(), Word Embeddings encoder, Efficient Data Representations Encoder–Decoder, Input and Output Sequences end-of-sequence (EOS) token, Handling Variable-Length Output Sequences energy functions, Hopfield Networks enqueuing data, Enqueuing data Ensemble Learning, Better Evaluation Using Cross-Validation, Ensemble Methods, Ensemble Learning and Random Forests-Exercisesbagging and pasting, Bagging and Pasting-Out-of-Bag Evaluation boosting, Boosting-Gradient Boosting in-graph versus between-graph replication, In-Graph Versus Between-Graph Replication-In-Graph Versus Between-Graph Replication Random Forests, Random Forests-Feature Importance(see also Random Forests) random patches and random subspaces, Random Patches and Random Subspaces stacking, Stacking-Stacking entropy impurity measure, Gini Impurity or Entropy?


pages: 323 words: 65,306

Programming in CoffeeScript by Mark Bates

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

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) Click here to view code image * * * (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

Alan Turing: On Computable Numbers, with an Application to the Entscheidungsproblem, Apple II, barriers to entry, Berlin Wall, Big Tech, British Empire, business process, Californian Ideology, Charles Babbage, conceptual framework, create, read, update, delete, crowdsourcing, don't repeat yourself, Donald Knuth, East Village, European colonialism, finite state, Firefox, Flash crash, functional programming, glass ceiling, Grace Hopper, Hacker News, haute couture, hype cycle, 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, synthetic biology, tech worker, the Cathedral and the Bazaar, theory of mind, Therac-25, Turing machine, wikimedia commons, women in the workforce

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.


Realtime Web Apps: HTML5 WebSocket, Pusher, and the Web’s Next Big Thing by Jason Lengstorf, Phil Leggetter

Amazon Web Services, barriers to entry, don't repeat yourself, en.wikipedia.org, Firefox, Google Chrome, MVC pattern, Ruby on Rails, Skype, software as a service, SQL injection, web application, WebSocket

Most common technologies for web design, such as HTML5 and CSS3, are supported by most mobile devices, meaning that it’s likely going to be more difficult to get all the features of your app running on old versions of Internet Explorer than it will be to get it running on mobile browsers. A very strong principle in software development is represented by the acronym DRY, which is short for Don’t Repeat Yourself. Consolidating all supported platforms into one central codebase by focusing on building a single responsive web application is a huge step toward a DRY app. There are platforms such as PhoneGap11 and Trigger.io12 that aim to make a web app into various platform-specific apps. The very existence of tools such as these is a testament to both the market for native applications and to the difficulty of learning how to code for different platforms.


pages: 420 words: 79,867

Developing Backbone.js Applications by Addy Osmani

Airbnb, anti-pattern, business logic, create, read, update, delete, don't repeat yourself, Firefox, full text search, Google Chrome, Khan Academy, Kickstarter, 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.


pages: 761 words: 80,914

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

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, machine readable, MITM: man-in-the-middle, 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: 290 words: 119,172

Beginning Backbone.js by James Sugrue

Airbnb, business logic, 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.


pages: 1,758 words: 342,766

Code Complete (Developer Best Practices) by Steve McConnell

Ada Lovelace, Albert Einstein, Buckminster Fuller, business logic, call centre, classic study, continuous integration, data acquisition, database schema, don't repeat yourself, Donald Knuth, fault tolerance, General Magic , global macro, Grace Hopper, haute cuisine, if you see hoof prints, think horses—not zebras, index card, inventory management, iterative process, Larry Wall, loose coupling, Menlo Park, no silver bullet, off-by-one error, Perl 6, place-making, premature optimization, revision control, Sapir-Whorf hypothesis, seminal paper, slashdot, sorting algorithm, SQL injection, statistical model, Tacoma Narrows Bridge, the Cathedral and the Bazaar, the scientific method, Thomas Kuhn: the structure of scientific revolutions, Turing machine, web application

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.

standards, IEEE, The Book Paradigm for Program Documentation style differences, managing, Team Variation UDFs, External Documentation visual, of designs, Capturing Your Design Work why vs. how, Commenting Paragraphs of Code dog tag fields, General Tips on Pointers dog-and-pony shows, Dog-and-Pony Shows DoNothing() macros, Null Statements DRY (Don't Repeat Yourself) principle, Philosophy of Software Evolution duplication, Valid Reasons to Create a Routine, Philosophy of Software Evolution avoiding with routines, Valid Reasons to Create a Routine code as refactoring indicator, Philosophy of Software Evolution E early-wave environments, Your Location on the Technology Wave ease of maintenance design goal, Desirable Characteristics of a Design eclecticism, Iterate, Repeatedly, Again and Again editing tools, Programming Tools, Integrated Development Environments (IDEs), Integrated Development Environments (IDEs), Multiple-File String Searching and Replacing, Multiple-File String Searching and Replacing, Multiple-File String Searching and Replacing, Interface Documentation Tools, Interface Documentation Tools, Interface Documentation Tools, Interface Documentation Tools beautifiers, Multiple-File String Searching and Replacing (see ) class-hierarchy generators, Interface Documentation Tools cross-reference tools, Interface Documentation Tools Diff tools, Multiple-File String Searching and Replacing grep, Integrated Development Environments (IDEs) IDEs, Programming Tools interface documentation, Interface Documentation Tools merge tools, Multiple-File String Searching and Replacing multiple-file string searches, Integrated Development Environments (IDEs) templates, Interface Documentation Tools efficiency, Characteristics of Software Quality eighty/twenty (80/20) rule, Introduction to Code Tuning else clauses, Plain if-then Statements, Plain if-then Statements, Plain if-then Statements, Chains of if-then-else Statements, Chains of if-then-else Statements, Chains of if-then-else Statements, Chains of if-then-else Statements, gotos and Sharing Code in an else Clause boolean function calls with, Chains of if-then-else Statements case statements instead of, Chains of if-then-else Statements chains, in, Plain if-then Statements common cases first guideline, Chains of if-then-else Statements correctness testing, Plain if-then Statements default for covering all cases, Chains of if-then-else Statements gotos with, gotos and Sharing Code in an else Clause null, Plain if-then Statements embedded life-critical systems, Boss-Readiness Test emergent nature of design process, Design Is a Sloppy Process (Even If it Produces a Tidy Result) emulated pure blocks layout style, Pure Blocks encapsulation, Form Consistent Abstractions, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Good Encapsulation, Beyond Classes: Packages, Reasons to Refactor, Reasons to Refactor, Routine-Level Refactorings assumptions about users, Good Encapsulation checklist, Beyond Classes: Packages classes, role for, Good Encapsulation coupling classes too tightly, Good Encapsulation downcast objects, Routine-Level Refactorings friend class concern, Good Encapsulation heuristic design with, Form Consistent Abstractions minimizing accessibility, Good Encapsulation private details in class interfaces, Good Encapsulation public data members, Reasons to Refactor public members of classes, Good Encapsulation public routines in interfaces concern, Good Encapsulation semantic violations of, Good Encapsulation weak, Reasons to Refactor endless loops, Controlling Loops, Entering the Loop endline comments, Endline Comments and Their Problems endline layout, Using begin-end Pairs (Braces) to Designate Block Boundaries, Other Considerations, Laying Out Routines enumerated types, Naming Boolean Variables, Guidelines for a Language-Independent Convention, Sample Naming Conventions, Boolean Variables, Boolean Variables, Boolean Variables, Boolean Variables, Boolean Variables, Boolean Variables, Boolean Variables, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, Enumerated Types, If Your Language Doesn't Have Enumerated Types, If Your Language Doesn't Have Enumerated Types, Guidelines for Creating Your Own Types, Common Problems with Global Data, Commenting Data Declarations benefits of, Boolean Variables (see ) booleans, alternative to, Enumerated Types C++, Boolean Variables, Enumerated Types changes benefit, Enumerated Types checklist, Guidelines for Creating Your Own Types comments substituting for, Commenting Data Declarations creating for Java, If Your Language Doesn't Have Enumerated Types defined, Boolean Variables emulation by global variables, Common Problems with Global Data explicit value pitfalls, Enumerated Types first entry invalid trick, Enumerated Types iterating through, Enumerated Types Java, creating for, If Your Language Doesn't Have Enumerated Types languages available in, Boolean Variables loop limits with, Enumerated Types naming, Naming Boolean Variables, Guidelines for a Language-Independent Convention, Sample Naming Conventions parameters using, Boolean Variables readability from, Boolean Variables reliability benefit, Enumerated Types standard for, Enumerated Types validation with, Enumerated Types Visual Basic, Boolean Variables equality, floating-point, Integers equivalence partitioning, Combinations of Data States error codes, Error-Handling Techniques error detection, doing early, Appeal to Data error guessing, Error Guessing error handling, Input/Output, Input/Output, Input/Output, Error Processing, Architectural Feasibility, Building Your Own Assertion Mechanism, Guidelines for Using Assertions, Guidelines for Using Assertions, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Error-Handling Techniques, Robustness vs.

naming routines, Design the Routine performance considerations, Design the Routine prerequisites, Design the Routine problem definition, Design the Routine refactoring, Code the Routine reviewing, Design the Routine routines, steps in creating, Steps in Creating a Class, Design the Routine testing, planning for, Design the Routine Pseudocode Programming Process, Design the Routine psychological distance, How "Psychological Distance" Can Help psychological factors, Curiosity psychological set, Fixing a Defect public data members, Reasons to Refactor pure blocks layout style, Parentheses Python, Java, Common Sources of Inefficiency description of, Java performance issues, Common Sources of Inefficiency Q quality assurance, Measure Twice, Cut Once: Upstream Prerequisites, Boss-Readiness Test, Handling Requirements Changes During Construction, Selection of Major Construction Practices, Characteristics of Software Quality checklist, Selection of Major Construction Practices good practices table for, Boss-Readiness Test prerequisites role in, Measure Twice, Cut Once: Upstream Prerequisites requirements checklist, Handling Requirements Changes During Construction quality gates, Techniques for Improving Software Quality quality of software, The Software-Quality Landscape, The Software-Quality Landscape, The Software-Quality Landscape, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Characteristics of Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Techniques for Improving Software Quality, Development Process, Development Process, Development Process, Development Process, Development Process, Setting Objectives, Percentage of Defects Detected, Percentage of Defects Detected, Percentage of Defects Detected, Cost of Finding Defects, Cost of Finding Defects, Cost of Fixing Defects, Cost of Fixing Defects, The General Principle of Software Quality, The General Principle of Software Quality, The General Principle of Software Quality, The General Principle of Software Quality, Relevant Standards, Relevant Standards, Developer Testing, Overview of Debugging Issues, Software Quality-Assurance Standards accuracy, Characteristics of Software Quality (see ) adaptability, Characteristics of Software Quality change-control procedures, Development Process checklist for, The General Principle of Software Quality correctness, The Software-Quality Landscape costs of finding defects, Cost of Finding Defects costs of fixing defects, Cost of Finding Defects debugging, role of, The General Principle of Software Quality, Overview of Debugging Issues detection of defects by various techniques, table of, Percentage of Defects Detected development process assurance activities, Techniques for Improving Software Quality efficiency, Characteristics of Software Quality engineering guidelines, Techniques for Improving Software Quality explicit activity for, Techniques for Improving Software Quality external audits, Techniques for Improving Software Quality external characteristics of, The Software-Quality Landscape Extreme Programming, Percentage of Defects Detected flexibility, Characteristics of Software Quality gates, Techniques for Improving Software Quality General Principle of Software Quality, The General Principle of Software Quality integrity, Characteristics of Software Quality internal characteristics, Characteristics of Software Quality key points, Relevant Standards maintainability, Characteristics of Software Quality measurement of results, Development Process multiple defect detection techniques recommended, Percentage of Defects Detected objectives, setting, Techniques for Improving Software Quality, Development Process optimization conflicts, Characteristics of Software Quality percentage of defects measurement, Setting Objectives portability, Characteristics of Software Quality programmer performance, objectives based, Development Process prototyping, Development Process readability, Characteristics of Software Quality recommended combination for, Cost of Fixing Defects relationships of characteristics, Characteristics of Software Quality reliability, Characteristics of Software Quality resources for, The General Principle of Software Quality reusability, Characteristics of Software Quality reviews, Techniques for Improving Software Quality robustness, Characteristics of Software Quality standards, IEEE, Relevant Standards, Software Quality-Assurance Standards testing, Characteristics of Software Quality, Techniques for Improving Software Quality, Developer Testing understandability, Characteristics of Software Quality usability, The Software-Quality Landscape when to do assurance of, Cost of Fixing Defects R random-data generators, Test-Data Generators readability, Common Software Metaphors, Characteristics of Software Quality, Defects as Opportunities, Techniques for Encouraging Good Coding, Human and Computer Interpretations of a Program, Curiosity, Pick Your Process, Pick Your Process, Write Programs for People First, Computers Second, Write Programs for People First, Computers Second, Watch for Falling Rocks as management standard, Techniques for Encouraging Good Coding defects exposing lack of, Defects as Opportunities defined, Characteristics of Software Quality importance of, Common Software Metaphors, Pick Your Process maintenance benefit from, Write Programs for People First, Computers Second positive effects from, Pick Your Process private vs. public programs, Write Programs for People First, Computers Second professional development, importance to, Curiosity structures, importance of, Human and Computer Interpretations of a Program warning sign, as a, Watch for Falling Rocks reading as a skill, Curiosity reading plan for software developers, Special-Interest Publications records, refactoring, Data-Level Refactorings recursion, Multiple Returns from a Routine, Multiple Returns from a Routine, Recursion, Recursion, Example of Recursion, Example of Recursion, Example of Recursion, Tips for Using Recursion, Tips for Using Recursion, Tips for Using Recursion, Tips for Using Recursion, gotos, gotos alternatives to, Tips for Using Recursion (see ) checklist, gotos defined, Multiple Returns from a Routine factorials using, Tips for Using Recursion Fibonacci numbers using, Tips for Using Recursion guidelines for, Recursion key points, gotos maze example, Recursion safety counters for, Example of Recursion single routine guideline, Example of Recursion sorting example, Multiple Returns from a Routine stack space concerns, Tips for Using Recursion terminating, Example of Recursion refactoring, Code the Routine, Philosophy of Software Evolution, Philosophy of Software Evolution, Philosophy of Software Evolution, Philosophy of Software Evolution, Philosophy of Software Evolution, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons to Refactor, Reasons Not to Refactor, Reasons Not to Refactor, Reasons Not to Refactor, Reasons Not to Refactor, Reasons Not to Refactor, Reasons Not to Refactor, Data-Level Refactorings, Data-Level Refactorings, Data-Level Refactorings, Data-Level Refactorings, Data-Level Refactorings, Data-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Statement-Level Refactorings, Routine-Level Refactorings, Routine-Level Refactorings, Routine-Level Refactorings, Routine-Level Refactorings, Routine-Level Refactorings, Class Implementation Refactorings, Class Implementation Refactorings, Class Implementation Refactorings, Class Implementation Refactorings, Class Interface Refactorings, Class Interface Refactorings, Class Interface Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, System-Level Refactorings, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Refactoring Safely, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Bad Times to Refactor, Refactoring Strategies, Refactoring Strategies, Refactoring Strategies, Refactoring Strategies, Additional Resources, Additional Resources, Code-Tuning Techniques, Picky Syntax and Semantics Checkers 80/20 rule, Bad Times to Refactor adding routines, Bad Times to Refactor algorithms, Statement-Level Refactorings arrays, Data-Level Refactorings backing up old code, System-Level Refactorings bidirectional class associations, System-Level Refactorings boolean expressions, Data-Level Refactorings case statements, Statement-Level Refactorings checklists for, Reasons to Refactor, System-Level Refactorings checkpoints for, Refactoring Safely class cohesion indicator, Reasons to Refactor class interfaces, Class Implementation Refactorings classes, Reasons to Refactor, Routine-Level Refactorings, System-Level Refactorings, Bad Times to Refactor code tuning, compared to, Code-Tuning Techniques collections, Data-Level Refactorings comments on bad code, Reasons to Refactor complex modules, Refactoring Strategies conditional expressions, Statement-Level Refactorings constant values varying among subclass, Routine-Level Refactorings constructors to factory methods, System-Level Refactorings data from uncontrolled sources, Class Interface Refactorings data sets, related, as indicator, Reasons to Refactor data types to classes, Data-Level Refactorings data-level, Reasons Not to Refactor, System-Level Refactorings defects, fixes of, Bad Times to Refactor defined, Philosophy of Software Evolution designing code for future needs, Reasons to Refactor Don't Repeat Yourself principle, Philosophy of Software Evolution duplicate code indicator, Philosophy of Software Evolution error-prone modules, Bad Times to Refactor expressions, Reasons Not to Refactor global variables, Reasons to Refactor GUI data, Class Interface Refactorings if statements, Statement-Level Refactorings interfaces, Reasons to Refactor, Class Implementation Refactorings, System-Level Refactorings key points, Additional Resources listing planned steps, Refactoring Safely literal constants, Reasons Not to Refactor loops, Philosophy of Software Evolution, Statement-Level Refactorings maintenance triggering, Refactoring Strategies middleman classes, Reasons to Refactor misuse of, Bad Times to Refactor null objects, Statement-Level Refactorings objects, Routine-Level Refactorings one-at-a-time rule, Refactoring Safely overloaded primitive data types, Reasons to Refactor parallel modifications required indicator, Reasons to Refactor parameters, Reasons to Refactor, Reasons Not to Refactor, Statement-Level Refactorings PPP coding step, Code the Routine public data members, Reasons to Refactor queries, Routine-Level Refactorings reasons not to, Reasons Not to Refactor records, Data-Level Refactorings redesigning instead of, Bad Times to Refactor reference objects, Routine-Level Refactorings resources on, Additional Resources reviews of, Refactoring Safely risk levels of, Refactoring Safely routines, Philosophy of Software Evolution, Statement-Level Refactorings, System-Level Refactorings, Bad Times to Refactor safety guidelines, System-Level Refactorings, Refactoring Strategies setup code, Reasons to Refactor size guideline, Refactoring Safely statement-level, Data-Level Refactorings, System-Level Refactorings strategies for, Bad Times to Refactor subclasses, Reasons to Refactor, Class Implementation Refactorings superclasses, Class Implementation Refactorings system-level, Class Interface Refactorings, System-Level Refactorings takedown code, Reasons to Refactor testing, Refactoring Safely to do lists for, Refactoring Safely tools for, Picky Syntax and Semantics Checkers tramp data, Reasons to Refactor ugly code, interfaces to, Refactoring Strategies unidirectional class associations, System-Level Refactorings unit tests for, Refactoring Safely variables, Reasons Not to Refactor warnings, compiler, Refactoring Safely references (&), C++, General Tips on Pointers regression testing, Developer Testing, Building Scaffolding to Test Individual Classes, Improving Your Testing defined, Developer Testing diff tools for, Building Scaffolding to Test Individual Classes purpose of, Improving Your Testing reliability, Design at the Routine Level, Characteristics of Software Quality cohesive routines, Design at the Routine Level defined, Characteristics of Software Quality religious attitude toward programming, Team Variation, Layout as Religion, Iterate, Repeatedly, Again and Again, Iterate, Repeatedly, Again and Again, Iterate, Repeatedly, Again and Again, Eclecticism eclecticism, Iterate, Repeatedly, Again and Again experimentation compared to, Eclecticism harmful effects of, Iterate, Repeatedly, Again and Again layout styles becoming, Layout as Religion managing people, Team Variation software oracles, Iterate, Repeatedly, Again and Again reports, What Results Can You Expect from Inspections?


pages: 350 words: 114,454

Docker: Up & Running: Shipping Reliable Containers in Production by Sean P. Kane, Karl Matthias

Airbnb, Amazon Web Services, business logic, business process, cloud computing, Colossal Cave Adventure, continuous integration, Debian, DevOps, don't repeat yourself, false flag, interchangeable parts, Kubernetes, loose coupling, Lyft, microservices, revision control, software as a service, source of truth, web application

The ENV instruction allows you to set shell variables that can be used by your running application for configuration and during the build process to simplify the Dockerfile and help keep it DRYer:1 ENV AP /data/app ENV SCPATH /etc/supervisor/conf.d In the following code, you’ll use a collection of RUN instructions to start and create the required file structure that you need, and install some required software dependen‐ cies. RUN apt-get -y update # The daemons RUN apt-get -y install supervisor RUN mkdir -p /var/log/supervisor 1 Don’t Repeat Yourself. Anatomy of a Dockerfile | 51 While we’re demonstrating it here for simplicity, it is not recom‐ mended that you run commands like apt-get -y update or yum -y update in your application’s Dockerfile. This is because it requires crawling the repository index each time you run a build, and means that your build is not guaranteed to be repeatable since package versions might change between builds.


pages: 555 words: 119,733

Autotools by John Calcote

Albert Einstein, card file, Debian, delayed gratification, Dennis Ritchie, don't repeat yourself, en.wikipedia.org, Everything should be made as simple as possible, Free Software Foundation, place-making, Richard Feynman, seminal paper, 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: 960 words: 125,049

Mastering Ethereum: Building Smart Contracts and DApps by Andreas M. Antonopoulos, Gavin Wood Ph. D.

air gap, Amazon Web Services, bitcoin, blockchain, business logic, continuous integration, cryptocurrency, Debian, digital divide, Dogecoin, domain-specific language, don't repeat yourself, Edward Snowden, en.wikipedia.org, Ethereum, ethereum blockchain, fault tolerance, fiat currency, Firefox, functional programming, Google Chrome, information security, initial coin offering, intangible asset, Internet of things, litecoin, machine readable, move fast and break things, node package manager, non-fungible token, peer-to-peer, Ponzi scheme, prediction markets, pull request, QR code, Ruby on Rails, Satoshi Nakamoto, sealed-bid auction, sharing economy, side project, smart contracts, transaction costs, Turing complete, Turing machine, Vickrey auction, Vitalik Buterin, web application, WebSocket

If someone tells you that their project has produced “thousands of lines of code” for their smart contracts, you should question the security of that project. Simpler is more secure. Code reuse Try not to reinvent the wheel. If a library or contract already exists that does most of what you need, reuse it. Within your own code, follow the DRY principle: Don’t Repeat Yourself. If you see any snippet of code repeated more than once, ask yourself whether it could be written as a function or library and reused. Code that has been extensively used and tested is likely more secure than any new code you write. Beware of “Not Invented Here” syndrome, where you are tempted to “improve” a feature or component by building it from scratch.


pages: 680 words: 157,865

Beautiful Architecture: Leading Thinkers Reveal the Hidden Beauty in Software Design by Diomidis Spinellis, Georgios Gousios

Albert Einstein, barriers to entry, business intelligence, business logic, business process, call centre, continuous integration, corporate governance, database schema, Debian, domain-specific language, don't repeat yourself, Donald Knuth, duck typing, en.wikipedia.org, fail fast, fault tolerance, financial engineering, Firefox, Free Software Foundation, functional programming, general-purpose programming language, higher-order functions, iterative process, linked data, locality of reference, loose coupling, meta-analysis, MVC pattern, Neal Stephenson, no silver bullet, peer-to-peer, premature optimization, recommendation engine, Richard Stallman, Ruby on Rails, semantic web, smart cities, social graph, social web, SPARQL, Steve Jobs, Stewart Brand, Strategic Defense Initiative, systems thinking, the Cathedral and the Bazaar, traveling salesman, Turing complete, type inference, web application, zero-coupon bond

Early on, we had only a casual knowledge of Spring, so we chose not to depend on it, though we all expected to need it later. When we added Spring, the .jar file dependency problems were multiplied by configuration file problems. Each deployment configuration needs its own beans.xml file, but well over half of the beans would be duplicated between files—a clear violation of the “don’t repeat yourself” principle[10]—and a sure-fire source of defects. Nobody should have to manually synchronize bean definitions in thousand-line XML files. And, besides, isn’t a multi-thousand-line XML file a code smell in its own right? We needed a solution that would let us modularize Spring beans files, manage .jar file dependencies, keep libraries close to the code that uses them, and manage the classpath at build time and at runtime.


pages: 1,606 words: 168,061

Python Cookbook by David Beazley, Brian K. Jones

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

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).


pages: 612 words: 187,431

The Art of UNIX Programming by Eric S. Raymond

A Pattern Language, Albert Einstein, Apple Newton, barriers to entry, bioinformatics, Boeing 747, Clayton Christensen, combinatorial explosion, commoditize, Compatible Time-Sharing System, correlation coefficient, David Brooks, Debian, Dennis Ritchie, domain-specific language, don't repeat yourself, Donald Knuth, end-to-end encryption, Everything should be made as simple as possible, facts on the ground, finite state, Free Software Foundation, general-purpose programming language, George Santayana, history of Unix, Innovator's Dilemma, job automation, Ken Thompson, Larry Wall, level 1 cache, machine readable, macro virus, Multics, MVC pattern, Neal Stephenson, no silver bullet, OSI model, pattern recognition, Paul Graham, peer-to-peer, premature optimization, pre–internet, publish or perish, revision control, RFC: Request For Comment, Richard Stallman, Robert Metcalfe, Steven Levy, the Cathedral and the Bazaar, transaction costs, Turing complete, Valgrind, wage slave, web application

But on the whole the Unix API is a good example: Otherwise it not only would not but could not be so widely imitated by C libraries on other operating systems. This is also a reason that the Unix API repays study even if you are not a Unix programmer; it has lessons about orthogonality to teach. The SPOT Rule The Pragmatic Programmer articulates a rule for one particular kind of orthogonality that is especially important. Their “Don't Repeat Yourself” rule is: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. In this book we prefer, following a suggestion by Brian Kernighan, to call this the Single Point Of Truth or SPOT rule. Repetition leads to inconsistency and code that is subtly broken, because you changed only some repetitions when you needed to change all of them.


pages: 999 words: 194,942

Clojure Programming by Chas Emerick, Brian Carper, Christophe Grand

Amazon Web Services, Benoit Mandelbrot, cloud computing, cognitive load, continuous integration, database schema, domain-specific language, don't repeat yourself, drop ship, duck typing, en.wikipedia.org, failed state, finite state, Firefox, functional programming, game design, general-purpose programming language, Guido van Rossum, higher-order functions, Larry Wall, mandelbrot fractal, no silver bullet, 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, SQL injection, 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.


pages: 1,201 words: 233,519

Coders at Work by Peter Seibel

Ada Lovelace, Bill Atkinson, bioinformatics, Bletchley Park, Charles Babbage, cloud computing, Compatible Time-Sharing System, Conway's Game of Life, Dennis Ritchie, domain-specific language, don't repeat yourself, Donald Knuth, fallacies of distributed computing, fault tolerance, Fermat's Last Theorem, Firefox, Free Software Foundation, functional programming, George Gilder, glass ceiling, Guido van Rossum, history of Unix, HyperCard, industrial research laboratory, information retrieval, Ken Thompson, L Peter Deutsch, Larry Wall, loose coupling, Marc Andreessen, Menlo Park, Metcalfe's law, Multics, no silver bullet, 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, systems thinking, the scientific method, Therac-25, Turing complete, Turing machine, Turing test, type inference, Valgrind, web application

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.