Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (16 votes)
599 views

Download ebooks file Learning JavaScript Design Patterns A JavaScript and React Developer s Guide 2nd Edition Adnan Osmani all chapters

Patterns

Uploaded by

azriendenule
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (16 votes)
599 views

Download ebooks file Learning JavaScript Design Patterns A JavaScript and React Developer s Guide 2nd Edition Adnan Osmani all chapters

Patterns

Uploaded by

azriendenule
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Download the full version of the ebook at ebookname.

com

Learning JavaScript Design Patterns A JavaScript


and React Developer s Guide 2nd Edition Adnan
Osmani

https://ebookname.com/product/learning-javascript-design-
patterns-a-javascript-and-react-developer-s-guide-2nd-
edition-adnan-osmani/

OR CLICK BUTTON

DOWNLOAD EBOOK

Download more ebook instantly today at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Learning JavaScript Design Patterns Addy Osmani

https://ebookname.com/product/learning-javascript-design-patterns-
addy-osmani/

ebookname.com

Pro Javascript Design Patterns 1st Edition Ross Harmes

https://ebookname.com/product/pro-javascript-design-patterns-1st-
edition-ross-harmes/

ebookname.com

Learning JavaScript 2nd Edition Shelley Powers

https://ebookname.com/product/learning-javascript-2nd-edition-shelley-
powers/

ebookname.com

Fundamentals of Revision Hip Arthroplasty Diagnosis


Evaluation and Treatment 1st Edition David Jacofsky

https://ebookname.com/product/fundamentals-of-revision-hip-
arthroplasty-diagnosis-evaluation-and-treatment-1st-edition-david-
jacofsky/
ebookname.com
Limited Language Rewriting Design Responding to a Feedback
Culture 1st Edition Colin Davies

https://ebookname.com/product/limited-language-rewriting-design-
responding-to-a-feedback-culture-1st-edition-colin-davies/

ebookname.com

Human Embryogenesis Methods and Protocols 1st Edition


Cathy Vaillancourt

https://ebookname.com/product/human-embryogenesis-methods-and-
protocols-1st-edition-cathy-vaillancourt/

ebookname.com

Speech Out of Doors Preserving First Amendment Liberties


in Public Places 1st Edition Timothy Zick

https://ebookname.com/product/speech-out-of-doors-preserving-first-
amendment-liberties-in-public-places-1st-edition-timothy-zick/

ebookname.com

Pygmalion Webster s Spanish Thesaurus Edition George


Bernard Shaw

https://ebookname.com/product/pygmalion-webster-s-spanish-thesaurus-
edition-george-bernard-shaw/

ebookname.com

GACE English to Speakers of Other Languages 119 120 XAM


GACE First Edition, New Edition Sharon Wynne

https://ebookname.com/product/gace-english-to-speakers-of-other-
languages-119-120-xam-gace-first-edition-new-edition-sharon-wynne/

ebookname.com
eBusiness Essentials 2nd Edition Mark Norris

https://ebookname.com/product/ebusiness-essentials-2nd-edition-mark-
norris/

ebookname.com
Se dit
E
co ion
nd
Learning
JavaScript
Design Patterns
A JavaScript and
React Developer's Guide

Addy Osmani
Learning JavaScript Design Patterns
Do you want to write beautiful, structured, and maintainable
JavaScript by applying modern design patterns to the “Addy’s book is a
language? Do you want clean, efficient, manageable pragmatic approach to
code? Want to stay up-to-date with the latest best fundamental concepts
practices? If so, the updated second edition of Learning that are useful across
JavaScript Design Patterns is the ideal place to start. myriad uses. JavaScript
Design Patterns are
Author Addy Osmani shows you how to apply modern intrinsic to developers
design patterns—­including modules, mixins, observers, applying systems thinking
and mediators—to JavaScript and React. You’ll learn about to their own work. Any
performance and rendering patterns such as server-side developer reading this
rendering and Islands architecture. You’ll also learn how book will see incredible
architectural patterns like MVC, MVP, and MVVM are useful returns on the time
from the perspective of a modern web application developer. investment reading it.”
—Sarah Drasner
This book explores: Director of Engineering at Google
• Architectural patterns for structuring your components
“Addy Osmani strikes
and apps
again, and he has
• More than 20 design patterns in JavaScript and delivered a much
React, applicable for developers at any level appreciated update
• Different pattern categories including to his already classic
creational, structural, and behavioral
book on design patterns
in JavaScript.”
• Essential performance patterns including —Stoyan Stefanov
dynamic imports and code-splitting WebPageTest.org engineer and
author of JavaScript Patterns
• Rendering patterns such as server-side rendering,
hydration, Islands architecture, and more
Additionally, you’ll explore modern JavaScript syntax like Addy Osmani is an engineering
JavaScript modules, React patterns like Hooks, higher-order leader for Google, where he leads
the Chrome developer experience
components (HOCs), and more, to stay ahead in the teams, helping to keep the web
ever-evolving world of web development. fast and delightful to build upon.

WEB DEVELOPMENT Twitter: @oreillymedia


linkedin.com/company/oreilly-media
US $65.99 CAN $82.99 youtube.com/oreillymedia
ISBN: 978-1-098-13987-2
SECOND EDITION

Learning JavaScript
Design Patterns
A JavaScript and React Developer’s Guide

Addy Osmani

Beijing Boston Farnham Sebastopol Tokyo


Learning JavaScript Design Patterns
by Addy Osmani
Copyright © 2023 Adnan Osmani. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://oreilly.com). For more information, contact our corporate/institu‐
tional sales department: 800-998-9938 or corporate@oreilly.com.

Acquisitions Editor: Amanda Quinn Indexer: Sue Klefstad


Development Editor: Michele Cronin Interior Designer: David Futato
Production Editor: Clare Laylock Cover Designer: Karen Montgomery
Copyeditor: Stephanie English Illustrator: Kate Dullea
Proofreader: Rising Sun Technologies

August 2012: First Edition


April 2023: Second Edition

Revision History for the Second Edition


2023-04-28: First Release

See http://oreilly.com/catalog/errata.csp?isbn=9781098139872 for release details.

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning JavaScript Design Patterns,
the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author and do not represent the publisher’s views.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.

978-1-098-13987-2
[LSI]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

1. Introduction to Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


History of Design Patterns 2
What Is a Pattern? 2
An Everyday Use Case for Design Patterns 4
Summary 5

2. “Pattern”-ity Testing, Proto-Patterns, and the Rule of Three. . . . . . . . . . . . . . . . . . . . . . . 7


What Are Proto-Patterns? 7
The “Pattern” Tests 8
Rule of Three 9
Summary 9

3. Structuring and Writing Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11


The Structure of a Design Pattern 11
Well-Written Patterns 12
Writing a Pattern 13
Summary 14

4. Anti-Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
What Are Anti-Patterns? 15
Anti-Patterns in JavaScript 16
Summary 17

5. Modern JavaScript Syntax and Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19


The Importance of Decoupling Applications 19
Modules with Imports and Exports 20
Module Objects 22

iii
Modules Loaded from Remote Sources 23
Static Imports 23
Dynamic Imports 23
Import on Interaction 24
Import on Visibility 24
Modules for the Server 24
Advantages of Using Modules 25
Classes with Constructors, Getters, and Setters 26
Classes in JavaScript Frameworks 28
Summary 29
Related Reading 29

6. Categories of Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31


Background 31
Creational Design Patterns 32
Structural Design Patterns 32
Behavioral Design Patterns 32
Design Pattern Classes 32
Summary 34

7. JavaScript Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


