Some people feel that getting objectoriented

Size: px
Start display at page:

Download "Some people feel that getting objectoriented"

Transcription

1 software construction Editors: Dave Thomas and Andy Hunt The Pragmatic Programmers OO in One Sentence: Keep It DRY, Shy, and Tell the Other Guy Andy Hunt and Dave Thomas Some people feel that getting objectoriented programming is a difficult, time-consuming process. But does it need to be that hard? And is the difficulty even specific to OO programming? Many of the cornerstones of OO programming benefit other programming paradigms as well. Even if you re writing shell scripts or batch files, you can use these techniques to great advantage. What s good code? There are many aspects to writing good code, but most of these hinge on a single underlying quality: flexibility. Flexibility means that you can change the code easily, adapt it to new and revised circumstances, and use it in contexts other than those originally intended. Why does code need to be flexible? It s largely because of us humans. We misunderstand communications (be they written or oral). Requirements change. We build the right thing the wrong way, or if we manage to build something the right way, it turns out to be the wrong thing by the time we re done. Despite our fondest wishes, we ll never get it right the first time. Our mistakes lie in continually assuming that we can and in searching for salvation in new programming languages, better processes, or new IDEs. Instead, we need to realize that software must be soft: it has to be easy to change because it will change despite our misguided efforts otherwise. Capers Jones, in his book Software Assessments, Benchmarks, and Best Practices (Addison-Wesley, 2000), showed that requirements change at a rate of about 2 percent per month (which really starts to add up after a year or two). But the problem with changes to projects is by no means limited to the common scapegoat of requirements, nor is it limited to the software industry. According to a study of building construction in the UK ( Rethinking Construction, Construction Task Force report to the Deputy Prime Minister, 1998), some 30 percent of rework isn t due to requirements changes at all. It s due to mistakes: plain, old human errors, such as cutting a joist 2 inches too short. Using the wrong kind of nail. Cutting the window in the wrong wall. It s just human nature that we ll get some things wrong, so what differentiates software quality is how well and how quickly we can fix or change something. Flexible code can be changed easily and cheaply, regardless of whether the change is necessitated by volatile requirements or our own misunderstanding. Most of the important lessons to be learned about object technology how to avoid many /04/$ IEEE Published by the IEEE Computer Society IEEE SOFTWARE 101

2 SOFTWARE CONSTRUCTION getorder().getcustomer().getaddress().getstate() Figure 1. Example of the train wreck style of dynamic coupling. common mistakes and keep code flexible can be summed up in one sentence: Keep it DRY, keep it shy, and tell the other guy. Let s take a look at what that means and how you can apply these lessons to all good code, not just OO code. Keep it DRY Our DRY (Don t Repeat Yourself) principle deals with knowledge representation in programs (see The Pragmatic Programmer, Addison-Wesley, 2000). It s a powerful idea that states: Every piece of knowledge must have a single, unambiguous, and authoritative representation within a system. In other words, you should represent any idea, any scrap of knowledge, in a system in just one place. You might end up with physical copies of code for various reasons (middleware and database products could impose this restriction, for instance). But only one of these physical representations is the authoritative source. Ideally, you d be able to automatically generate or produce the nonauthoritative sources from the single authoritative source. Why go to all this trouble? So that when a code change is required, you only have to make it in one place. Anything else is a recipe for disaster, introducing inconsistencies and potentially hard-to-find bugs. DRY applies to code but also to every other part of the system and to developers daily lives build processes, documentation, database schema, code reviews, and so on. Keep it shy The best code is very shy. Like a four-year old hiding behind a mother s skirt, code shouldn t reveal too much of itself and shouldn t be too nosy into others affairs. But you might find that your shy code grows up too fast, shedding its demure shyness in favor of wild promiscuity. When code isn t shy, you ll get unwanted coupling; these axes of ill-advised coupling include static, dynamic, domain, and temporal. Static coupling exists when a piece of code requires another piece of code to compile. This isn t a bad or evil thing far from it. Even the canonical Hello World program requires the standard I/O library and such. But you have to be aware of accidentally dragging in more than you need. Inheritance is infamous for dragging in a lot of excess baggage. Often it s more efficient, more flexible, and safer to use delegation instead of inheritance (which should be reserved for true is-a relationships, not has-a or uses-a). Shy people don t talk to strangers, and shy code should be equally wary of other code that wants to come along for the ride. Dynamic coupling occurs when a piece of code uses another piece of code at runtime. This can get seriously out of hand using a style we call the train wreck (see Figure 1). To get the state for an order, this code has to have detailed knowledge of an address, a customer, and an order Always plan on writing concurrent code because the odds are good that it will end up that way anyhow, and you ll get a better design as a fringe benefit. and rely on these three components implied hierarchal structure. If anything in that mix changes, we re in trouble; this code will break. Shy code only talks to code it deals with directly and doesn t daisy-chain through to strangers as in the previous example. Domain coupling takes place when business rules and policies become embedded in code. Again, that s not necessarily a bad thing unless mirroring realworld changes becomes difficult. If the real world is particularly volatile, put the business rules in metadata, either in a database or property file. Keep the code shy by not being too nosy about the details: the code can act as an engine for the business rules. The rules can change at whim, and the code will merrily process them without any change to the code itself. Small interpreters work well for this (really small like a case statement, not a large yacc/lex endeavor). Temporal coupling appears when you have a dependency on time either on things that must occur in a certain order, at a certain time, by a certain time, or worse, at the same time. Always plan on writing concurrent code because the odds are good that it will end up that way anyhow, and you ll get a better design as a fringe benefit. Your code shouldn t care about what else might be happening at the same time; it should just work regardless. Code shouldn t be nosy. I used to have a neighbor who would peer hawklike over her kitchen sink out the front window and keep track of every neighbor s comings and goings. Her life hung at the mercy of every whim of the entire neighborhood; it wasn t a healthy position for her to be in, and it isn t a healthy position for your code either. A big part of not being nosy lies in our next item. Tell the other guy One of our favorite OO principles is Tell, Don t Ask (see IEEE Software, Jan./Feb. 2003, p. 10). To recap briefly: as an industry, we ve come to think of software in terms of function calls. Even in OO systems, we 102 IEEE SOFTWARE

