100% found this document useful (1 vote)
112 views

Practical object-oriented design: an agile primer using Ruby Second Edition Metz 2024 Scribd Download

using

Uploaded by

calhazgarki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
112 views

Practical object-oriented design: an agile primer using Ruby Second Edition Metz 2024 Scribd Download

using

Uploaded by

calhazgarki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Practical object-oriented design: an agile primer


using Ruby Second Edition Metz

https://textbookfull.com/product/practical-object-oriented-
design-an-agile-primer-using-ruby-second-edition-metz/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Systems Analysis and Design An Object Oriented Approach


with UML Dennis

https://textbookfull.com/product/systems-analysis-and-design-an-
object-oriented-approach-with-uml-dennis/

textboxfull.com

Object-Oriented Design with ABAP: A Practical Approach 1st


Edition James E. Mcdonough (Auth.)

https://textbookfull.com/product/object-oriented-design-with-abap-a-
practical-approach-1st-edition-james-e-mcdonough-auth/

textboxfull.com

Object Oriented Data Structures Using Java 4th Edition


Dale

https://textbookfull.com/product/object-oriented-data-structures-
using-java-4th-edition-dale/

textboxfull.com

Systems Analysis and Design An Object Oriented Approach


with UML 5th Edition Dennis

https://textbookfull.com/product/systems-analysis-and-design-an-
object-oriented-approach-with-uml-5th-edition-dennis/

textboxfull.com
C++ Programming: An Object-Oriented Approach, 1e ISE
Behrouz A. Forouzan

https://textbookfull.com/product/c-programming-an-object-oriented-
approach-1e-ise-behrouz-a-forouzan/

textboxfull.com

Design Patterns in Modern C++: Reusable Approaches for


Object-Oriented Software Design 1st Edition Dmitri
Nesteruk
https://textbookfull.com/product/design-patterns-in-modern-c-reusable-
approaches-for-object-oriented-software-design-1st-edition-dmitri-
nesteruk/
textboxfull.com

Head First Design Patterns: Building Extensible and


Maintainable Object-Oriented Software 2nd Edition Eric
Freeman
https://textbookfull.com/product/head-first-design-patterns-building-
extensible-and-maintainable-object-oriented-software-2nd-edition-eric-
freeman/
textboxfull.com

Deep Learning in Python An Object Oriented Programming 1st