Creational Patterns 35
The Constructor Pattern 36
Object Creation 36
Basic Constructors 38
Constructors with Prototypes 39
The Module Pattern 40
Object Literals 40
The Module Pattern 42
Module Pattern Variations 46
Modern Module Pattern with WeakMap 48
Modules with Modern Libraries 50
The Revealing Module Pattern 51
Advantages 53
Disadvantages 53
The Singleton Pattern 53
State Management in React 57
The Prototype Pattern 58
The Factory Pattern 61
When to Use the Factory Pattern 64
When Not to Use the Factory Pattern 64
Abstract Factories 64
Structural Patterns 65

iv | Table of Contents
The Facade Pattern 66
The Mixin Pattern 68
Subclassing 68
Mixins 69
Advantages and Disadvantages 72
The Decorator Pattern 73
Pseudoclassical Decorators 76
Interfaces 77
Abstract Decorators 78
Advantages and Disadvantages 81
Flyweight 82
Using Flyweights 83
Flyweights and Sharing Data 83
Implementing Classical Flyweights 83
Converting Code to Use the Flyweight Pattern 86
A Basic Factory 89
Managing the Extrinsic States 89
The Flyweight Pattern and the DOM 91
Example: Centralized Event Handling 91
Behavioral Patterns 93
The Observer Pattern 93
Differences Between the Observer and Publish/Subscribe Pattern 97
Advantages 100
Disadvantages 100
Publish/Subscribe Implementations 100
The Mediator Pattern 110
A Simple Mediator 111
Similarities and Differences 112
Event Aggregator Use 114
Mediator Use 114
Event Aggregator (Pub/Sub) and Mediator Together 115
Mediator/Middleware in Modern JavaScript 116
Mediator Versus Facade 117
The Command Pattern 117
Summary 119

8. JavaScript MV* Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121


MVC 121
Smalltalk-80 MVC 122
MVC for JavaScript Developers 122
Models 123
Views 124
Templating 126

Table of Contents | v
Controllers 128
What Does MVC Give Us? 128
Smalltalk-80 MVC in JavaScript 128
Summary of MVC 129
MVP 129
Models, Views, and Presenters 130
MVP or MVC? 131
MVVM 132
History 132
Model 133
View 133
ViewModel 134
Recap: The View and the ViewModel 134
ViewModel Versus Model 134
Pros and Cons 135
Advantages 135
Disadvantages 135
MVC Versus MVP Versus MVVM 135
Modern MV* Patterns 136
MV* and React.js 136
Summary 137

9. Asynchronous Programming Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139


Asynchronous Programming 139
Background 141
Promise Patterns 142
Promise Chaining 143
Promise Error Handling 144
Promise Parallelism 144
Promise Sequential Execution 144
Promise Memoization 144
Promise Pipeline 145
Promise Retry 146
Promise Decorator 146
Promise Race 147
async/await Patterns 147
async Function Composition 147
async Iteration 148
async Error Handling 148
async Parallelism 148
async Sequential Execution 149
async Memoization 149
async Event Handling 149

vi | Table of Contents
async/await Pipeline 150
async Retry 150
async/await Decorator 150
Additional Practical Examples 151
Making an HTTP Request 151
Reading a File from the Filesystem 151
Writing to a File on the Filesystem 151
Executing Multiple async Operations 152
Executing Multiple async Operations in Sequence 152
Caching the Result of an async Operation 152
Handling Events with async/await 153
Retrying an async Operation on Failure 153
Creating an async/await Decorator 153
Summary 154

10. Modular JavaScript Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155


A Note on Script Loaders 155
AMD 156
Getting Started with Modules 156
AMD Modules with jQuery 160
AMD Conclusions 163
CommonJS 163
Getting Started 164
Consuming Multiple Dependencies 165
CommonJS in Node.js 166
Is CommonJS Suitable for the Browser? 166
Related Reading for CommonJS 167
AMD and CommonJS: Competing, but Equally Valid Standards 167
UMD: AMD and CommonJS-Compatible Modules for Plug-ins 168
Summary 173

11. Namespacing Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175


Namespacing Fundamentals 175
Single Global Variables 176
Prefix Namespacing 176
Object Literal Notation 177
Nested Namespacing 180
Immediately Invoked Function Expressions 181
Namespace Injection 184
Advanced Namespacing Patterns 186
Automating Nested Namespacing 186
Dependency Declaration Pattern 188
Deep Object Extension 189

Table of Contents | vii


Recommendation 191
Summary 192

12. React.js Design Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193


An Introduction to React 193
Terminology Used 194
Basic Concepts 194
Higher-Order Components 196
Composing 199
Pros 199
Cons 200
Render Props Pattern 200
Lifting State 202
Children as a Function 204
Pros 205
Cons 205
Hooks Pattern 205
Class Components 206
Restructuring 207
Complexity 208
Hooks 208
State Hook 208
Effect Hook 210
Custom Hooks 211
Additional Hooks Guidance 213
Pros and Cons of Using Hooks 213
React Hooks Versus Classes 216
Static Import 216
Dynamic Import 217
Loadable Components 219
Import on Interaction 220
Import on Visibility 220
Code-Splitting 221
Route-based Splitting 221
Bundle Splitting 222
PRPL Pattern 224
Loading Prioritization 226
Preload in Single-Page Apps 227
Preload + the async Hack 228
Preload in Chrome 95+ 228
List Virtualization 228
How Does Windowing/Virtualization Work? 228
Lists 229

viii | Table of Contents


Grid 230
Improvements in the Web Platform 232
Conclusions 232
Summary 232

13. Rendering Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


Importance of Rendering Patterns 234
Client-Side Rendering 236
Server-Side Rendering 236
Static Rendering 237
Incremental Static Regeneration 238
On-Demand ISR 239
Summary of Static Rendering 239
Streaming SSR 240
Edge SSR 241
Hybrid Rendering 241
Progressive Hydration 242
Islands Architecture 243
Implementing Islands 243
Pros and Cons 244
React Server Components 245
Hybrid Rendering with RSC and the Next.js App Router 246
Summary 246

14. Application Structure for React.js. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249


Introduction 249
Group by Module, Feature, or Route 250
Group by File Type 250
Hybrid Grouping Based on Domain and Common Components 251
Application Structure for Modern React Features 252
Redux 253
Containers 253
Hooks 253
Styled Components 254
Other Best Practices 254
Application Structure for Next.js Apps 256
Summary 257

15. Conclusions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259

Appendix: References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

Table of Contents | ix
Preface

The world of JavaScript has come a long way since I wrote the first edition of Learn‐
ing JavaScript Design Patterns over 10 years ago. At that time, I was working on large-
scale web applications and found that the lack of structure and organization in
JavaScript code made it difficult to maintain and scale those applications.
Fast forward to today, and the web development landscape has changed dramatically.
JavaScript has become one of the most popular programming languages in the world
and is used for everything from simple scripts to complex web applications. The Java‐
Script language has evolved to include modules, promises, and async/await, which
has heavily influenced how we architect applications. The way developers write com‐
ponents, such as with React, has also significantly impacted how they think about
maintainability. This has resulted in the need for modern patterns that take these new
changes into account.
With the rise of modern libraries and frameworks like React, Vue, and Angular,
developers are now building applications that are more complex than ever before. I
recognized the need for an updated version of Learning JavaScript Design Patterns to
reflect the changes in JavaScript and web application development.
In this second edition of Learning JavaScript Design Patterns, I aim to help developers
apply modern design patterns to their JavaScript code and React applications. The
book covers more than 20 design patterns essential for building maintainable and
scalable applications. The book is not just about design patterns but also about ren‐
dering and performance patterns, which are critical to the success of modern web
applications.
The first edition of this book focused on classical design patterns, such as the Module
pattern, the Observer pattern, and the Mediator pattern. These patterns are still
important and relevant today, but the web development world has evolved signifi‐
cantly in the past decade, and new patterns have emerged. This new edition covers
these new patterns, such as promises, async/await, and the newer variations of the