3 ADVERTISER / PRODUCT INDEX view an object s behavioral interface as a set of function calls. That s really not a helpful metaphor. Instead of calling software a function, view it as sending a message. Sending a message to an object conveys an air of apathy. I ve just sent you an order (or a request), and I don t really care who or what you are or (especially) how you do it. Just get it done. This service-oriented, operationcentric viewpoint is critical to good code. Apathy toward the details, in this case, is just the right approach. You tell an object what to do; you don t ask it for data (too many details) and attempt to do the work yourself. By telling the other guy in this way, you ensure an imperative coding style that keeps your code from becoming too nosy and from getting involved in details that it shouldn t care about. Such involvement would make your code much more vulnerable to change. To make this work in a system, you ll need to preserve the commonsense semantics of commands (that is, every object that has a print method should behave similarly when called). This isn t an OO-specific technique either. Even shell scripts can benefit from this approach. In fact, a common Linux command employs polymorphism at the command line. The command fsck (which is not a cartoon swear word really) performs a file system check. When you invoke fsck, it determines the file system type and then runs a delegate, such as fsck.ext2, fsck.msdos, or fsck.vfat, that performs the actual tests for that kind of file system. But you, as the requester, don t care. You tell the system to check the disk via an fsck command and it just does it. It s just the right amount of apathy. So remember to keep it DRY, keep it shy, and tell the other guy. Andy Hunt and Dave Thomas are partners in The Pragmatic Programmers and authors of the Jolt Productivity Award-winning The Pragmatic Starter Kit book series. Contact them via Advertiser / Product Mid Atlantic (product/recruitment) Dawn Becker Phone: Fax: New England (product) Jody Estabrook Phone: Fax: New England (recruitment) Barbara Lynch Phone: Fax: Connecticut (product) Stan Greenfield Phone: Fax: Southeast (recruitment) Jana Smith Phone: Fax: Southeast (product) Bob Doran Phone: Fax: MAY/JUNE 2004 Agile Development Conference 2004 Cover 4 JavaOne Pace University 1 SAP Labs 9 Scientific Toolworks, Inc. 10 Software Development Springer-Verlag New York, Inc. Cover 2 Classified Advertising 47 Marion Delaney IEEE Media, Advertising Director Phone: Fax: Marian Anderson Advertising Coordinator Phone: Fax: Advertising Personnel Midwest/Southwest (recruitment) Darcy Giovingo Phone: Fax: Midwest (product) Dave Jones Phone: Fax: Will Hamilton Phone: Fax: Joe DiNardo Phone: Fax: Southwest (product) Josh Mayer Phone: Fax: Northwest (product) Peter D. Scott Phone: Fax: Page Number Sandy Brown IEEE Computer Society, Business Development Manager Phone: Fax: Advertising Sales Representatives IEEE Software IEEE Computer Society Los Vaqueros Circle Los Alamitos, California USA Phone: Fax: Southern CA (product) Marshall Rubin Phone: Fax: Northwest/Southern CA (recruitment) Tim Matteson Phone: Fax: Japan (product/recruitment) German Tajiri Phone: Fax: Europe (product) Hilary Turnbull Phone: Fax: Europe (recruitment) Penny Lee Phone: Fax:

Businesses create huge amounts of potentially