Edition Hong M. Lei [Lei

https://textbookfull.com/product/deep-learning-in-python-an-object-
oriented-programming-1st-edition-hong-m-lei-lei/

textboxfull.com

Object Orientation Abstraction and Data Structures Using


Scala Second Edition Lacher

https://textbookfull.com/product/object-orientation-abstraction-and-
data-structures-using-scala-second-edition-lacher/

textboxfull.com
About This E-Book
EPUB is an open, industry-standard format for e-books.
However, support for EPUB and its many features varies across
reading devices and applications. Use your device or app settings to
customize the presentation to your liking. Settings that you can
customize often include font, font size, single or double column,
landscape or portrait mode, and figures that you can click or tap to
enlarge. For additional information about the settings and features
on your reading device or app, visit the device manufacturer’s Web
site.
Many titles include programming code or configuration
examples. To optimize the presentation of these elements, view the
e-book in single-column, landscape mode and adjust the font size to
the smallest setting. In addition to presenting code and
configurations in the reflowable text format, we have included
images of the code that mimic the presentation found in the print
book; therefore, where the reflowable format may compromise the
presentation of the code listing, you will see a “Click here to view
code image” link. Click the link to view the print-fidelity code image.
To return to the previous page viewed, click the Back button on your
device or app.
Praise for the first edition of Practical
Object-Oriented Design in Ruby
“Meticulously pragmatic and exquisitely articulate, Practical
Object Oriented Design in Ruby makes otherwise elusive
knowledge available to an audience which desperately needs it.
The prescriptions are appropriate both as rules for novices and
as guidelines for experienced professionals.”
—Katrina Owen, Creator, Exercism
“I do believe this will be the most important Ruby book of 2012.
Not only is the book 100% on-point, Sandi has an easy writing
style with lots of great analogies that drive every point home.”
—Avdi Grimm, author of Exceptional Ruby and Objects on Rails
“While Ruby is an object-oriented language, little time is spent
in the documentation on what OO truly means or how it should
direct the way we build programs. Here Metz brings it to the
fore, covering most of the key principles of OO development
and design in an engaging, easy-to-understand manner. This is
a must for any respectable Ruby bookshelf.”
—Peter Cooper, editor, Ruby Weekly

“So good, I couldn’t put it down! This is a must-read for anyone


wanting to do object-oriented programming in any language,
not to mention it has completely changed the way I approach
testing.”
—Charles Max Wood, Ruby Rogues Podcast co-host and CEO of
Devchat.tv
“Distilling scary OO design practices with clear-cut examples and
explanations makes this a book for novices and experts alike. It
is well worth the study by anyone interested in OO design being
done right and ‘light.’ I thoroughly enjoyed this book.”
—Manuel Pais, DevOps and Continuous Delivery Consultant,
Independent
“If you call yourself a Ruby programmer, you should read this
book. It’s jam-packed with great nuggets of practical advice and
coding techniques that you can start applying immediately in
your projects.”
—Ylan Segal, San Diego Ruby User Group

“This is the best OO book I’ve ever read. It’s short, sweet, but
potent. It slowly moves from simple techniques to more
advanced, each example improving on the last. The ideas it
presents are useful not just in Ruby but in static languages like
C# too. Highly recommended!”
—Kevin Berridge, software engineering manager, Pointe Blank
Solutions, and organizer, Burning River Developers Meetup
“This is the best programming book I’ve read in ages. Sandi
talks about basic principles, but these are things we’re probably
still doing wrong and she shows us why and how. The book has
the perfect mix of code, diagrams, and words. I can’t
recommend it enough and if you’re serious about being a better
programmer, you’ll read it and agree.
—Derick Hitchcock, software engineer, Cisco

“Metz’s take on the subject is rooted strongly in theory, but the


explanation always stays grounded in real world concerns,
which helped me to internalize it. The book is clear and concise,
yet achieves a tone that is more friendly than terse.”
—Alex Strasheim, network administrator, Ensemble Travel Group

“Whether you’re just getting started in your software


development career, or you’ve been coding for years (like I
have), it’s likely that you’ll learn a lot from Ms. Metz’s book. She
does a fantastic job of explaining the whys of well-designed
software along with the hows.”
—Gabe Hollombe, software craftsman, avantbard.com
PRACTICAL OBJECT-ORIENTED DESIGN
An Agile Primer Using Ruby

Second Edition

Sandi Metz

Boston • Columbus • New York • San Francisco • Amsterdam •


Cape Town • Dubai London • Madrid • Milan • Munich • Paris •
Montreal • Toronto • Delhi • Mexico City São Paulo • Sydney •
Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to
distinguish their products are claimed as trademarks. Where those
designations appear in this book, and the publisher was aware of a
trademark claim, the designations have been printed with initial
capital letters or in all capitals.
The author and publisher have taken care in the preparation of this
book, but make no expressed or implied warranty of any kind and
assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with
or arising out of the use of the information or programs contained
herein.
For information about buying this title in bulk quantities, or for
special sales opportunities (which may include electronic versions;
custom cover designs; and content particular to your business,
training goals, marketing focus, or branding interests), please
contact our corporate sales department at
[email protected] or (800) 382-3419.
For government sales inquiries, please contact
[email protected].
For questions about sales outside the U.S., please contact
[email protected].
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2018939833
Copyright © 2019 Pearson Education, Inc.
All rights reserved. This publication is protected by copyright, and
permission must be obtained from the publisher prior to any
prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the
Pearson Education Global Rights & Permissions Department, please
visit www.pearsoned.com/permissions/.
ISBN-13: 978-0-13-445647-8
ISBN-10: 0-13-445647-5
1 18
For Amy, who read everything first
Contents

Introduction
Acknowledgments
About the Author

1 Object-Oriented Design
1.1 In Praise of Design
1.1.1 The Problem Design Solves
1.1.2 Why Change Is Hard
1.1.3 A Practical Definition of Design
1.2 The Tools of Design
1.2.1 Design Principles
1.2.2 Design Patterns
1.3 The Act of Design
1.3.1 How Design Fails
1.3.2 When to Design
1.3.3 Judging Design
1.4 A Brief Introduction to Object-Oriented Programming
1.4.1 Procedural Languages
1.4.2 Object-Oriented Languages
1.5 Summary
2 Designing Classes with a Single Responsibility
2.1 Deciding What Belongs in a Class
2.1.1 Grouping Methods into Classes
2.1.2 Organizing Code to Allow for Easy Changes
2.2 Creating Classes That Have a Single Responsibility
2.2.1 An Example Application: Bicycles and Gears
2.2.2 Why Single Responsibility Matters
2.2.3 Determining If a Class Has a Single Responsibility
2.2.4 Determining When to Make Design Decisions
2.3 Writing Code That Embraces Change
2.3.1 Depend on Behavior, Not Data
2.3.2 Enforce Single Responsibility Everywhere
2.4 Finally, the Real Wheel
2.5 Summary

3 Managing Dependencies
3.1 Understanding Dependencies
3.1.1 Recognizing Dependencies
3.1.2 Coupling Between Objects (CBO)
3.1.3 Other Dependencies
3.2 Writing Loosely Coupled Code
3.2.1 Inject Dependencies
3.2.2 Isolate Dependencies
3.2.3 Remove Argument-Order Dependencies
3.3 Managing Dependency Direction
3.3.1 Reversing Dependencies
3.3.2 Choosing Dependency Direction
3.4 Summary
4 Creating Flexible Interfaces
4.1 Understanding Interfaces
4.2 Defining Interfaces
4.2.1 Public Interfaces
4.2.2 Private Interfaces
4.2.3 Responsibilities, Dependencies, and Interfaces
4.3 Finding the Public Interface
4.3.1 An Example Application: Bicycle Touring Company
4.3.2 Constructing an Intention
4.3.3 Using Sequence Diagrams
4.3.4 Asking for “What” Instead of Telling “How”
4.3.5 Seeking Context Independence
4.3.6 Trusting Other Objects
4.3.7 Using Messages to Discover Objects
4.3.8 Creating a Message-Based Application
4.4 Writing Code That Puts Its Best (Inter)Face Forward
4.4.1 Create Explicit Interfaces
4.4.2 Honor the Public Interfaces of Others
4.4.3 Exercise Caution When Depending on Private
Interfaces
4.4.4 Minimize Context
4.5 The Law of Demeter
4.5.1 Defining Demeter
4.5.2 Consequences of Violations
4.5.3 Avoiding Violations
4.5.4 Listening to Demeter
4.6 Summary

5 Reducing Costs with Duck Typing


5.1 Understanding Duck Typing
5.1.1 Overlooking the Duck
5.1.2 Compounding the Problem
5.1.3 Finding the Duck
5.1.4 Consequences of Duck Typing
5.2 Writing Code That Relies on Ducks
5.2.1 Recognizing Hidden Ducks
5.2.2 Placing Trust in Your Ducks
5.2.3 Documenting Duck Types
5.2.4 Sharing Code between Ducks
5.2.5 Choosing Your Ducks Wisely
5.3 Conquering a Fear of Duck Typing
5.3.1 Subverting Duck Types with Static Typing
5.3.2 Static versus Dynamic Typing
5.3.3 Embracing Dynamic Typing
5.4 Summary

6 Acquiring Behavior through Inheritance


6.1 Understanding Classical Inheritance
6.2 Recognizing Where to Use Inheritance
6.2.1 Starting with a Concrete Class
6.2.2 Embedding Multiple Types
6.2.3 Finding the Embedded Types
6.2.4 Choosing Inheritance
6.2.5 Drawing Inheritance Relationships
6.3 Misapplying Inheritance
6.4 Finding the Abstraction
6.4.1 Creating an Abstract Superclass
6.4.2 Promoting Abstract Behavior
6.4.3 Separating Abstract from Concrete
6.4.4 Using the Template Method Pattern
6.4.5 Implementing Every Template Method
6.5 Managing Coupling between Superclasses and Subclasses
6.5.1 Understanding Coupling
6.5.2 Decoupling Subclasses Using Hook Messages
6.6 Summary

7 Sharing Role Behavior with Modules


7.1 Understanding Roles
7.1.1 Finding Roles
7.1.2 Organizing Responsibilities
7.1.3 Removing Unnecessary Dependencies
7.1.4 Writing the Concrete Code
7.1.5 Extracting the Abstraction
7.1.6 Looking Up Methods
7.1.7 Inheriting Role Behavior
7.2 Writing Inheritable Code
7.2.1 Recognize the Antipatterns
7.2.2 Insist on the Abstraction
7.2.3 Honor the Contract
7.2.4 Use the Template Method Pattern
7.2.5 Preemptively Decouple Classes
7.2.6 Create Shallow Hierarchies
7.3 Summary

8 Combining Objects with Composition


8.1 Composing a Bicycle of Parts
8.1.1 Updating the Bicycle Class
8.1.2 Creating a Parts Hierarchy
8.2 Composing the Parts Object
8.2.1 Creating a Part
8.2.2 Making the Parts Object More Like an Array
8.3 Manufacturing Parts
8.3.1 Creating the PartsFactory
8.3.2 Leveraging the PartsFactory
8.4 The Composed Bicycle
8.5 Deciding between Inheritance and Composition
8.5.1 Accepting the Consequences of Inheritance
8.5.2 Accepting the Consequences of Composition
8.5.3 Choosing Relationships
8.6 Summary

9 Designing Cost-Effective Tests


9.1 Intentional Testing
9.1.1 Knowing Your Intentions
9.1.2 Knowing What to Test
9.1.3 Knowing When to Test
9.1.4 Knowing How to Test
9.2 Testing Incoming Messages
9.2.1 Deleting Unused Interfaces
9.2.2 Proving the Public Interface
9.2.3 Isolating the Object under Test
9.2.4 Injecting Dependencies Using Classes
9.2.5 Injecting Dependencies as Roles
9.3 Testing Private Methods
9.3.1 Ignoring Private Methods during Tests
9.3.2 Removing Private Methods from the Class under Test
9.3.3 Choosing to Test a Private Method
9.4 Testing Outgoing Messages
9.4.1 Ignoring Query Messages
9.4.2 Proving Command Messages
9.5 Testing Duck Types
9.5.1 Testing Roles
9.5.2 Using Role Tests to Validate Doubles
9.6 Testing Inherited Code
9.6.1 Specifying the Inherited Interface
9.6.2 Specifying Subclass Responsibilities
9.6.3 Testing Unique Behavior
9.7 Summary

Afterword
Index
Introduction

We want to do our best work, and we want the work we do to have


meaning. And, all else being equal, we prefer to enjoy ourselves
along the way.
Those of us whose work is to write software are incredibly lucky.
Building software is a guiltless pleasure because we get to use our
creative energy to get things done. We have arranged our lives to
have it both ways; we can enjoy the pure act of writing code in sure
knowledge that the code we write has use. We produce things that
matter. We are modern craftspeople, building structures that make
up present-day reality, and no less than bricklayers or bridge
builders, we take justifiable pride in our accomplishments.
This all programmers share, from the most enthusiastic newbie
to the apparently jaded elder, whether working at the lightest weight
Internet startup or the most staid, long-entrenched enterprise. We
want to do our best work. We want our work to have meaning. We
want to have fun along the way.
And so it’s especially troubling when software goes awry. Bad
software impedes our purpose and interferes with our happiness.
Where once we felt productive, now we feel thwarted. Where once
fast, now slow. Where once peaceful, now frustrated.
This frustration occurs when it costs too much to get things
done. Our internal calculators are always running, comparing total
amount accomplished to overall effort expended. When the cost of
doing work exceeds its value, our efforts feel wasted. If
programming gives joy it is because it allows us to be useful, when it
becomes painful it is a sign that we believe we could, and should, be
doing more. Our pleasure follows in the footsteps of work.
This book is about designing object-oriented software. It is not
an academic tome, it is a programmer’s story about how to write
code. It teaches how to arrange software so as to be productive
today and to remain so next month and next year. It shows how to
write applications that can succeed in the present and still adapt to
the future. It allows you to raise your productivity and reduce your
costs for the entire lifetime of your applications.
This book believes in your desire to do good work and gives you
the tools you need to best be of use. It is completely practical and
as such is, at its core, a book about how to write code that brings
you joy.

Who Might Find This Book Useful?


This book assumes that you have at least tried to write object-
oriented software. It is not necessary that you feel you succeeded,
just that you made the attempt in any object-oriented (OO)
language. Chapter 1, “Object-Oriented Design,” contains a brief
overview of object-oriented programming (OOP), but its goal is to
define common terms, not to teach programming.
If you want to learn OO design (OOD) but have not yet done
any object-oriented programming, at least take a tutorial before
reading this book. OOD solves problems; suffering from those
problems is very nearly a prerequisite for comprehending these
solutions. Experienced programmers may be able to skip this step,
but most readers will be happier if they write some OO code before
starting this book.
This book uses Ruby to teach OOD but you do not need to
know Ruby to understand the concepts herein. There are many code
examples but all are quite straightforward. If you have programmed
in any OO language you will find Ruby easy to understand.
If you come from a statically typed OO language like Java or
C++ you have the background necessary to benefit from reading
this book. The fact that Ruby is dynamically typed simplifies the
syntax of the examples and distills the design ideas to their essence,
but every concept in this book can be directly translated to a
statically typed OO language.

How to Read This Book


Chapter 1 contains a general overview of the whys, whens, and
wherefores of OO design, followed by a brief overview of object-
oriented programming. This chapter stands alone. You can read it
first, last, or, frankly, skip it entirely, although if you are currently
stuck with an application that suffers from lack of design, you may
find it a comforting tale.
If you have experience writing object-oriented applications and
want to jump right in, you can safely start with Chapter 2. If you do
so and then stumble upon an unfamiliar term, come back and
browse the “Introduction to Object-Oriented Programming” section
of Chapter 1, which introduces and defines common OO terms used
throughout the book.
Chapters 2 through 9 progressively explain object-oriented
design. Chapter 2, “Designing Classes with a Single Responsibility,”
covers how to decide what belongs in a single class. Chapter 3,
“Managing Dependencies,” illustrates how objects get entangled with
one another and shows how to keep them apart. These two
chapters are focused on objects rather than messages.
In Chapter 4, “Creating Flexible Interfaces,” the emphasis
begins to shift away from object-centric toward message-centric
design. Chapter 4 is about defining interfaces and is concerned with
how objects talk to one another. Chapter 5, “Reducing Costs with
Duck Typing,” is about duck typing and introduces the idea that
objects of different classes may play common roles. Chapter 6,
“Acquiring Behavior through Inheritance,” teaches the techniques of
classical inheritance, which are then used in Chapter 7, “Sharing Role
Behavior with Modules,” to create duck typed roles. Chapter 8,
“Combining Objects with Composition,” explains the technique of
building objects via composition and provides guidelines for choosing
among composition, inheritance, and duck-typed role sharing.
Chapter 9, “Designing Cost-Effective Tests,” concentrates on the
design of tests, which it illustrates using code from earlier chapters
of the book.
Each of these chapters builds on the concepts of the last. They
are full of code and best read in order.

How to Use This Book


This book will mean different things to readers of different
backgrounds. Those already familiar with OOD will find things to
think about, possibly encounter some new points of view, and
probably disagree with a few of the suggestions. Because there is no
final authority on OOD, challenges to the principles (and to this
author) will improve the understanding of all. In the end, you must
be the arbiter of your own designs; it is up to you to question, to
experiment, and to choose.
While this book should be of interest to many levels of reader, it
is written with the particular goal of being accessible to novices. If
you are one of those novices, this part of the introduction is
especially for you. Know this: Object-oriented design is not black
magic. It is simply things you don’t yet know. The fact that you’ve
read this far indicates you care about design; this desire to learn is
the only prerequisite for benefiting from this book.
Chapters 2 through 9 explain OOD principles and provide very
explicit programming rules; these rules will mean different things to
novices than they mean to experts. If you are a novice, start out by
following these rules in blind faith if necessary. This early obedience
will stave off disaster until you can gain enough experience to make
your own decisions. By the time the rules start to chafe, you’ll have
enough experience to make up rules of your own, and your career
as a designer will have begun.
Software Versions Used in This Book
The examples in this book were written using Ruby 2.4 and tested
with Minitest 5.10.3. Source code for the examples can be found at
https://github.com/skmetz/poodr2.

Register your copy of Practical Object-Oriented Design, Second


Edition, on the InformIT site for convenient access to updates
and/or corrections as they become available. To start the
registration process, go to informit.com/register and log in or
create an account. Enter the product ISBN (9780134456478)
and click Submit. Look on the Registered Products tab for an
Access Bonus Content link next to this product, and follow that
link to access any available bonus materials. If you would like to
be notified of exclusive offers on new editions and updates,
please check the box to receive email from us.
Acknowledgments

It is a wonder this book exists; the fact that it does is due to the
efforts and encouragement of many people.
Throughout the long process of writing, Lori Evans and TJ
Stankus provided early feedback on every chapter. They live in
Durham, NC, and thus could not escape me, but this fact does
nothing to lessen my appreciation for their help.
Midway through the book, after it became impossible to deny
that its writing would take approximately twice as long as originally
estimated, Mike Dalessio and Gregory Brown read drafts and gave
invaluable feedback and support. Their encouragement and
enthusiasm kept the project alive during dark days.
A number of reviewers cast their keen eyes on the entire book,
acting as gracious stand-ins for you, the gentle reader. As the first
edition neared completion, Steve Klabnik, Desi McAdam, and Seth
Wax gave it careful readings. The second edition was meticulously
scoured by Will Sommers and Tory Peterschild. Their impressions
and suggestions caused changes that will benefit all who follow.
Late drafts were given careful, thorough readings by Katrina
Owen, Avdi Grimm, and Rebecca Wirfs-Brock, and the book is much
improved by their kind and thoughtful feedback. Before they pitched
in, Katrina, Avdi, and Rebecca were strangers to me; I am grateful
for their involvement and humbled by their generosity. If you find
this book useful, thank them when you next see them.
I am also grateful for the Gotham Ruby Group and for everyone
who expressed their appreciation for the design talks I gave at
GoRuCo 2009 and 2011. The folks at GoRuCo took a chance on an
unknown and gave me a forum in which to express these ideas; this
book started there. Ian McFarland and Brian Ford watched those
talks and their immediate and ongoing enthusiasm for this project
was both infectious and convincing.
The process of writing was greatly aided by Michael Thurston of
Pearson, who was like an ocean liner of calmness and organization
chugging through the chaotic sea of my opposing rogue writing
waves. You can, I expect, see the problem he faced. He insisted,
with endless patience and grace, that the writing be arranged in a
readable structure. I believe his efforts have paid off and hope you
will agree.
My thanks also to Debra Williams Cauley, my editor at
Pearson/Addison-Wesley, who overheard an ill-timed hallway rant in
2006 at the first Ruby on Rails conference in Chicago and launched
the campaign that eventually resulted in this book. Despite my best
efforts, she would not take no for an answer. She cleverly moved
from one argument to the next until she finally found the one that
convinced; this accurately reflects her persistence and dedication.
I owe a debt to the entire object-oriented design community. I
did not make up the ideas in this book, I am merely a translator, and
I stand on the shoulders of giants. It goes without saying that while
all credit for these ideas belongs to others—failures of translation are
mine alone.
And finally, this book owes its existence to my partner Amy
Germuth. Before this project started I could not imagine writing a
book; her view of the world as a place where people did such things
made doing so seem possible. The book in your hands is a tribute to
her boundless patience and endless support.
Thank you, each and every one.
About the Author

Sandi Metz, author of Practical Object-Oriented Design in Ruby and


99 Bottles of OOP, believes in simple code and straightforward
explanations. She prefers working software, practical solutions, and
lengthy bicycle trips (not necessarily in that order), and writes,
consults, speaks, and teaches about object-oriented design.
CHAPTER 1

Object-Oriented Design

The world is procedural. Time flows forward and events, one by one,
pass by. Your morning procedure may be to get up, brush your
teeth, make coffee, dress, and then get to work. These activities can
be modeled using procedural software; because you know the order
of events, you can write code to do each thing and then quite
deliberately string the things together, one after another.
The world is also object-oriented. The objects with which you
interact might include a spouse and a cat, or an old car and a pile of
bike parts in the garage, or your ticking heart and the exercise plan
you use to keep it healthy. Each of these objects comes equipped
with its own behavior, and while some of the interactions between
them might be predictable, it is entirely possible for your spouse to
unexpectedly step on the cat, causing a reaction that rapidly raises
everyone’s heart rate and gives you new appreciation for your
exercise regimen.
In a world of objects, new arrangements of behavior emerge
naturally. You don’t have to explicitly write code for the
spouse_steps_on_cat procedure; all you need is a spouse object
that takes steps and a cat object that does not like being stepped
on. Put these two objects into a room together and unanticipated
combinations of behavior will appear.
This book is about designing object-oriented software, and how
it views the world as a series of spontaneous interactions between
objects. Object-oriented design (OOD) requires that you shift from
thinking of the world as a collection of predefined procedures to
modeling the world as a series of messages that pass between
objects. Failures of OOD might look like failures of coding technique,
but they are actually failures of perspective. The first requirement for
learning how to do object-oriented design is to immerse yourself in
objects; once you acquire an object-oriented perspective, the rest
follows naturally.
This book guides you through the immersion process. This
chapter starts with a general discussion of OOD. It argues the case
for design and then proceeds to describe when to do it and how to
judge it. The chapter ends with a brief overview of object-oriented
programming that defines the terms used throughout the book.

1.1 In Praise of Design


Software gets built for a reason. The target application—whether a
trivial game or a program to guide radiation therapy—is the entire
point. If painful programming were the most cost-effective way to
produce working software, programmers would be morally obligated
to suffer stoically or to find other jobs.
Fortunately, you do not have to choose between pleasure and
productivity. The programming techniques that make code a joy to
write overlap with those that most efficiently produce software. The
techniques of object-oriented design solve both the moral and the
technical dilemmas of programming; following them produces cost-
effective software using code that is also a pleasure to work on.
1.1.1 The Problem Design Solves
Imagine writing a new application. Imagine that this application
comes equipped with a complete and correct set of requirements.
And if you will, imagine one more thing: once written, this
application need never change.
For this case, design does not matter. Like a circus performer
spinning plates in a world without friction or gravity, you could
program the application into motion and then stand back proudly
and watch it run forever. No matter how wobbly, the plates of code
would rotate on and on, teetering round and round but never quite
falling.
As long as nothing changed.
Unfortunately, something will change. It always does. The
customers didn’t know what they wanted, they didn’t say what they
meant. You didn’t understand their needs, you’ve learned how to do
something better. Even applications that are perfect in every way are
not stable. The application was a huge success, now everyone wants
more. Change is unavoidable. It is ubiquitous, omnipresent, and
inevitable.
Changing requirements are the programming equivalent of
friction and gravity. They introduce forces that apply sudden and
unexpected pressures that work against the best-laid plans. It is the
need for change that makes design matter.
Applications that are easy to change are a pleasure to write and
a joy to extend. They’re flexible and adaptable. Applications that
resist change are just the opposite; every change is expensive and
each makes the next cost more. Few difficult-to-change applications
are pleasant to work on. The worst of them gradually become
personal horror films where you star as a hapless programmer,
running madly from one spinning plate to the next, trying to stave
off the sound of crashing crockery.
1.1.2 Why Change Is Hard
Object-oriented applications are made up of parts that interact to
produce the behavior of the whole. The parts are objects;
interactions are embodied in the messages that pass between them.
Getting the right message to the correct target object requires that
the sender of the message know things about the receiver. This
knowledge creates dependencies between the two, and these
dependencies stand in the way of change.
Object-oriented design is about managing dependencies. It is a
set of coding techniques that arrange dependencies such that
objects can tolerate change. In the absence of design, unmanaged
dependencies wreak havoc because objects know too much about
one another. Changing one object forces change upon its
collaborators, which in turn forces change upon its collaborators, ad
infinitum. A seemingly insignificant enhancement can cause damage
that radiates outward in overlapping concentric circles, ultimately
leaving no code untouched.
When objects know too much, they have many expectations
about the world in which they reside. They’re picky, they need things
to be “just so.” These expectations constrain them. The objects
resist being reused in different contexts; they are painful to test and
susceptible to being duplicated.
In a small application, poor design is survivable. Even if
everything is connected to everything else, if you can hold it all in
your head at once, you can still improve the application. The
problem with poorly designed small applications is that if they are
successful, they grow up to be poorly designed big applications.
They gradually become tar pits in which you fear to tread lest you
sink without a trace. Changes that should be simple may cascade
around the application, breaking code everywhere and requiring
extensive rewriting. Tests are caught in the crossfire and begin to
feel like a hindrance rather than a help.
1.1.3 A Practical Definition of Design
Every application is a collection of code; the code’s arrangement is
the design. Two isolated programmers, even when they share
common ideas about design, can be relied upon to solve the same
problem by arranging code in different ways. Design is not an
assembly line where similarly trained workers construct identical
widgets; it’s a studio where like-minded artists sculpt custom
applications. Design is thus an art, the art of arranging code.
Part of the difficulty of design is that every problem has two
components. You must not only write code for the feature you plan
to deliver today, you must also create code that is amenable to being
changed later. For any period of time that extends past initial
delivery of the beta, the cost of change will eventually eclipse the
original cost of the application. Because design principles overlap
and every problem involves a shifting timeframe, design challenges
can have a bewildering number of possible solutions. Your job is one
of synthesis; you must combine an overall understanding of your
application’s requirements with knowledge of the costs and benefits
of design alternatives and then devise an arrangement of code that
is cost effective in the present and will continue to be so in the
future.
Taking the future into consideration might seem to introduce a
need for psychic abilities normally considered outside the realm of
programming. Not so. The future that design considers is not one in
which you anticipate unknown requirements and preemptively
choose one from among them to implement in the present.
Programmers are not psychics. Designs that anticipate specific future
requirements almost always end badly. Practical design does not
anticipate what will happen to your application; it merely accepts
that something will and that, in the present, you cannot know what.
It doesn’t guess the future; it preserves your options for
accommodating the future. It doesn’t choose; it leaves you room to
move.
The purpose of design is to allow you to do design later, and its
primary goal is to reduce the cost of change.
Another Random Scribd Document
with Unrelated Content
more elaborate relations, but form a comparatively permanent
source out of which the latter are ever springing. Of course they are
not independent of the larger society, but to some extent reflect its
spirit; as the German family and the German school bear somewhat
distinctly the print of German militarism. But this, after all, is like the
tide setting back into creeks, and does not commonly go very far.
Among the German, and still more among the Russian, peasantry
are found habits of free coöperation and discussion almost
uninfluenced by the character of the state; and it is a familiar and
well-supported view that the village commune, self-governing as
regards local affairs and habituated to discussion, is a very
widespread institution in settled communities, and the continuator of
a similar autonomy previously existing in the clan. “It is man who
makes monarchies and establishes republics, but the commune
seems to come directly from the hand of God.”[9]
In our own cities the crowded tenements and the general
economic and social confusion have sorely wounded the family and
the neighborhood, but it is remarkable, in view of these conditions,
what vitality they show; and there is nothing upon which the
conscience of the time is more determined than upon restoring them
to health.
These groups, then, are springs of life, not only for the individual
but for social institutions. They are only in part moulded by special
traditions, and, in larger degree, express a universal nature. The
religion or government of other civilizations may seem alien to us,
but the children or the family group wear the common life, and with
them we can always make ourselves at home.
By human nature, I suppose, we may understand those
sentiments and impulses that are human in being superior to those
of lower animals, and also in the sense that they belong to mankind
at large, and not to any particular race or time. It means, particularly,
sympathy and the innumerable sentiments into which sympathy
enters, such as love, resentment, ambition, vanity, hero-worship, and
the feeling of social right and wrong.[10]
Human nature in this sense is justly regarded as a comparatively
permanent element in society. Always and everywhere men seek
honor and dread ridicule, defer to public opinion, cherish their goods
and their children, and admire courage, generosity, and success. It is
always safe to assume that people are and have been human.
It is true, no doubt, that there are differences of race capacity, so
great that a large part of mankind are possibly incapable of any high
kind of social organization. But these differences, like those among
individuals of the same race, are subtle, depending upon some
obscure intellectual deficiency, some want of vigor, or slackness of
moral fibre, and do not involve unlikeness in the generic impulses of
human nature. In these all races are very much alike. The more
insight one gets into the life of savages, even those that are
reckoned the lowest, the more human, the more like ourselves, they
appear. Take for instance the natives of Central Australia, as
described by Spencer and Gillen,[11] tribes having no definite
government or worship and scarcely able to count to five. They are
generous to one another, emulous of virtue as they understand it,
kind to their children and to the aged, and by no means harsh to
women. Their faces as shown in the photographs are wholly human
and many of them attractive.
And when we come to a comparison between different stages in
the development of the same race, between ourselves, for instance,
and the Teutonic tribes of the time of Cæsar, the difference is neither
in human nature nor in capacity, but in organization, in the range and
complexity of relations, in the diverse expression of powers and
passions essentially much the same.
There is no better proof of this generic likeness of human nature
than in the ease and joy with which the modern man makes himself
at home in literature depicting the most remote and varied phases of
life—in Homer, in the Nibelung tales, in the Hebrew Scriptures, in the
legends of the American Indians, in stories of frontier life, of soldiers
and sailors, of criminals and tramps, and so on. The more
penetratingly any phase of human life is studied the more an
essential likeness to ourselves is revealed.
To return to primary groups: the view here maintained is that
human nature is not something existing separately in the individual,
but a group-nature or primary phase of society, a relatively simple
and general condition of the social mind. It is something more, on the
one hand, than the mere instinct that is born in us—though that
enters into it—and something less, on the other, than the more
elaborate development of ideas and sentiments that makes up
institutions. It is the nature which is developed and expressed in
those simple, face-to-face groups that are somewhat alike in all
societies; groups of the family, the playground, and the
neighborhood. In the essential similarity of these is to be found the
basis, in experience, for similar ideas and sentiments in the human
mind. In these, everywhere, human nature comes into existence.
Man does not have it at birth; he cannot acquire it except through
fellowship, and it decays in isolation.
If this view does not recommend itself to common-sense I do not
know that elaboration will be of much avail. It simply means the
application at this point of the idea that society and individuals are
inseparable phases of a common whole, so that wherever we find an
individual fact we may look for a social fact to go with it. If there is a
universal nature in persons there must be something universal in
association to correspond to it.
What else can human nature be than a trait of primary groups?
Surely not an attribute of the separate individual—supposing there
were any such thing—since its typical characteristics, such as
affection, ambition, vanity, and resentment, are inconceivable apart
from society. If it belongs, then, to man in association, what kind or
degree of association is required to develop it? Evidently nothing
elaborate, because elaborate phases of society are transient and
diverse, while human nature is comparatively stable and universal. In
short the family and neighborhood life is essential to its genesis and
nothing more is.
Here as everywhere in the study of society we must learn to see
mankind in psychical wholes, rather than in artificial separation. We
must see and feel the communal life of family and local groups as
immediate facts, not as combinations of something else. And
perhaps we shall do this best by recalling our own experience and
extending it through sympathetic observation. What, in our life, is the
family and the fellowship; what do we know of the we-feeling?
Thought of this kind may help us to get a concrete perception of that
primary group-nature of which everything social is the outgrowth.

FOOTNOTES:
[6] The History of Human Marriage.
[7] A History of Matrimonial Institutions.
[8] Newer Ideals of Peace, 177.
[9] De Tocqueville, Democracy in America, vol. i, chap. 5.
[10] These matters are expounded at some length in the
writer’s Human Nature and the Social Order.
[11] The Native Tribes of Central Australia. Compare also
Darwin’s views and examples given in chap. 7 of his Descent of
Man.
CHAPTER IV
PRIMARY IDEALS

Nature of Primary Idealism—The Ideal of a “We” or Moral


Unity—It Does not Exclude Self-Assertion—Ideals
Springing from Hostility—Loyalty, Truth, Service—
Kindness—Lawfulness—Freedom—The Doctrine of
Natural Right—Bearing of Primary Idealism upon
Education and Philanthropy.
Life in the primary groups gives rise to social ideals which, as they
spring from similar experiences, have much in common throughout
the human race. And these naturally become the motive and test of
social progress. Under all systems men strive, however blindly, to
realize objects suggested by the familiar experience of primary
association.
Where do we get our notions of love, freedom, justice, and the like
which we are ever applying to social institutions? Not from abstract
philosophy, surely, but from the actual life of simple and widespread
forms of society, like the family or the play-group. In these relations
mankind realizes itself, gratifies its primary needs, in a fairly
satisfactory manner, and from the experience forms standards of
what it is to expect from more elaborate association. Since groups of
this sort are never obliterated from human experience, but flourish
more or less under all kinds of institutions, they remain an enduring
criterion by which the latter are ultimately judged.
Of course these simpler relations are not uniform for all societies,
but vary considerably with race, with the general state of civilization,
and with the particular sort of institutions that may prevail. The
primary groups themselves are subject to improvement and decay,
and need to be watched and cherished with a very special care.
Neither is it claimed that, at the best, they realize ideal conditions;
only that they approach them more nearly than anything else in
general experience, and so form the practical basis on which higher
imaginations are built. They are not always pleasant or righteous, but
they almost always contain elements from which ideals of
pleasantness and righteousness may be formed.
The ideal that grows up in familiar association may be said to be a
part of human nature itself. In its most general form it is that of a
moral whole or community wherein individual minds are merged and
the higher capacities of the members find total and adequate
expression. And it grows up because familiar association fills our
minds with imaginations of the thought and feeling of other members
of the group, and of the group as a whole, so that, for many
purposes, we really make them a part of ourselves and identify our
self-feeling with them.
Children and savages do not formulate any such ideal, but they
have it nevertheless; they see it; they see themselves and their
fellows as an indivisible, though various, “we,” and they desire this
“we” to be harmonious, happy, and successful. How heartily one may
merge himself in the family and in the fellowships of youth is perhaps
within the experience of all of us; and we come to feel that the same
spirit should extend to our country, our race, our world. “All the
abuses which are the objects of reform ... are unconsciously
amended in the intercourse of friends.”[12]
A congenial family life is the immemorial type of moral unity, and
source of many of the terms—such as brotherhood, kindness, and
the like—which describe it. The members become merged by
intimate association into a whole wherein each age and sex
participates in its own way. Each lives in imaginative contact with the
minds of the others, and finds in them the dwelling-place of his social
self, of his affections, ambitions, resentments, and standards of right
and wrong. Without uniformity, there is yet unity, a free, pleasant,
wholesome, fruitful, common life.
As to the playground, Mr. Joseph Lee, in an excellent paper on
Play as a School of the Citizen, gives the following account of the
merging of the one in the whole that may be learned from sport. The
boy, he says,
“is deeply participating in a common purpose. The team and the plays
that it executes are present in a very vivid manner to his
consciousness. His conscious individuality is more thoroughly lost in
the sense of membership than perhaps it ever becomes in any other
way. So that the sheer experience of citizenship in its simplest and
essential form—of the sharing in a public consciousness, of having
the social organization present as a controlling ideal in your heart—is
very intense....
Along with the sense of the team as a mechanical instrument, and
unseparated from it in the boy’s mind, is the consciousness of it as the
embodiment of a common purpose. There is in team play a very
intimate experience of the ways in which such a purpose is built up
and made effective. You feel, though without analysis, the subtle ways
in which a single strong character breaks out the road ahead and
gives confidence to the rest to follow; how the creative power of one
ardent imagination, bravely sustained, makes possible the putting
through of the play as he conceives it. You feel to the marrow of your
bones how each loyal member contributes to the salvation of all the
others by holding the conception of the whole play so firmly in his
mind as to enable them to hold it, and to participate in his single-
minded determination to see it carried out. You have intimate
experience of the ways in which individual members contribute to the
team and of how the team, in turn, builds up their spiritual nature....
And the team is not only an extension of the player’s
consciousness; it is a part of his personality. His participation has
deepened from coöperation to membership. Not only is he now a part
of the team, but the team is a part of him.”[13]
Moral unity, as this illustration implies, admits and rewards
strenuous ambition; but this ambition must either be for the success
of the group, or at least not inconsistent with that. The fullest self-
realization will belong to the one who embraces in a passionate self-
feeling the aims of the fellowship, and spends his life in fighting for
their attainment.
The ideal of moral unity I take to be the mother, as it were, of all
social ideals.
It is, then, not my aim to depreciate the self-assertive passions. I
believe that they are fierce, inextinguishable, indispensable.
Competition and the survival of the fittest are as righteous as
kindness and coöperation, and not necessarily opposed to them: an
adequate view will embrace and harmonize these diverse aspects.
The point I wish particularly to bring out in this chapter is that the
normal self is moulded in primary groups to be a social self whose
ambitions are formed by the common thought of the group.
In their crudest form such passions as lust, greed, revenge, the
pride of power and the like are not, distinctively, human nature at all,
but animal nature, and so far as we rise into the spirit of family or
neighborhood association we control and subordinate them. They
are rendered human only so far as they are brought under the
discipline of sympathy, and refined into sentiments, such as love,
resentment, and ambition. And in so far as they are thus humanized
they become capable of useful function.
Take the greed of gain, for example, the ancient sin of avarice, the
old wolf, as Dante says, that gets more prey than all the other
beasts.[14] The desire of possession is in itself a good thing, a phase
of self-realization and a cause of social improvement. It is immoral or
greedy only when it is without adequate control from sympathy, when
the self realized is a narrow self. In that case it is a vice of isolation
or weak social consciousness, and indicates a state of mind
intermediate between the brutal and the fully human or moral, when
desire is directed toward social objects—wealth or power—but is not
social in its attitude toward others who desire the same objects.
Intimate association has the power to allay greed. One will hardly be
greedy as against his family or close friends, though very decent
people will be so as against almost any one else. Every one must
have noticed that after frank association, even of a transient
character, with another person, one usually has a sense of kindred
with him which makes one ashamed to act greedily at his expense.
Those who dwell preponderantly upon the selfish aspect of human
nature and flout as sentimentalism the “altruistic” conception of it,
make their chief error in failing to see that our self itself is altruistic,
that the object of our higher greed is some desired place in the
minds of other men, and that through this it is possible to enlist
ordinary human nature in the service of ideal aims. The improvement
of society does not call for any essential change in human nature,
but, chiefly, for a larger and higher application of its familiar
impulses.
I know, also, that the most truculent behavior may be exalted into
an ideal, like the ferocity of Samuel, when he hewed Agag to pieces
before the Lord,[15] or of the orthodox Christian of a former age in
the destruction of heretics. In general there is always a morality of
opposition, springing from the need of the sympathetic group to
assert itself in the struggle for existence. Even at the present day this
more or less idealizes destructiveness and deceit in the conflicts of
war, if not of commerce.
But such precepts are secondary, not ideals in the same primary
and enduring sense that loyalty and kindness are. They shine by
reflected light, and get their force mainly from the belief that they
express the requirements of the “we” group in combating its
enemies. Flourishing at certain stages of development because they
are requisite under the prevailing conditions of destructive conflict,
they are slowly abandoned or transformed when these conditions
change. Mankind at large has no love of them for their own sake,
though individuals, classes, or even nations may acquire them as a
habit. With the advance of civilization conflict itself is brought more
and more under the control of those principles that prevail in primary
groups, and, so far as this is the case, conduct which violates such
principles ceases to have any ideal value.
To break up the ideal of a moral whole into particular ideals is an
artificial process which every thinker would probably carry out in his
own way. Perhaps, however, the most salient principles are loyalty,
lawfulness, and freedom.
In so far as one identifies himself with a whole, loyalty to that
whole is loyalty to himself; it is self-realization, something in which
one cannot fail without losing self-respect. Moreover this is a larger
self, leading out into a wider and richer life, and appealing, therefore,
to enthusiasm and the need of quickening ideals. One is never more
human, and as a rule never happier, than when he is sacrificing his
narrow and merely private interest to the higher call of the congenial
group. And without doubt the natural genesis of this sentiment is in
the intimacy of face-to-face coöperation. It is rather the rule than the
exception in the family, and grows up among children and youth so
fast as they learn to think and act to common ends. The team feeling
described above illustrates it as well as anything.
Among the ideals inseparable from loyalty are those of truth,
service, and kindness, always conceived as due to the intimate
group rather than to the world at large.
Truth or good faith toward other members of a fellowship is, so far
as I know, a universal human ideal. It does not involve any abstract
love of veracity, and is quite consistent with deception toward the
outside world, being essentially “truth of intercourse” or fair dealing
among intimates. There are few, even among those reckoned
lawless, who will not keep faith with one who has the gift of getting
near to them in spirit and making them feel that he is one of
themselves. Thus Judge Lindsey of Denver has worked a revolution
among the neglected boys of his city, by no other method than that
of entering into the same moral whole, becoming part of a “we” with
them. He awakens their sense of honor, trusts it, and is almost never
disappointed. When he wishes to send a boy to the reform school
the latter promises to repair to the institution at a given time and
invariably does so. Among tramps a similar sentiment prevails. “It will
be found,” said a young man who had spent the summer among
vagrants, “that if they are treated square they will do the same.”
The ideal of service likewise goes with the sense of unity. If there
is a vital whole the right aim of individual activity can be no other
than to serve that whole. And this is not so much a theory as a
feeling that will exist wherever the whole is felt. It is a poor sort of an
individual that does not feel the need to devote himself to the larger
purposes of the group. In our society many feel this need in youth
and express it on the playground who never succeed in realizing it
among the less intimate relations of business or professional life.
All mankind acknowledges kindness as the law of right intercourse
within a social group. By communion minds are fused into a
sympathetic whole, each part of which tends to share the life of all
the rest, so that kindness is a common joy, and harshness a
common pain. It is the simplest, most attractive, and most diffused of
human ideals. The golden rule springs directly from human nature.
Accordingly this ideal has been bound up with association in all
past times and among all peoples: it was a matter of course that
when men acted together in war, industry, devotion, sport, or what
not, they formed a brotherhood or friendship. It is perhaps only in
modern days, along with the great and sudden differentiation of
activities, that feeling has failed to keep up, and the idea of
coöperation without friendship has become familiar.
Mr. Westermarck, than whom there is no better authority on a
question of this sort, has filled several chapters of his work on the
Origin and Development of Moral Ideas with evidence of the
universality of kindness and the kindly ideal. After showing at length
that uncivilized people recognize the duty of kindness and support
from mother to child, father to child, child to parent, and among
brethren and kinsmen, he goes on to say:[16] “But the duty of helping
the needy and protecting those in danger goes beyond the limits of
the family and the gens. Uncivilized peoples are, as a rule, described
as kind toward members of their own community or tribe. Between
themselves charity is enjoined as a duty and generosity is praised as
a virtue. Indeed their customs regarding mutual aid are often much
more stringent than our own. And this applies even to the lowest
savages.”
Beginning with the Australians, he quotes the statement of
Spencer and Gillen that their treatment of one another “is marked on
the whole by considerable kindness, that is, of course, in the case of
members of friendly groups, with every now and then the
perpetration of acts of cruelty.” Concerning the North American
Indians he cites many writers. Catlin says “to their friends there are
no people on earth that are more kind.” Adair that “they are very kind
and liberal to every one of their own tribe, even to the last morsel of
food they enjoy”; also that Nature’s school “teaches them the plain,
easy rule, Do to others as you would be done by.” Morgan reports
that “among the Iroquois kindness to the orphan, hospitality to all,
and a common brotherhood were among the doctrines held up for
acceptance by their religious instructors.” An Iroquois “would
surrender his dinner to feed the hungry, vacate his bed to refresh the
weary, and give up his apparel to clothe the naked.”
And so Westermarck goes on, in the exhaustive way familiar to
readers of his works, to show that like sentiments prevail the world
over. Kropotkin has collected similar evidence in his Mutual Aid a
Factor in Civilization. The popular notion of savages as lacking in the
gentler feelings is an error springing from the external, usually
hostile, nature of our contact with them. Indeed, a state of things,
such as is found in our own cities, where want and plenty exist side
by side without the latter feeling any compulsion to relieve the
former, is shocking and incomprehensible to many savages.
Ordinarily the ideal of kindness, in savage and civilized societies
alike, applies only to those within the sympathetic group; the main
difference between civilization and savagery, in this regard, being
that under the former the group tends to enlarge. One reason for the
restriction is that kindness is aroused by sympathy, and can have
little life except as our imaginations are opened to the lives of others
and they are made part of ourselves. Even the Christian church, as
history shows, has for the most part inculcated kindness only to
those within its own pale, or within a particular sect; and the modern
ideal of a kindness embracing all humanity (modern at least so far as
western nations are concerned) is connected with a growing
understanding of the unity of the race.
Every intimate group, like every individual, experiences conflicting
impulses within itself, and as the individual feels the need of definite
principles to shape his conduct and give him peace, so the group
needs law or rule for the same purpose. It is not merely that the
over-strong or the insubordinate must be restrained, but that all alike
may have some definite criterion of what the good member ought to
do. It is a mere fact of psychology that where a social whole exists it
may be as painful to do wrong as to suffer it—because one’s own
spirit is divided—and the common need is for harmony through a
law, framed in the total interest, which every one can and must obey.
This need of rules to align differentiated impulse with the good of
the whole is nowhere more apparent than on the playground. Miss
Buck, the author of an instructive work on Boys’ Self-Governing
Clubs, suggests that the elementary form of equity is “taking turns,”
as at swings and the like; and any one who has shared in a boys’
camp will recall the constant demand, by the boys themselves, for
rules of this nature. There must be a fair distribution of privileges as
to boats, games, and so on, and an equal distribution of food. And
we learn from Robert Woods that gangs of boys on the streets of
cities generally have a “judge” to whom all disputes are referred if no
agreement is otherwise reached.[17]
No doubt every one remembers how the idea of justice is
developed in children’s games. There is always something to be
done, in which various parts are to be taken, success depending
upon their efficient distribution. All see this and draw from experience
the idea that there is a higher principle that ought to control the
undisciplined ambition of individuals. “Rough games,” says Miss
Buck, “in many respects present in miniature the conditions of a
society where an ideal state of justice, freedom and equality
prevails.”[18] Mr. Joseph Lee, in the paper quoted above, expounds
the matter at more length and with much insight.
You may be very intent to beat the other man in the race, but after
experience of many contests the fair promise of whose morning has
been clouded over by the long and many-worded dispute terminating
in a general row, with indecisive and unsatisfying result, you begin
dimly to perceive that you and the other fellows and the rest of the
crowd, for the very reason that you are contestants and prospective
contestants, have interests in common—interests in the establishment
and maintenance of those necessary rules and regulations without
which satisfactory contests cannot be carried on.... The child’s need of
conflict is from a desire not to exterminate his competitor, but to
overcome him and to have his own superiority acknowledged. The
boy desires to be somebody; but being somebody is to him a social
achievement. And though there is temptation to pervert justice, to try
to get the decision when you have not really furnished the proof, there
is also a motive against such procedure. The person whom you really
and finally want to convince is yourself. Your deepest desire is to beat
the other boy, not merely to seem to beat him. By playing unfairly and
forcing decisions in your own favor, you may possibly cheat the
others, but you cannot cheat yourself.
But the decisions in most of the disputes have behind them the
further, more obviously social, motive of carrying on a successful
game. The sense of common interest has been stretched so as to
take the competitive impulse itself into camp, domesticate it, and
make it a part of the social system. The acutely realized fact that a
society of chronic kickers can never play a game or anything else,
comes to be seen against the background of a possible orderly
arrangement of which one has had occasional experience, and with
which one has come at last to sympathize; there comes to be to some
extent an identification of one’s own interests and purposes with the
interests and purposes of the whole. Certainly the decisions of the
group as to whether Jimmy was out at first, as to who came out last,
and whether Mary Ann was really caught, are felt as community and
not as individual decisions.[19]
No doubt American boys have more of the spirit and practice of
this sort of organization than those of any other country, except
possibly England: they have the constant spectacle of self-
government among their elders, and also, perhaps, some advantage
in natural aptitude to help them on. But it is doubtful if there is any
great difference among the white peoples in the latter regard.
American children of German and Irish descent are not inferior to the
Anglo-Saxons, and among the newer immigrants the Jewish
children, at least, show a marked aptitude for organization. The
question might profitably be investigated in our great cities.
Of course the ideals derived from juvenile experience are carried
over into the wider life, and men always find it easy to conceive
righteousness in terms of fair play. “The Social Question,” says a
penetrative writer, “is forever an attack upon what, in some form, is
thought to be unfair privilege.”[20]
The law or rule that human nature demands has a democratic
principle latent in it, because it must be one congenial to general
sentiment. Explicit democracy, however—deciding by popular vote
and the like—is not primary and general like the need of law, but is
rather a mechanism for deciding what the rule is to be, and no more
natural than the appeal to authority. Indeed, there seems to be,
among children as among primitive peoples, a certain reluctance to
ascribe laws to the mere human choice of themselves and their
fellows. They wish to assign them to a higher source and to think of
them as having an unquestionable sanction. So far as my own
observation goes, even American boys prefer to receive rules from
tradition or from their elders, when they can. Nothing is easier than
for a parent, or mentor of any kind, to be a lawgiver to children, if
only he has their confidence, and if the laws themselves prove
workable. But the test of law is social and popular; it must suit the
general mind. If, for instance, a man takes a group of boys camping,
and has their confidence, they will gladly receive rules from him,
expecting, of course, that they will be good rules. But if they prove to
be unreasonable and troublesome, they will soon cease to work.
Freedom is that phase of the social ideal which emphasizes
individuality. The whole to which we belong is made up of diverse
energies which enkindle one another by friction; and its vigor
requires that these have play. Thus the fierce impulses of ambition
and pride may be as organic as anything else—provided they are
sufficiently humanized as to their objects—and are to be interfered
with only when they become destructive or oppressive. Moreover, we
must not be required to prove to others the beneficence of our
peculiarity, but should be allowed, if we wish, to “write whim on the
lintels of the door-post.” Our desires and purposes, though social in
their ultimate nature, are apt to be unacceptable on first appearance,
and the more so in proportion to their value. Thus we feel a need to
be let alone, and sympathize with a similar need in others.
This is so familiar a principle, especially among English and
Americans, to whose temperament and traditions it is peculiarly
congenial, that I need not discuss it at length. It is a phase of
idealism that comes most vividly to consciousness when formal and
antiquated systems of control need to be broken up, as in the
eighteenth century. It then represented the appeal to human nature
as against outworn mechanism. Our whole social and political
philosophy still echoes that conflict.
The bearing of this view of human nature may perhaps be made
clearer by considering its relation to the familiar but now somewhat
discredited doctrine of Natural Right. This is traced from the
speculations of Greek philosophers down through Roman
jurisprudence to Hobbes, Locke, Rousseau, and others, who gave it
its modern forms and through whose works it became a factor in
modern history. It was familiar to our forefathers and is set forth in
the Declaration of Independence. According to it society is made up,
primarily, of free individuals, who must be held to create government
and other institutions by a sort of implied contract, yielding up a part
of their natural right in order to enjoy the benefits of organization. But
if the organization does not confer these benefits, then, as most
writers held, it is wrong and void, and the individuals may properly
reclaim their natural freedom.
Now in form this doctrine is wholly at variance with evolutionary
thought. To the latter, society is an organic growth; there is no
individual apart from society, no freedom apart from organization, no
social contract of the sort taught by these philosophers. In its
practical applications, however, the teaching of natural right is not so
absurd and obsolete as is sometimes imagined. If it is true that
human nature is developed in primary groups which are everywhere
much the same, and that there also springs from these a common
idealism which institutions strive to express, we have a ground for
somewhat the same conclusions as come from the theory of a
natural freedom modified by contract. Natural freedom would
correspond roughly to the ideals generated and partly realized in
primary association, the social contract to the limitations these ideals
encounter in seeking a larger expression.
Indeed, is it not true that the natural rights of this philosophy—the
right to personal freedom, the right to labor, the right to property, the
right to open competition—are ideals which in reality sprang then as
they do now largely from what the philosophers knew of the activities
of men in small, face-to-face groups?
The reluctance to give up ideals like those of the Declaration of
Independence, without something equally simple and human to take
their place, is healthy and need not look far for theoretical
justification.
The idea of the germinal character of primary association is one
that is fast making its way in education and philanthropy. As we learn
that man is altogether social and never seen truly except in
connection with his fellows, we fix our attention more and more on
group conditions as the source, for better or worse, of personal
character, and come to feel that we must work on the individual
through the web of relations in which he actually lives.
The school, for instance, must form a whole with the rest of life,
using the ideas generated by the latter as the starting-point of its
training. The public opinion and traditions of the scholars must be
respected and made an ally of discipline. Children’s associations
should be fostered and good objects suggested for their activity.
In philanthropy it is essential that the unity of the family be
regarded and its natural bonds not weakened for the sake of
transient benefit to the individual. Children, especially, must be
protected from the destructive kindness which inculcates
irresponsibility in the parent. In general the heart of reform is in
control of the conditions which act upon the family and
neighborhood. When the housing, for example, is of such a
character as to make a healthy home life impossible, the boys and
girls are driven to the streets, the men into saloons, and thus society
is diseased at its source.
Without healthy play, especially group play, human nature cannot
rightly develop, and to preserve this, in the midst of the crowding and
aggressive commercialism of our cities, is coming to be seen as a
special need of the time. Democracy, it is now held, must recognize
as one of its essential functions the provision of ample spaces and
apparatus for this purpose, with enough judicious supervision to
ensure the ascendency of good play traditions. And with this must go
the suppression of child labor and other inhumane conditions.
Fruitful attention is being given to boys’ fellowships or “gangs.” It
appears—as any one who recalls his own boyhood might have
anticipated—that nearly all the juvenile population belong to such
fellowships, and put an ardent, though often misdirected, idealism
into them. “Almost every boy in the tenement-house quarters of the
district,” says Robert A. Woods, speaking of Boston, “is a member of
a gang. The boy who does not belong is not only the exception but
the very rare exception.”[21] In crowded neighborhoods, where there
are no playgrounds and street sports are unlawful, the human nature
of these gangs must take a semi-criminal direction; but with better
opportunities and guidance it turns quite as naturally to wholesome
sport and social service. Accordingly social settlements and similar
agencies are converting gangs into clubs, with the best results; and
there is also coming to be a regular organization of voluntary clubs in
affiliation with the public schools.
It is much the same in the country. In every village and township in
the land, I suppose, there are one or more groups of predatory boys
and hoydenish girls whose mischief is only the result of ill-directed
energy. If each of these could receive a little sympathetic attention
from kindred but wiser spirits, at least half of the crime and vice of
the next generation would almost certainly be done away with.

FOOTNOTES:
[12] Thoreau, A Week on the Concord and Merrimack Rivers,
283.
[13] Charities and the Commons, Aug. 3, 1907.
[14]
Antica lupa,
Che più che tutte l’altre bestie hai preda.
Purgatorio, XX, 10.
[15] 1 Samuel, 15:33.
[16] Vol. i, 540 ff.
[17] The City Wilderness, 116.
[18] Boys’ Self-Governing Clubs, 4, 5.
[19] Charities and the Commons, Aug. 3. 1907, abridged.
[20] John Graham Brooks, The Social Unrest, 135.
[21] The City Wilderness, 113.
CHAPTER V
THE EXTENSION OF PRIMARY IDEALS

Primary Ideals Underlie Democracy and Christianity—Why


They are not Achieved on a Larger Scale—What They
Require from Personality—From Social Mechanism—The
Principle of Compensation.
It will be found that those systems of larger idealism which are
most human and so of most enduring value, are based upon the
ideals of primary groups. Take, for instance, the two systems that
have most vitality at the present time—democracy and Christianity.
The aspirations of ideal democracy—including, of course,
socialism, and whatever else may go by a special name—are those
naturally springing from the playground or the local community;
embracing equal opportunity, fair play, the loyal service of all in the
common good, free discussion, and kindness to the weak. These are
renewed every day in the hearts of the people because they spring
from and are corroborated by familiar and homely experience.
Moreover, modern democracy as a historical current is apparently
traceable back to the village community life of the Teutonic tribes of
northern Europe, from which it descends through English
constitutional liberty and the American and French revolutions to its
broad and deep channels of the nineteenth and twentieth centuries.
And Christianity, as a social system, is based upon the family, its
ideals being traceable to the domestic circle of a Judaean carpenter.
God is a kind father; men and women are brothers and sisters; we
are all members one of another, doing as we would be done by and
referring all things to the rule of love. In so far as the church has
departed from these principles it has proved transient; these endure
because they are human.
But why is it that human nature is not more successful in achieving
these primary aims? They appear to be simple and reasonable, and
one asks why they are so little realized, why we are not, in fact, a
moral whole, a happy family.
It is not because we do not wish it. There can be no doubt, I
should say, that, leaving aside a comparatively few abnormal
individuals, whose influence is small, men in general have a natural
allegiance to the community ideal, and would gladly see it carried out
on a large as well as a small scale. And nearly all imaginative and
aspiring persons view it with enthusiasm, and would devote
themselves to it with some ardor and sacrifice if they saw clearly how
they could do so with effect. It is easy to imagine types of pure
malignity in people of whom we have little knowledge, but who ever
came to know any one intimately without finding that he had
somewhere in him the impulses of a man and a brother?
The failure to realize these impulses in practice is, of course, due
in part to moral weakness of a personal character, to the fact that our
higher nature has but an imperfect and transient mastery of our
lower, so that we never live up to our ideals. But going beyond this
and looking at the matter from the standpoint of the larger mind, the
cause of failure is seen to be the difficulty of organization. Even if our
intentions were always good, we should not succeed, because, to
make good intentions effective, they must be extended into a
system. In attempting to do this our constructive power is used up
and our ideals confused and discouraged. We are even led to create
a kind of institutions which, though good in certain aspects, may
brutalize or ossify the individual, so that primary idealism in him is
almost obliterated. The creation of a moral order on an ever-growing
scale is the great historical task of mankind, and the magnitude of it
explains all shortcomings.
From personality the building of a moral order requires not only
good impulses but character and capacity. The ideal must be worked
out with steadfastness, self-control, and intelligence. Even families
and fellowships, though usually on a higher level than more
elaborate structures, often break down, and commonly from lack of
character in their members. But if it is insufficient here, how much
less will it suffice for a righteous state. Our new order of life, with its
great extension of structure and its principle of freedom, is an ever
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like