xi
Module pattern. We also cover architectural patterns such as MVC, MVP, and
MVVM and discuss where modern frameworks fit with these architectural patterns.
Today’s developers are exposed to many library-specific or framework-specific
design patterns. React’s matured ecosystem and utilization of newer JS primitives
provide an excellent launchpad to talk about best practices and patterns in the frame‐
work or library context. In addition to classic design patterns, this book covers
modern React patterns, such as Hooks, Higher-Order Components, and Render
Props. These patterns are specific to React and essential for building modern web
applications using this popular framework.
This book is not just about patterns; it’s also about best practices. We cover topics
such as code organization, performance, and rendering, which are crucial for build‐
ing high-quality web applications. You will learn about dynamic imports, code-
splitting, server-side rendering, hydration, and Islands architecture, all of which are
essential for building fast and responsive web applications.
By the end of this book, you will have a deep understanding of design patterns and
how to apply them to your JavaScript code and React applications. You will also
know which patterns are relevant to the modern web and which are not. This book is
not just a reference for patterns; it’s also a guide to building high-quality web applica‐
tions. You will learn how to structure your code for maximum maintainability and
scalability and how to optimize your code for performance.

Structure of the Book


This book is organized into 15 chapters, designed to walk you through JavaScript
design patterns from a modern perspective, incorporating updated language features
and React-specific patterns. Each chapter builds upon the previous one, enabling you
to grow your knowledge incrementally and apply it effectively:

• Chapter 1, “Introduction to Design Patterns”: Get acquainted with the history of


design patterns and their significance in the programming world.
• Chapter 2, ““Pattern”-ity Testing, Proto-Patterns, and the Rule of Three”: Under‐
stand the process of evaluating and refining design patterns.
• Chapter 3, “Structuring and Writing Patterns”: Learn the anatomy of a well-
written pattern and how to create one.
• Chapter 4, “Anti-Patterns”: Discover what anti-patterns are and how to avoid
them in your code.
• Chapter 5, “Modern JavaScript Syntax and Features”: Explore the latest Java‐
Script language features and their impact on design patterns.

xii | Preface
• Chapter 6, “Categories of Design Patterns”: Delve into the different categories of
design patterns: creational, structural, and behavioral.
• Chapter 7, “JavaScript Design Patterns”: Study over 20 classic design patterns in
JavaScript and their modern adaptations.
• Chapter 8, “JavaScript MV* Patterns”: Learn about architectural patterns like
MVC, MVP, and MVVM and their significance in modern web development.
• Chapter 9, “Asynchronous Programming Patterns”: Understand the power of
asynchronous programming in JavaScript and various patterns for handling it.
• Chapter 10, “Modular JavaScript Design Patterns”: Discover patterns for organ‐
izing and modularizing your JavaScript code.
• Chapter 11, “Namespacing Patterns”: Learn various techniques for namespacing
your JavaScript code to avoid global namespace pollution.
• Chapter 12, “React.js Design Patterns”: Explore React-specific patterns, including
Higher-Order Components, Render Props, and Hooks.
• Chapter 13, “Rendering Patterns”: Understand different rendering techniques
like client-side rendering, server-side rendering, progressive hydration, and
Islands architecture.
• Chapter 14, “Application Structure for React.js”: Learn how to structure your
React application for better organization, maintainability, and scalability.
• Chapter 15, “Conclusions”: Wrap up the book with key takeaways and final
thoughts.

Throughout the book, practical examples are provided to illustrate the patterns and
concepts discussed. By the end of your journey, you’ll have a solid understanding of
JavaScript design patterns and be equipped to write elegant, maintainable, and scal‐
able code.
Whether you’re a seasoned web developer or just starting out, this book will provide
the knowledge and tools you need to build modern, maintainable, and scalable web
applications. I hope that this book will be a valuable resource for you as you continue
to develop your skills and build amazing web applications.

Conventions Used in This Book


The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.

Preface | xiii
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.

This element signifies a tip or suggestion.

This element signifies a general note.

Using Code Examples


Supplemental material (code examples, exercises, etc.) is available for download at
https://github.com/addyosmani/learning-jsdp.
If you have a technical question or a problem using the code examples, please send
email to bookquestions@oreilly.com.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing examples from O’Reilly
books does require permission. Answering a question by citing this book and quoting
example code does not require permission. Incorporating a significant amount of
example code from this book into your product’s documentation does require
permission.
We appreciate, but generally do not require, attribution. An attribution usually
includes the title, author, publisher, and ISBN. For example: “Learning JavaScript
Design Patterns, 2nd ed., by Addy Osmani (O’Reilly). Copyright 2023 Adnan
Osmani, 978-1-098-13987-2.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.

xiv | Preface
O’Reilly Online Learning
For more than 40 years, O’Reilly Media has provided technol‐
ogy and business training, knowledge, and insight to help
companies succeed.

Our unique network of experts and innovators share their knowledge and expertise
through books, articles, and our online learning platform. O’Reilly’s online learning
platform gives you on-demand access to live training courses, in-depth learning
paths, interactive coding environments, and a vast collection of text and video from
O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com.

How to Contact Us
Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.


1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at https://oreil.ly/js_design_patterns_2e.
Email bookquestions@oreilly.com to comment or ask technical questions about this
book.
For news and information about our books and courses, visit https://oreilly.com.
Find us on LinkedIn: https://linkedin.com/company/oreilly-media
Follow us on Twitter: https://twitter.com/oreillymedia
Watch us on YouTube: https://youtube.com/oreillymedia

Acknowledgments
I would like to thank the amazing reviewers for the second edition, including Stoyan
Stefanov, Julian Setiawan, Viswesh Ravi Shrimali, Adam Scott, and Lydia Hallie.
The first edition’s passionate, talented technical reviewers included Nicholas Zakas,
Andrée Hansson, Luke Smith, Eric Ferraiuolo, Peter Michaux, and Alex Sexton.
They—as well as members of the community at large—helped review and improve

Preface | xv
this book, and the knowledge and enthusiasm they brought to the project was simply
amazing.
A special thanks to Leena Sohoni-Kasture for her contributions and feedback to the
editing of the second edition.
Finally, I would like to thank my wonderful wife, Elle, for all of her support while I
was putting together this publication.

xvi | Preface
CHAPTER 1
Introduction to Design Patterns

Good code is like a love letter to the next developer who will maintain it!
Design patterns provide a common vocabulary to structure code, making it easier to
understand. They help enhance the quality of this connection to other developers.
Knowledge of design patterns helps us identify recurring themes in requirements and
map them to definitive solutions. We can rely on the experience of others who have
encountered a similar problem and devised an optimized method to address it. This
knowledge is invaluable as it paves the way for writing or refactoring code to make it
maintainable.
Whether on the server or client, JavaScript is a cornerstone of modern web applica‐
tion development. The previous edition of this book focused on several popular
design patterns in the JavaScript context. Over the years, JavaScript has significantly
evolved as a language in terms of features and syntax. It now supports modules,
classes, arrow functions, and template literals that it did not previously. We also have
advanced JavaScript libraries and frameworks that have made life easy for many web
developers. How relevant, then, are design patterns in the modern JavaScript context?
It’s important to note that traditionally, design patterns are neither prescriptive nor
language-specific. You can apply them when you think they fit, but you don’t have to.
Like data structures or algorithms, you can still apply classic design patterns using
modern programming languages, including JavaScript. You may not need some of
these design patterns in modern frameworks or libraries where they are already
abstracted. Conversely, the use of specific patterns may even be encouraged by some
frameworks.
In this edition, we are taking a pragmatic approach to patterns. We will explore why
specific patterns may be the right fit for implementing certain features and if a pat‐
tern is still recommended in the modern JavaScript context.