Businesses create huge amounts of potentially There s content everywhere, but not the information you need. Content analysis can organize a pile of text into a richly accessible repository. Ramana Rao From Unstructured Data to Actionable Intelligence

More information

Greg Linden, Brent Smith, and Jeremy York Amazon.com

Greg Linden, Brent Smith, and Jeremy York Amazon.com Industry Report Amazon.com Recommendations Item-to-Item Collaborative Filtering Greg Linden, Brent Smith, and Jeremy York Amazon.com Recommendation algorithms are best known for their use on e-commerce

More information

What are requirements?

What are requirements? 2004 Steve Easterbrook. DRAFT PLEASE DO NOT CIRCULATE page 1 C H A P T E R 2 What are requirements? The simple question what are requirements? turns out not to have a simple answer. In this chapter we

More information

Programming from the Ground Up

Programming from the Ground Up Programming from the Ground Up Jonathan Bartlett Edited by Dominick Bruno, Jr. Programming from the Ground Up by Jonathan Bartlett Edited by Dominick Bruno, Jr. Copyright 2003 by Jonathan Bartlett Permission

More information

Basic Marketing Research: Volume 1

Basic Marketing Research: Volume 1 Basic Marketing Research: Volume 1 Handbook for Research Professionals Official Training Guide from Qualtrics Scott M. Smith Gerald S. Albaum Copyright 2012, Qualtrics Labs, Inc. ISBN: 978-0-9849328-1-8

More information

When Should a Test Be Automated?

When Should a Test Be Automated? Brian Marick Testing Foundations marick@testing.com I want to automate as many tests as I can. I m not comfortable running a test only once. What if a programmer then changes the code and introduces a

More information

Tips for writing good use cases.

Tips for writing good use cases. Transforming software and systems delivery White paper May 2008 Tips for writing good use cases. James Heumann, Requirements Evangelist, IBM Rational Software Page 2 Contents 2 Introduction 2 Understanding

More information

Base Tutorial: From Newbie to Advocate in a one, two... three!

Base Tutorial: From Newbie to Advocate in a one, two... three! Base Tutorial: From Newbie to Advocate in a one, two... three! BASE TUTORIAL: From Newbie to Advocate in a one, two... three! Step-by-step guide to producing fairly sophisticated database applications

More information

How To Write a Good PRD. Martin Cagan Silicon Valley Product Group

How To Write a Good PRD. Martin Cagan Silicon Valley Product Group How To Write a Good PRD Martin Cagan Silicon Valley Product Group HOW TO WRITE A GOOD PRD Martin Cagan, Silicon Valley Product Group OVERVIEW The PRD describes the product your company will build. It

More information

How Do You Know It? How Can You Show It?

How Do You Know It? How Can You Show It? How Do You Know It? How Can You Show It? Penny Reed Wisconsin Assistive Technology Initiative Gayl Bowser Oregon Technology Access Program Jane Korsten Responsive Centers for Psychology and Learning Wisconsin

More information

Rich Data, Poor Data Designing Dashboards to Inform

Rich Data, Poor Data Designing Dashboards to Inform Rich Data, Poor Data Designing Dashboards to Inform by Stephen Few A note about the author Stephen Few has worked for 24 years as an IT innovator, consultant, and educator. Today, as Principal of the consultancy

More information

Information for parents living apart from their child

Information for parents living apart from their child Information for parents living apart from their child a child maintenance decisions guide Understand your child maintenance choices Tools to help you set up a child maintenance arrangement Ideas from other

More information

Why Johnny Can t Encrypt: A Usability Evaluation of PGP 5.0

Why Johnny Can t Encrypt: A Usability Evaluation of PGP 5.0 Why Johnny Can t Encrypt: A Usability Evaluation of PGP 5.0 Alma Whitten School of Computer Science Carnegie Mellon University Pittsburgh, PA 15213 alma@cs.cmu.edu J. D. Tygar 1 EECS and SIMS University

More information

Understand how to develop and maintain

Understand how to develop and maintain 7. 1 working Understand how to develop and maintain relationships This topic guide will give you some of the tools to be able to understand working relationships, develop them and then maintain them by

More information

Turning Strategies into Action

Turning Strategies into Action Turning Strategies into Action Economic Development Planning Guide for Communities Turning Strategies into Action Table of Contents Introduction 2 Steps to taking action 6 1. Identify a leader to drive

More information

Making Smart IT Choices

Making Smart IT Choices Making Smart IT Choices Understanding Value and Risk in Government IT Investments Sharon S. Dawes Theresa A. Pardo Stephanie Simon Anthony M. Cresswell Mark F. LaVigne David F. Andersen Peter A. Bloniarz

More information

USE-CASE 2.0. The Guide to Succeeding with Use Cases. Ivar Jacobson Ian Spence Kurt Bittner. December 2011. USE-CASE 2.0 The Definitive Guide