1
As applications got more interactive, requiring a large amount of JavaScript, the lan‐
guage came under constant criticism for its negative impact on performance. Devel‐
opers are continuously looking for new patterns that can optimize JavaScript
performance. This edition highlights such improvements wherever relevant. We will
also discuss framework-specific patterns such as React Hooks and Higher-Order
Components that have become increasingly popular in the age of React.js.
Going back a step, let us start by exploring the history and importance of design pat‐
terns. If you’re already familiar with this history, feel free to skip to “What Is a Pat‐
tern?” on page 2 to continue reading.

History of Design Patterns


Design patterns can be traced back to the early work of an architect named Christo‐
pher Alexander. He often wrote about his experiences in solving design issues and
how they related to buildings and towns. One day, it occurred to Alexander that cer‐
tain design constructs lead to a desired optimal effect when used repeatedly.
Alexander produced a pattern language in collaboration with two other architects,
Sara Ishikawa and Murray Silverstein. This language would help empower anyone
wishing to design and build at any scale. They published it in 1977 in a paper titled
“A Pattern Language,” later released as a complete hardcover book.
Around 1990, software engineers began to incorporate the principles Alexander had
written about into the first documentation about design patterns to guide novice
developers looking to improve their coding skills. It’s important to note that the con‐
cepts behind design patterns have been around in the programming industry since its
inception, albeit in a less formalized form.
One of the first and arguably the most iconic formal works published on design pat‐
terns in software engineering was a book in 1995 called Design Patterns: Elements of
Reusable Object-Oriented Software—written by Erich Gamma, Richard Helm, Ralph
Johnson, and John Vlissides. Most engineers today recognize this group as the Gang
of Four (GoF).
The GoF publication was particularly instrumental in pushing the concept of design
patterns further in our field. It describes several development techniques and pitfalls
and provides 23 core object-oriented design patterns frequently used worldwide
today. We will cover these patterns in more detail in Chapter 6, and they also form
the basis for our discussion in Chapter 7.

What Is a Pattern?
A pattern is a reusable solution template that you can apply to recurring problems
and themes in software design. Similar to other programming languages, when build‐

2 | Chapter 1: Introduction to Design Patterns


ing a JavaScript web application, you can use the template to structure your Java‐
Script code in different situations where you think it will help.
Learning and using design patterns is mainly advantageous for developers because of
the following:
Patterns are proven solutions.
They are the result of the combined experience and insights of developers who
helped define them. They are time-tested approaches known to work when solv‐
ing specific issues in software development.
Patterns can be easily reused.
A pattern usually delivers an out-of-the-box solution you can adopt and adapt to
suit your needs. This feature makes them quite robust.
Patterns can be expressive.
Patterns can help express elegant solutions to extensive problems using a set
structure and a shared vocabulary.
Additional advantages that patterns offer include the following:
Patterns assist in preventing minor issues that can cause significant problems in the
application development process.
When you use established patterns to build code, you can relax about getting the
structure wrong and focus on the quality of the overall solution. The pattern
encourages you to write more structured and organized code naturally, avoiding
the need to refactor it for cleanliness in the future.
Patterns provide generalized solutions, documented in a fashion that doesn’t require
them to be tied to a specific problem.
This generalized approach means you can apply design patterns to improve code
structure regardless of the application (and, in many cases, the programming
language).
Some patterns can decrease the overall code file-size footprint by avoiding repetition.
Design patterns encourage developers to look more closely at their solutions for
areas where they can achieve instant reductions in duplication. For example, you
can reduce the number of functions performing similar processes in favor of a
single generalized function to decrease the size of your codebase. This is also
known as making code more dry.
Patterns add to a developer’s vocabulary, which makes communication faster.
Developers can reference the pattern when communicating with their team,
when discussing it in the design patterns community, or indirectly when another
developer later maintains the code.

What Is a Pattern? | 3
Popular design patterns can be improvised further by harnessing the collective experi‐
ences of developers using those patterns and contributing back to the community.
In some cases, this leads to the creation of entirely new design patterns, while in
others, it can lead to improved guidelines on the usage of specific patterns. This
can ensure that pattern-based solutions continue to become more robust than ad
hoc ones.

Patterns are not exact solutions. The role of a pattern is merely to


provide us with a solution scheme. Patterns don’t solve all design
problems, nor do they replace good software designers. You still
need sound designers to choose the correct patterns that can
enhance the overall design.

An Everyday Use Case for Design Patterns


If you have used React.js, you have probably come across the Provider pattern. If not,
you may have experienced the following situation.
The component tree in web applications often needs access to shared data such as
user information or user access permissions. The traditional way to do this in Java‐
Script is to set these properties for the root level component and then pass them
down from parent to child components. As the component hierarchy deepens and
becomes more nested, you drill down it with your data, resulting in the practice of
prop drilling. This leads to unmaintainable code where the property setting and pass‐
ing will get repeated in every child component, which relies on that data.
React and a few other frameworks address this problem using the Provider pattern.
With the Provider pattern, the React Context API can broadcast the state/data to
multiple components via a context provider. Child components needing the shared
data can tap into this provider as a context consumer or use the useContext Hook.
This is an excellent example of a design pattern used to optimize the solution to a
common problem. We will cover this and many such patterns in a lot of detail in this
book.

4 | Chapter 1: Introduction to Design Patterns


Summary
With that introduction to the importance of design patterns and their relevance to
modern JavaScript, we can now deep dive into learning JavaScript design patterns.
The first few chapters in this book cover structuring and classifying patterns and
identifying anti-patterns before we go into the specifics of design patterns for Java‐
Script. But first, let’s see what it takes for a proposed “proto-pattern” to be recognized
as a pattern in the next chapter.

Summary | 5
CHAPTER 2
“Pattern”-ity Testing, Proto-Patterns,
and the Rule of Three

From the moment a new pattern is proposed to its potential widespread adoption, a
pattern may have to go through multiple rounds of deep inspection by the design
community and software developers. This chapter talks about this journey of a newly
introduced “proto-pattern” through a “pattern”-ity test until it is eventually recog‐
nized as a pattern if it meets the rule of three.
This and the next chapter explore the approach to structuring, writing, presenting,
and reviewing nascent design patterns. If you’d prefer to learn established design pat‐
terns first, you can skip these two chapters for the time being.

What Are Proto-Patterns?


Remember that not every algorithm, best practice, or solution represents what might
be considered a complete pattern. There may be a few key ingredients missing, and
the pattern community is generally wary of something claiming to be one without an
extensive and critical evaluation. Even if something is presented to us which appears
to meet the criteria for a pattern, we should not consider it as one until it has under‐
gone suitable periods of scrutiny and testing by others.
Looking back upon Alexander’s work once more, he claims that a pattern should be
both a process and a “thing.” This definition is obtuse as he follows by saying that it is
the process that should create the “thing.” This is why patterns generally focus on
addressing a visually identifiable structure; we should be able to visually depict (or
draw) a picture representing the structure resulting from placing the pattern into
practice.

7
Random documents with unrelated
content Scribd suggests to you:
CHAPTER VIII
JANE GETS OFF THE FAIRWAY

The side-door leading into the smoking-room opened, and the


golf-club’s popular and energetic secretary came trotting down the
steps on to the terrace above the ninth green. As he reached the
gravel, a wandering puff of wind blew the door to with a sharp report,
and the Oldest Member, who had been dozing in a chair over his
Wodehouse on the Niblick, unclosed his eyes, blinking in the strong
light. He perceived the secretary skimming to and fro like a questing
dog.
“You have lost something?” he inquired, courteously.
“Yes, a book. I wish,” said the secretary, annoyed, “that people
would leave things alone. You haven’t seen a novel called The Man
with the Missing Eyeball anywhere about, have you? I’ll swear I left it
on one of these seats when I went in to lunch.”
“You are better without it,” said the Sage, with a touch of austerity.
“I do not approve of these trashy works of fiction. How much more
profitably would your time be spent in mastering the contents of such
a volume as I hold in my hand. This is the real literature.”
The secretary drew nearer, peering discontentedly about him; and
as he approached the Oldest Member sniffed inquiringly.
“What,” he said, “is that odour of—? Ah, I see that you are wearing
them in your buttonhole. White violets,” he murmured. “White violets.
Dear me!”
The secretary smirked.
“A girl gave them to me,” he said, coyly. “Nice, aren’t they?” He
squinted down complacently at the flowers, thus missing a sudden
sinister gleam in the Oldest Member’s eye—a gleam which, had he
been on his guard, would have sent him scudding over the horizon;
for it was the gleam which told that the Sage had been reminded of a
story.
“White violets,” said the Oldest Member, in a meditative voice. “A
curious coincidence that you should be wearing white violets and
looking for a work of fiction. The combination brings irresistibly to my
mind—”
Realising his peril too late, the secretary started violently. A gentle
hand urged him into the adjoining chair.
“—the story,” proceeded the Oldest Member, “of William Bates,
Jane Packard, and Rodney Spelvin.”
The secretary drew a deep breath of relief and the careworn look
left his face.
“It’s all right,” he said, briskly. “You told me that one only the other
day. I remember every word of it. Jane Packard got engaged to
Rodney Spelvin, the poet, but her better feelings prevailed in time,
and she broke it off and married Bates, who was a golfer. I recall the
whole thing distinctly. This man Bates was an unromantic sort of
chap, but he loved Jane Packard devotedly. Bless my soul, how it all
comes back to me! No need to tell it me at all!”
“What I am about to relate now,” said the sage, tightening his grip
on the other’s coat-sleeve, “is another story about William Bates,
Jane Packard, and Rodney Spelvin.”

Inasmuch (said the Oldest Member) as you have not forgotten the
events leading up to the marriage of William Bates and Jane
Packard, I will not repeat them. All I need say is that that curious
spasm of romantic sentiment which had caused Jane to fall
temporarily under the spell of a man who was not only a poet but
actually a non-golfer, appeared to have passed completely away,
leaving no trace behind. From the day she broke off her engagement
to Spelvin and plighted her troth to young Bates, nothing could have
been more eminently sane and satisfactory than her behaviour.
She seemed entirely her old self once more. Two hours after
William had led her down the aisle, she and he were out on the links,
playing off the final of the Mixed Foursomes which—and we all
thought it the best of omens for their married happiness—they won
hands down. A deputation of all that was best and fairest in the
village then escorted them to the station to see them off on their
honeymoon, which was to be spent in a series of visits to well-known
courses throughout the country.
Before the train left, I took young William aside for a moment. I
had known both him and Jane since childhood, and the success of
their union was very near my heart.
“William,” I said, “a word with you.”
“Make it snappy,” said William.
“You have learned by this time,” I said, “that there is a strong
romantic streak in Jane. It may not appear on the surface, but it is
there. And this romantic streak will cause her, like so many wives, to
attach an exaggerated importance to what may seem to you trivial
things. She will expect from her husband not only love and a
constant tender solicitude—”
“Speed it up,” urged William.
“What I am trying to say is that, after the habit of wives, she will
expect you to remember each year the anniversary of your wedding
day, and will be madder than a wet hen if you forget it.”
“That’s all right. I thought of that myself.”
“It is not all right,” I insisted. “Unless you take the most earnest
precautions, you are absolutely certain to forget. A year from now
you will come down to breakfast and Jane will say to you, ‘Do you
know what day it is to-day?’ and you will answer ‘Tuesday’ and reach
for the ham and eggs, thus inflicting on her gentle heart a wound
from which it will not readily recover.”
“Nothing like it,” said William, with extraordinary confidence. “I’ve
got a system calculated to beat the game every time. You know how
fond Jane is of white violets?”
“Is she?”
“She loves ’em. The bloke Spelvin used to give her a bunch every
day. That’s how I got the idea. Nothing like learning the shots from
your opponent. I’ve arranged with a florist that a bunch of white
violets is to be shipped to Jane every year on this day. I paid five
years in advance. I am therefore, speaking in the most conservative
spirit, on velvet. Even if I forget the day, the violets will be there to
remind me. I’ve looked at it from every angle, and I don’t see how it
can fail. Tell me frankly, is the scheme a wam or is it not?”
“A most excellent plan,” I said, relieved. And the next moment the
train came in. I left the station with my mind at rest. It seemed to me
that the only possible obstacle to the complete felicity of the young
couple had been removed.

Jane and William returned in due season from their honeymoon,


and settled down to the normal life of a healthy young couple. Each
day they did their round in the morning and their two rounds in the
afternoon, and after dinner they would sit hand in hand in the
peaceful dusk, reminding one another of the best shots they had
brought off at the various holes. Jane would describe to William how
she got out of the bunker on the fifth, and William would describe to
Jane the low raking wind-cheater he did on the seventh, and then for
a moment they would fall into that blissful silence which only true
lovers know, until William, illustrating his remarks with a walking-
stick, would show Jane how he did that pin-splitter with the mashie
on the sixteenth. An ideally happy union, one would have said.
But all the while a little cloud was gathering. As the anniversary of
their wedding day approached, a fear began to creep into Jane’s
heart that William was going to forget it. The perfect husband does
not wait till the dawning of the actual day to introduce the
anniversary motif into his conversation. As long as a week in
advance he is apt to say, dreamily, “About this time a year ago I was
getting the old silk hat polished up for the wedding,” or “Just about
now, a year ago, they sent home the sponge-bag trousers, as worn,
and I tried them on in front of the looking-glass.” But William said
none of these things. Not even on the night before the all-important
date did he make any allusion to it, and it was with a dull feeling of
foreboding that Jane came down to breakfast next morning.
She was first at the table, and was pouring out the coffee when
William entered. He opened the morning paper and started to peruse
its contents in silence. Not a yip did he let out of him to the effect that
this was the maddest, merriest day of all the glad new year.
“William,” said Jane.
“Hullo?”
“William,” said Jane, and her voice trembled a little, “what day is it
to-day?”
William looked at her over the paper surprised.
“Wednesday, old girl,” he replied. “Don’t you remember that
yesterday was Tuesday? Shocking memory you’ve got.”
He then reached out for the sausages and bacon and resumed his
reading.
“Jane,” he said, suddenly. “Jane, old girl, there’s something I want
to tell you.”
“Yes?” said Jane, her heart beginning to flutter.
“Something important.”
“Yes?”
“It’s about these sausages. They are the very best,” said William,
earnestly, “that I have ever bitten. Where did you get them?”
“From Brownlow.”
“Stick to him,” said William.
Jane rose from the table and wandered out into the garden. The
sun shone gaily, but for her the day was bleak and cold. That William
loved her she did not doubt. But that streak of romance in her
demanded something more than mere placid love. And when she
realised that the poor mutt with whom she had linked her lot had
forgotten the anniversary of their wedding-day first crack out of the
box, her woman’s heart was so wounded that for two pins she could
have beaned him with a brick.
It was while she was still brooding in this hostile fashion that she
perceived the postman coming up the garden. She went to meet
him, and was handed a couple of circulars and a mysterious parcel.
She broke the string, and behold! a cardboard box containing white
violets.
Jane was surprised. Who could be sending her white violets? No
message accompanied them. There was no clue whatever to their
origin. Even the name of the florist had been omitted.
“Now, who—?” mused Jane, and suddenly started as if she had
received a blow. Rodney Spelvin! Yes, it must be he. How many a
bunch of white violets had he given her in the brief course of their
engagement! This was his poetic way of showing her that he had not
forgotten. All was over between them, she had handed him his hat
and given him the air, but he still remembered.
Jane was a good and dutiful wife. She loved her William, and no
others need apply. Nevertheless, she was a woman. She looked
about her cautiously. There was nobody in sight. She streaked up to
her room and put the violets in water. And that night, before she went
to bed, she gazed at them for several minutes with eyes that were a
little moist. Poor Rodney! He could be nothing to her now, of course,
but a dear lost friend; but he had been a good old scout in his day.