USE-CASE 2.0. The Guide to Succeeding with Use Cases. Ivar Jacobson Ian Spence Kurt Bittner. December 2011. USE-CASE 2.0 The Definitive Guide USE-CASE 2.0 The Guide to Succeeding with Use Cases Ivar Jacobson Ian Spence Kurt Bittner December 2011 USE-CASE 2.0 The Definitive Guide About this Guide 3 How to read this Guide 3 What is Use-Case 2.0?

More information

Evaluation. valuation of any kind is designed to document what happened in a program.

Evaluation. valuation of any kind is designed to document what happened in a program. Using Case Studies to do Program Evaluation E valuation of any kind is designed to document what happened in a program. Evaluation should show: 1) what actually occurred, 2) whether it had an impact, expected

More information

Objects and Agents: How do they differ?

Objects and Agents: How do they differ? Copyright 1999, James Odell DRAFT 2.2 1 Objects and Agents: How do they differ? by James Odell Just how different are objects and agents? Some developers consider agents to be objects, but with more bells

More information

On System Design. Jim Waldo

On System Design. Jim Waldo On System Design Jim Waldo On System Design Jim Waldo Perspectives 2006-6 In an Essay Series Published by Sun Labs December 2006 This work first appeared as part of the OOPSLA 2006 Essays track, October

More information

Managing digital records without an electronic record management system

Managing digital records without an electronic record management system Managing digital records without an electronic record management system Crown copyright 2012 You may re-use this information (excluding logos) free of charge in any format or medium, under the terms of

More information

PLANNING ANALYSIS PLANNING ANALYSIS DESIGN

PLANNING ANALYSIS PLANNING ANALYSIS DESIGN PLANNING ANALYSIS Apply Requirements Analysis Technique (Business Process Automation, Business Process Improvement, or Business Process Reengineering) Use Requirements-Gathering Techniques (Interview,

More information

Why Johnny Can t Encrypt

Why Johnny Can t Encrypt In Security and Usability: Designing Secure Systems that People Can Use, eds. L. Cranor and G. Simson. O'Reilly, 2005, pp. 679-702 CHAPTER THIRTY- FOUR Why Johnny Can t Encrypt A Usability Evaluation of

More information

Monitoring and Evaluation

Monitoring and Evaluation OVERVIEW Brief description This toolkit deals with the nuts and bolts (the basics) of setting up and using a monitoring and evaluation system for a project or an organisation. It clarifies what monitoring

More information

THE PLAIN LANGUAGE VERSION OF THE PROMOTION OF ACCESS TO INFORMATION

THE PLAIN LANGUAGE VERSION OF THE PROMOTION OF ACCESS TO INFORMATION THE PLAIN LANGUAGE VERSION OF THE PROMOTION OF ACCESS TO INFORMATION ACT CONTENTS Part 1: Introduction What is the Act trying to achieve? Who does the Act apply to? Part 2: Provisions in the Act relating

More information

Out of the Tar Pit. February 6, 2006

Out of the Tar Pit. February 6, 2006 Out of the Tar Pit Ben Moseley ben@moseley.name Peter Marks public@indigomail.net February 6, 2006 Abstract Complexity is the single major difficulty in the successful development of large-scale software

More information

How to Write More Clearly, Think More Clearly, and Learn Complex Material More Easily

How to Write More Clearly, Think More Clearly, and Learn Complex Material More Easily How to Write More Clearly, Think More Clearly, and Learn Complex Material More Easily Michael A. Covington Artificial Intelligence Center The University of Georgia Copyright 2005, 2009 Michael A. Covington

More information

WHAT IS APPLICATION LIFECYCLE MANAGEMENT?

WHAT IS APPLICATION LIFECYCLE MANAGEMENT? WHAT IS APPLICATION LIFECYCLE MANAGEMENT? DAVID CHAPPELL DECEMBER 2008 SPONSORED BY MICROSOFT CORPORATION COPYRIGHT 2008 CHAPPELL & ASSOCIATES Defining application lifecycle management (ALM) isn t easy.

More information

Do-it-Yourself Recovery of Unpaid Wages

Do-it-Yourself Recovery of Unpaid Wages Do-it-Yourself Recovery of Unpaid Wages How to Represent Yourself Before the California Labor Commissioner A Publication of: The Legal Aid Society-Employment Law Center 600 Harrison Street, Suite 120 San

More information

As Good As They Give. Providing volunteers with the management they deserve. Workbook Two Attracting and Selecting Volunteers

As Good As They Give. Providing volunteers with the management they deserve. Workbook Two Attracting and Selecting Volunteers As Good As They Give Providing volunteers with the management they deserve Workbook Two Attracting and Selecting Volunteers Volunteering takes many forms - traditional service giving, mutual aid and self-help,

More information