It is not my purpose to weary you with repetitious detail in this


narrative. I will, therefore, merely state that the next year and the
next year and the year after that precisely the same thing took place
in the Bates’s home. Punctually every September the seventh
William placidly forgot, and punctually every September the seventh
the sender of the violets remembered. It was about a month after the
fifth anniversary, when William had got his handicap down to nine
and little Braid Vardon Bates, their only child, had celebrated his
fourth birthday, that Rodney Spelvin, who had hitherto confined
himself to poetry, broke out in a new place and inflicted upon the
citizenry a novel entitled The Purple Fan.
I saw the announcement of the publication in the papers; but
beyond a passing resolve that nothing would induce me to read the
thing I thought no more of the matter. It is always thus with life’s
really significant happenings. Fate sneaks its deadliest wallops in on
us with such seeming nonchalance. How could I guess what that
book was to do to the married happiness of Jane and William Bates?
In deciding not to read The Purple Fan I had, I was to discover,
over-estimated my powers of resistance. Rodney Spelvin’s novel
turned out to be one of those things which it is impossible not to
read. Within a week of its appearance it had begun to go through the
country like Spanish influenza; and, much as I desired to avoid it, a
perusal was forced on me by sheer weight of mass-thinking. Every
paper that I picked up contained reviews of the book, references to
it, letters from the clergy denouncing it; and when I read that three
hundred and sixteen mothers had signed a petition to the authorities
to have it suppressed, I was reluctantly compelled to spring the
necessary cash and purchase a copy.
I had not expected to enjoy it, and I did not. Written in the
neodecadent style, which is so popular nowadays, its preciosity
offended me; and I particularly objected to its heroine, a young
woman of a type which, if met in real life, only ingrained chivalry
could have prevented a normal man from kicking extremely hard.
Having skimmed through it, I gave my copy to the man who came to
inspect the drains. If I had any feeling about the thing, it was a
reflection that, if Rodney Spelvin had had to get a novel out of his
system, this was just the sort of novel he was bound to write. I
remember experiencing a thankfulness that he had gone so entirely
out of Jane’s life. How little I knew!
Jane, like every other woman in the village, had bought her copy
of The Purple Fan. She read it surreptitiously, keeping it concealed,
when not in use, beneath a cushion on the Chesterfield. It was not its
general tone that caused her to do this, but rather the subconscious
feeling that she, a good wife, ought not to be deriving quite so much
enjoyment from the work of a man who had occupied for a time such
a romantic place in her life.
For Jane, unlike myself, adored the book. Eulalie French, its
heroine, whose appeal I had so missed, seemed to her the most
fascinating creature she had ever encountered.
She had read the thing through six times when, going up to town
one day to do some shopping, she ran into Rodney Spelvin. They
found themselves standing side by side on the pavement, waiting for
the traffic to pass.
“Rodney!” gasped Jane.
It was a difficult moment for Rodney Spelvin. Five years had
passed since he had last seen Jane, and in those five years so many
delightful creatures had made a fuss of him that the memory of the
girl to whom he had once been engaged for a few weeks had
become a little blurred. In fact, not to put too fine a point on it, he had
forgotten Jane altogether. The fact that she had addressed him by
his first name seemed to argue that they must have met at some
time somewhere; but, though he strained his brain, absolutely
nothing stirred.
The situation was one that might have embarrassed another man,
but Rodney Spelvin was a quick thinker. He saw at a glance that
Jane was an extremely pretty girl, and it was his guiding rule in life
never to let anything like that get past him. So he clasped her hand
warmly, allowed an expression of amazed delight to sweep over his
face, and gazed tensely into her eyes.
“You!” he murmured, playing it safe. “You, little one!”
Jane stood five feet seven in her stockings and had a fore-arm like
the village blacksmith’s, but she liked being called “little one.”
“How strange that we should meet like this!” she said, blushing
brightly.
“After all these years,” said Rodney Spelvin, taking a chance. It
would be a nuisance if it turned out that they had met at a studio-
party the day before yesterday, but something seemed to tell him
that she dated back a goodish way. Besides, even if they had met
the day before yesterday, he could get out of it by saying that the
hours had seemed like years. For you cannot stymie these modern
poets. The boys are there.
“More than five,” murmured Jane.
“Now where the deuce was I five years ago?” Rodney Spelvin
asked himself.
Jane looked down at the pavement and shuffled her left shoe
nervously.
“I got the violets, Rodney,” she said.
Rodney Spelvin was considerably fogged, but he came back
strongly.
“That’s good!” he said. “You got the violets? That’s capital. I was
wondering if you would get the violets.”
“It was like you to send them.”
Rodney blinked, but recovered himself immediately. He waved his
hand with a careless gesture, indicative of restrained nobility.
“Oh, as to that—!”
“Especially as I’m afraid I treated you rather badly. But it really was
for the happiness of both of us that I broke off the engagement. You
do understand that, don’t you?”
A light broke upon Rodney Spelvin. He had been confident that it
would if he only stalled along for a while. Now he placed this girl.
She was Jane something, the girl he had been engaged to. By Jove,
yes. He knew where he was now.
“Do not let us speak of it,” he said, registering pain. It was quite
easy for him to do this. All there was to it was tightening the lips and
drawing up the left eyebrow. He had practised it in front of his mirror,
for a fellow never knew when it might not come in useful.
“So you didn’t forget me, Rodney?”
“Forget you!”
There was a short pause.
“I read your novel,” said Jane. “I loved it.”
She blushed again, and the colour in her cheeks made her look so
remarkably pretty that Rodney began to feel some of the emotions
which had stirred him five years ago. He decided that this was a
good thing and wanted pushing along.
“I hoped that you might,” he said in a low voice, massaging her
hand. He broke off and directed into her eyes a look of such squashy
sentimentality that Jane reeled where she stood. “I wrote it for you,”
he added, simply.
Jane gasped.
“For me?”
“I supposed you would have guessed,” said Rodney. “Surely you
saw the dedication?”
The Purple Fan had been dedicated, after Rodney Spelvin’s
eminently prudent fashion, to “One Who Will Understand.” He had
frequently been grateful for the happy inspiration.
“The dedication?”
“‘To One Who Will Understand,’” said Rodney, softly. “Who would
that be but you?”
“Oh, Rodney!”
“And didn’t you recognise Eulalie, Jane? Surely you cannot have
failed to recognise Eulalie?”
“Recognise her?”
“I drew her from you,” said Rodney Spelvin.

Jane’s mind was in a whirl as she went home in the train. To have
met Rodney Spelvin again was enough in itself to stimulate into
activity that hidden pulse of romance in her. To discover that she had
been in his thoughts so continuously all these years and that she still
held such sway over his faithful heart that he had drawn the heroine
of his novel from her was simply devastating. Mechanically she got
out at the right station and mechanically made her way to the
cottage. She was relieved to find that William was still out on the
links. She loved William devotedly, of course, but just at the moment
he would have been in the way; for she wanted a quiet hour with The
Purple Fan. It was necessary for her to re-read in the light of this
new knowledge the more important of the scenes in which Eulalie
French figured. She knew them practically by heart already, but
nevertheless she wished to read them again. When William returned,
warm and jubilant, she was so absorbed that she only just had time
to slide the book under the sofa-cushion before the door opened.
Some guardian angel ought to have warned William Bates that he
was selecting a bad moment for his re-entry into the home, or at
least to have hinted that a preliminary wash and brush-up would be
no bad thing. There had been rain in the night, causing the links to
become a trifle soggy in spots, and William was one of those
energetic golfers who do not spare themselves. The result was that
his pleasant features were a good deal obscured by mud. An
explosion-shot out of the bunker on the fourteenth had filled his hair
with damp sand, and his shoes were a disgrace to any refined home.
No, take him for all in all, William did not look his best. He was fine if
the sort of man you admired was the brawny athlete straight from the
dust of the arena; but on a woman who was picturing herself the
heroine of The Purple Fan he was bound to jar. Most of the scenes
in which Eulalie French played anything like a fat part took place
either on moonlight terraces or in beautifully furnished studios
beneath the light of Oriental lamps with pink silk shades, and all the
men who came in contact with her—except her husband, a
clodhopping brute who spent most of his time in riding-kit—were
perfectly dressed and had dark, clean-cut, sensitive faces.
William, accordingly, induced in Jane something closely
approximating to the heeby-jeebies.
“Hullo, old girl!” said William, affectionately. “You back? What have
you been doing with yourself?”
“Oh, shopping,” said Jane, listlessly.
“See any one you knew?”
For a moment Jane hesitated.
“Yes,” she said. “I met Rodney Spelvin.”
Jealousy and suspicion had been left entirely out of William
Bates’s make-up. He did not start and frown; he did not clutch the
arm of his chair; he merely threw back his head and laughed like a
hyæna. And that laugh wounded Jane more than the most violent
exhibition of mistrust could have done.
“Good Lord!” gurgled William, jovially. “You don’t mean to say that
bird is still going around loose? I should have thought he would have
been lynched years ago. Looks like negligence somewhere.”
There comes a moment in married life when every wife gazes
squarely at her husband and the scales seem to fall from her eyes
and she sees him as he is—one of Nature’s Class A fatheads.
Fortunately for married men, these times of clear vision do not last
long, or there would be few homes left unbroken. It was so that Jane
gazed at William now, but unhappily her conviction that he was an
out-size in rough-neck chumps did not pass. Indeed, all through that
evening it deepened. That night she went to bed feeling for the first
time that, when the clergyman had said, “Wilt thou, Jane?” and she
had replied in the affirmative, a mean trick had been played on an
inexperienced girl.
And so began that black period in the married life of Jane and
William Bates, the mere recollection of which in after years was
sufficient to put them right off their short game and even to affect
their driving from the tee. To William, having no clue to the cause of
the mysterious change in his wife, her behaviour was inexplicable.
Had not her perfect robustness made such a theory absurd, he
would have supposed that she was sickening for something. She
golfed now intermittently, and often with positive reluctance. She was
frequently listless and distrait. And there were other things about her
of which he disapproved.
“I say, old girl,” he said one evening, “I know you won’t mind my
mentioning it, and I don’t suppose you’re aware of it yourself, but
recently you’ve developed a sort of silvery laugh. A nasty thing to
have about the home. Try to switch it off, old bird, would you mind?”
Jane said nothing. The man was not worth answering. All through
the pages of The Purple Fan, Eulalie French’s silvery laugh had
been highly spoken of and greatly appreciated by one and all. It was
the thing about her that the dark, clean-cut, sensitive-faced men
most admired. And the view Jane took of the matter was that if
William did not like it the poor fish could do the other thing.
But this brutal attack decided her to come out into the open with
the grievance which had been vexing her soul for weeks past.
“William,” she said, “I want to say something. William, I am feeling
stifled.”
“I’ll open the window.”
“Stifled in this beastly little village, I mean,” said Jane, impatiently.
“Nobody ever does anything here except play golf and bridge, and
you never meet an artist-soul from one year’s end to the other. How
can I express myself? How can I be myself? How can I fulfil myself?”
“Do you want to?” asked William, somewhat out of his depth.
“Of course I want to. And I shan’t be happy unless we leave this
ghastly place and go to live in a studio in town.”
William sucked thoughtfully at his pipe. It was a tense moment for
a man who hated metropolitan life as much as he did. Nevertheless,
if the solution of Jane’s recent weirdness was simply that she had
got tired of the country and wanted to live in town, to the town they
must go. After a first involuntary recoil, he nerved himself to the
martyrdom like the fine fellow he was.
“We’ll pop off as soon as I can sell the house,” he said.
“I can’t wait as long as that. I want to go now.”
“All right,” said William, amiably. “We’ll go next week.”

William’s forebodings were quickly fulfilled. Before he had been in


the Metropolis ten days he had realised that he was up against it as
he had never been up against it before. He and Jane and little Braid
Vardon had established themselves in what the house-agent
described as an attractive bijou studio-apartment in the heart of the
artistic quarter. There was a nice bedroom for Jane, a delightful
cupboard for Braid Vardon, and a cosy corner behind a Japanese
screen for William. Most compact. The rest of the place consisted of
a room with a large skylight, handsomely furnished with cushions
and samovars, where Jane gave parties to the intelligentsia.
It was these parties that afflicted William as much as anything
else. He had not realised that Jane intended to run a salon. His idea
of a pleasant social evening was to have a couple of old friends in for
a rubber of bridge, and the almost nightly incursion of a horde of
extraordinary birds in floppy ties stunned him. He was unequal to the
situation from the first. While Jane sat enthroned on her cushion,
exchanging gay badinage with rising young poets and laughing that
silvery laugh of hers, William would have to stand squashed in a
corner, trying to hold off some bobbed-haired female who wanted his
opinion of Augustus John.
The strain was frightful, and, apart from the sheer discomfort of it,
he found to his consternation that it was beginning to affect his golf.
Whenever he struggled out from the artistic zone now to one of the
suburban courses, his jangled nerves unfitted him for decent play. Bit
by bit his game left him. First he found that he could not express
himself with the putter. Then he began to fail to be himself with the
mashie-niblick. And when at length he discovered that he was only
fulfilling himself about every fifth shot off the tee he felt that this thing
must stop.

The conscientious historian will always distinguish carefully


between the events leading up to a war and the actual occurrence
resulting in the outbreak of hostilities. The latter may be, and
generally is, some almost trivial matter, whose only importance is
that it fulfils the function of the last straw. In the case of Jane and
William what caused the definite rift was Jane’s refusal to tie a can to
Rodney Spelvin.
The author of The Purple Fan had been from the first a leading
figure in Jane’s salon. Most of those who attended these functions
were friends of his, introduced by him, and he had assumed almost
from the beginning the demeanour of a master of the revel. William,
squashed into his corner, had long gazed at the man with sullen
dislike, yearning to gather him up by the slack of his trousers and
heave him into outer darkness; but it is improbable that he would
have overcome his native amiability sufficiently to make any active
move, had it not been for the black mood caused by his rotten golf.
But one evening, when, coming home after doing the Mossy Heath
course in five strokes over the hundred, he found the studio
congested with Rodney Spelvin and his friends, many of them
playing ukeleles, he decided that flesh and blood could bear the
strain no longer.
As soon as the last guest had gone he delivered his ultimatum.
“Listen, Jane,” he said. “Touching on this Spelvin bloke.”
“Well?” said Jane, coldly. She scented battle from afar.
“He gives me a pain in the neck.”
“Really?” said Jane, and laughed a silvery laugh.
“Don’t do it, old girl,” pleaded William, wincing.
“I wish you wouldn’t call me ‘old girl’.”
“Why not?”
“Because I don’t like it.”
“You used to like it.”
“Well, I don’t now.”
“Oh!” said William, and ruminated awhile. “Well, be that as it may,”
he went on, “I want to tell you just one thing. Either you throw the
bloke Spelvin out on his left ear and send for the police if he tries to
get in again, or I push off. I mean it! I absolutely push off.”
There was a tense silence.
“Indeed?” said Jane at last.
“Positively push off,” repeated William, firmly. “I can stand a lot, but
pie-faced Spelvin tries human endurance too high.”
“He is not pie-faced,” said Jane, warmly.
“He is pie-faced,” insisted William. “Come round to the Vienna
Bon-Ton Bakery to-morrow and I will show you an individual custard-
pie that might be his brother.”
“Well, I am certainly not going to be bullied into giving up an old
friend just because—”
William stared.
“You mean you won’t hand him the mitten?”
“I will not.”
“Think what you are saying, Jane. You positively decline to give
this false-alarm the quick exit?”
“I do.”
“Then,” said William, “all is over. I pop off.”
Jane stalked without a word into her bedroom. With a mist before
his eyes William began to pack. After a few moments he tapped at
her door.
“Jane.”
“Well?”
“I’m packing.”
“Indeed?”
“But I can’t find my spare mashie.”
“I don’t care.”
William returned to his packing. When it was finished, he stole to
her door again. Already a faint stab of remorse was becoming
blended with his just indignation.
“Jane.”
“Well?”
“I’ve packed.”
“Really?”
“And now I’m popping.”
There was silence behind the door.
“I’m popping, Jane,” said William. And in his voice, though he tried
to make it cold and crisp, there was a note of wistfulness.
Through the door there came a sound. It was the sound of a
silvery laugh. And as he heard it William’s face hardened. Without
another word he picked up his suit-case and golf-bag, and with set
jaw strode out into the night.
One of the things that tend to keep the home together in these
days of modern unrest is the fact that exalted moods of indignation
do not last. William, released from the uncongenial atmosphere of
the studio, proceeded at once to plunge into an orgy of golf that for a
while precluded regret. Each day he indulged his starved soul with
fifty-four holes, and each night he sat smoking in bed, pleasantly
fatigued, reviewing the events of the past twelve hours with complete
satisfaction. It seemed to him that he had done the good and
sensible thing.
And then, slowly at first, but day by day more rapidly, his mood
began to change. That delightful feeling of jolly freedom ebbed away.
It was on the morning of the tenth day that he first became
definitely aware that all was not well. He had strolled out on the links
after breakfast with a brassie and a dozen balls for a bit of practice,
and, putting every ounce of weight and muscle into the stroke,
brought off a snifter with his very first shot. Straight and true the ball
sped for the distant green, and William, forgetting everything in the
ecstasy of the moment, uttered a gladsome cry.
“How about that one, old girl?” he exclaimed.
And then, with a sudden sinking of the heart, he realised that he
was alone.
An acute spasm of regret shot through William’s massive bosom.
In that instant of clear thinking he understood that golf is not all.
What shall it profit a man that he do the long hole in four, if there is
no loving wife at his elbow to squeak congratulations? A dull
sensation of forlorn emptiness afflicted William Bates. It passed, but
it had been. And he knew it would come again.
It did. It came that same afternoon. It came next morning.
Gradually it settled like a cloud on his happiness. He did his best to
fight it down. He increased his day’s output to sixty-three holes, but
found no relief. When he reflected that he had had the stupendous
luck to be married to a girl like Jane and had chucked the thing up,
he could have kicked himself round the house. He was in exactly the
position of the hero of the movie when the subtitle is flashed on the
screen: “Came a Day When Remorse Bit Like an Adder Into Roland
Spenlow’s Soul.” Of all the chumps who had ever tripped over
themselves and lost a good thing, from Adam downwards, he, he
told himself, was the woollen-headedest.
On the fifteenth morning it began to rain.

Now, William Bates was not one of your fair-weather golfers. It


took more than a shower to discourage him. But this was real rain,
with which not even the stoutest enthusiast could cope. It poured
down all day in a solid sheet and set the seal on his melancholy. He
pottered about the house, sinking deeper and deeper into the slough
of despond, and was trying to derive a little faint distraction from
practising putts into a tooth-glass when the afternoon post arrived.
There was only one letter. He opened it listlessly. It was from
Jukes, Enderby, and Miller, florists, and what the firm wished to
ascertain was whether, his deposit on white violets to be despatched
annually to Mrs. William Bates being now exhausted, he desired to
renew his esteemed order. If so, on receipt of the money they would
spring to the task of sending same.
William stared at the letter dully. His first impression was that
Jukes, Enderby, and Miller were talking through their collective hats.
White violets? What was all this drivel about white violets? Jukes
was an ass. He knew nothing about white violets. Enderby was a
fool. What had he got to do with white violets? Miller was a pin-head.
He had never deposited any money to have white violets
despatched.
William gasped. Yes, by George, he had, though, he remembered
with a sudden start. So he had, by golly! Good gosh! It all came back
to him. He recalled the whole thing, by Jove! Crikey, yes!
The letter swam before William’s eyes. A wave of tenderness
engulfed him. All that had passed recently between Jane and himself
was forgotten—her weirdness, her wish to live in the Metropolis, her
silvery laugh—everything. With one long, loving gulp, William Bates
dashed a not unmanly tear from his eye and, grabbing a hat and
raincoat, rushed out of the house and sprinted for the station.
At about the hour when William flung himself into the train, Jane
was sitting in her studio-apartment, pensively watching little Braid
Vardon as he sported on the floor. An odd melancholy had gripped
her. At first she had supposed that this was due to the rain, but now
she was beginning to realise that the thing went much deeper than
that. Reluctant though she was to confess it, she had to admit that
what she was suffering from was a genuine soul-sadness, due
entirely to the fact that she wanted William.
It was strange what a difference his going had made. William was
the sort of fellow you shoved into a corner and forgot about, but
when he was not there the whole scheme of things seemed to go
blooey. Little by little, since his departure, she had found the
fascination of her surroundings tending to wane, and the glamour of
her new friends had dwindled noticeably. Unless you were in the
right vein for them, Jane felt, they could be an irritating crowd. They
smoked too many cigarettes and talked too much. And not far from
being the worst of them, she decided, was Rodney Spelvin. It was
with a sudden feeling of despair that she remembered that she had
invited him to tea this afternoon and had got in a special seed-cake
for the occasion. The last thing in the world that she wanted to do
was to watch Rodney Spelvin eating cake.
It is a curious thing about men of the Spelvin type, how seldom
they really last. They get off to a flashy start and for a while convince
impressionable girls that the search for a soul-mate may be
considered formally over; but in a very short while reaction always
sets in. There had been a time when Jane could have sat and
listened to Rodney Spelvin for hours on end. Then she began to feel
that from fifteen to twenty minutes was about sufficient. And now the
mere thought of having to listen to him at all was crushing her like a
heavy burden.
She had got thus far in her meditations when her attention was
attracted to little Braid Vardon, who was playing energetically in a

You might also like