(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
1. Instant Ebook Access, One Click Away – Begin at ebooknice.com
(Ebook) JavaScript Application Design: A Build
First Approach by Nicolas Bevacqua
https://ebooknice.com/product/javascript-application-design-
a-build-first-approach-50195416
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebooknice.com
2. Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
Start reading on any device today!
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
ISBN 9781617291951, 1617291951
https://ebooknice.com/product/javascript-application-design-a-build-first-
approach-5124860
ebooknice.com
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Bevacqua
ISBN 9781617291951, 1617291951
https://ebooknice.com/product/javascript-application-design-a-build-first-
approach-55920766
ebooknice.com
(Ebook) Practical Modern JavaScript: Dive into ES6 and the Future of JavaScript by
Nicolás Bevacqua ISBN 9781491943533, 149194353X
https://ebooknice.com/product/practical-modern-javascript-dive-into-es6-and-the-
future-of-javascript-10481740
ebooknice.com
(Ebook) High Performance JavaScript (Build Faster Web Application Interfaces) by
Nicholas C. Zakas ISBN 9780596802790, 059680279X
https://ebooknice.com/product/high-performance-javascript-build-faster-web-
application-interfaces-1321550
ebooknice.com
3. (Ebook) JavaScript Patterns: Build Better Applications with Coding and Design
Patterns by Stefanov, Stoyan ISBN 9780596806750, 0596806752
https://ebooknice.com/product/javascript-patterns-build-better-applications-
with-coding-and-design-patterns-55886614
ebooknice.com
(Ebook) Algorithmic Trading Systems and Strategies: A New Approach: Design, Build,
and Maintain by Viktoria Dolzhenko ISBN 9798868803567, 8868803569
https://ebooknice.com/product/algorithmic-trading-systems-and-strategies-a-new-
approach-design-build-and-maintain-58302764
ebooknice.com
(Ebook) Web Application Design and Implementation: Apache 2, PHP5, MySQL,
JavaScript, and Linux UNIX (Quantitative Software Engineering Series) by Steven A.
GabarrĂł ISBN 9780471773917, 0471773913
https://ebooknice.com/product/web-application-design-and-implementation-
apache-2-php5-mysql-javascript-and-linux-unix-quantitative-software-engineering-
series-2495740
ebooknice.com
(Ebook) JavaScript Domain-Driven Design_ Speed up your application development by
leveraging the patterns of domain-driven design by kan
https://ebooknice.com/product/javascript-domain-driven-design-speed-up-your-
application-development-by-leveraging-the-patterns-of-domain-driven-
design-50195404
ebooknice.com
(Ebook) Creating a Web Site: Design and Build Your First Site! by Greg Rickaby ISBN
9781119376514, 9781119376521, 9781119376538, 1119376513, 1119376521, 111937653X
https://ebooknice.com/product/creating-a-web-site-design-and-build-your-first-
site-11948782
ebooknice.com
8. Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – EBM – 20 19 18 17 16 15
9. Dedication
To Marian, for withstanding the birth of this book, your unconditional love,
and your endless patience.
I love you!
Will you marry me?
10. Brief Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Foreword
Preface
Acknowledgments
About this Book
About the Author
About the Cover Illustration
1. Build processes
Chapter 1. Introduction to Build First
Chapter 2. Composing build tasks and flows
Chapter 3. Mastering environments and the development workflow
Chapter 4. Release, deployment, and monitoring
2. Managing complexity
Chapter 5. Embracing modularity and dependency management
Chapter 6. Understanding asynchronous flow control methods in
JavaScript
Chapter 7. Leveraging the Model-View-Controller
Chapter 8. Testing JavaScript components
Chapter 9. REST API design and layered service architectures
Appendix A. Modules in Node.js
Appendix B. Introduction to Grunt
Appendix C. Picking your build tool
Appendix D. JavaScript code quality guide
12. Table of Contents
Copyright
Brief Table of Contents
Table of Contents
Foreword
Preface
Acknowledgments
About this Book
About the Author
About the Cover Illustration
1. Build processes
Chapter 1. Introduction to Build First
1.1. When things go wrong
1.1.1. How to lose $172,222 a second for 45 minutes
1.1.2. Build First
1.1.3. Rites of initiation
1.2. Planning ahead with Build First
1.2.1. Core principles in Build First
1.3. Build processes
Build
Deployment
Benefits of a Build Process
1.4. Handling application complexity and design
Modularity
Design
13. Asynchronous Code
Testing Practices
Practical design considerations
Build process
Design and Rest API
Battle testing
1.5. Diving into Build First
1.5.1. Keeping code quality in check
1.5.2. Lint in the command line
1.6. Summary
Chapter 2. Composing build tasks and flows
2.1. Introducing Grunt
2.1.1. Installing Grunt
2.1.2. Setting up your first Grunt task
2.1.3. Using Grunt to manage the build process
2.2. Preprocessing and static asset optimization
2.2.1. Discussing preprocessing
2.2.2. Doing LESS
2.2.3. Bundling static assets
2.2.4. Static asset minification
2.2.5. Implementing image sprites
2.3. Setting up code integrity
2.3.1. Cleaning up your working directory
2.3.2. Lint, lint, lint!
2.3.3. Automating unit testing
14. 2.4. Writing your first build task
2.5. Case study: database tasks
Two-way schema changes
Having a backup plan
2.6. Summary
Chapter 3. Mastering environments and the development workflow
3.1. Application environments
3.1.1. Configuring build distributions
3.1.2. Environment-level configuration
3.1.3. What’s so special about development?
3.2. Configuring environments
3.2.1. Storing configuration in a waterfall
3.2.2. Using encryption to harden environment configuration
security
3.2.3. Setting environment-level configuration at the OS level
3.2.4. Merging configuration as a waterfall in code
3.3. Automating tedious first-time setup tasks
3.4. Working in continuous development
3.4.1. Waste no time, use a watch!
3.4.2. Monitoring for changes to the Node app
3.4.3. A text editor that cares
3.4.4. Browser refresh is so Y2K
3.5. Summary
Chapter 4. Release, deployment, and monitoring
4.1. Releasing your application
15. 4.1.1. Image optimization
4.1.2. Static asset caching
4.1.3. Inlining critical above-the-fold CSS
4.1.4. Testing before a deployment
4.2. Predeployment operations
Predeployment operations
4.2.1. Semantic versioning
4.2.2. Using changelogs
4.2.3. Bumping changelogs
4.3. Deploying to Heroku
4.3.1. Deploying builds
4.3.2. Managing environments
4.4. Continuous integration
4.4.1. Hosted CI using Travis
4.4.2. Continuous deployments
4.5. Monitoring and diagnostics
4.5.1. Logging and notifications
4.5.2. Debugging Node applications
4.5.3. Adding performance analytics
4.5.4. Uptime and process management
4.6. Summary
2. Managing complexity
Chapter 5. Embracing modularity and dependency management
5.1. Working with code encapsulation
5.1.1. Understanding the Single Responsibility Principle
16. 5.1.2. Information hiding and interfaces
5.1.3. Scoping and this keyword
5.1.4. Strict mode
5.1.5. Variable hoisting
5.2. JavaScript modules
5.2.1. Closures and the module pattern
5.2.2. Prototypal modularity
5.2.3. CommonJS modules
5.3. Using dependency management
5.3.1. Dependency graphs
5.3.2. Introducing RequireJS
5.3.3. Browserify: CJS in the browser
5.3.4. The Angular way
5.4. Understanding package management
5.4.1. Introducing Bower
5.4.2. Big libraries, small components
5.4.3. Choosing the right module system
5.4.4. Learning about circular dependencies
5.5. Harmony: a glimpse of ECMAScript 6
5.5.1. Traceur as a Grunt task
5.5.2. Modules in Harmony
5.5.3. Let there be block scope
5.6. Summary
Chapter 6. Understanding asynchronous flow control methods in
JavaScript
6.1. Using callbacks
17. 6.1.1. Avoiding callback hell
6.1.2. Untangling the callback jumble
6.1.3. Requests upon requests
6.1.4. Asynchronous error handling
6.2. Using the async library
6.2.1. Waterfall, series, or parallel?
6.2.2. Asynchronous functional tasks
6.2.3. Asynchronous task queues
6.2.4. Flow composition and dynamic flows
6.3. Making Promises
6.3.1. Promise fundamentals
6.3.2. Chaining Promises
6.3.3. Controlling the flow
6.3.4. Handling rejected Promises
6.4. Understanding events
6.4.1. Events and the DOM
6.4.2. Creating your own event emitters
6.5. Glimpse of the future: ES6 generators
6.5.1. Creating your first generator
6.5.2. Asynchronicity and generators
6.6. Summary
Chapter 7. Leveraging the Model-View-Controller
7.1. jQuery isn’t enough
Code organization and jQuery
View templates
18. Using controllers
Models
Views
Controllers
Router
7.2. Model-View-Controller in JavaScript
7.2.1. Why Backbone?
7.2.2. Installing Backbone
7.2.3. Browserifying your Backbone module with Grunt
7.3. Introduction to Backbone
7.3.1. Backbone views
7.3.2. Creating Backbone models
7.3.3. Organizing models with Backbone collections
7.3.4. Adding Backbone routers
7.4. Case study: the shopping list
7.4.1. Starting with a static shopping list
7.4.2. This time with remove buttons
7.4.3. Adding items to your cart
7.4.4. Using inline editing
7.4.5. A service layer and view routing
7.5. Backbone and Rendr: server/client shared rendering
7.5.1. Diving into Rendr
7.5.2. Understanding boilerplate in Rendr
7.5.3. A simple Rendr application
7.6. Summary
Chapter 8. Testing JavaScript components
19. 8.1. JavaScript testing crash course
8.1.1. Logical units in isolation
8.1.2. Using the Test Anything Protocol (TAP)
8.1.3. Putting together our first unit test
8.1.4. Tape in the browser
8.1.5. Arrange, Act, Assert
8.1.6. Unit testing
8.1.7. Convenience over convention
8.1.8. Case study: unit testing an event emitter
8.1.9. Testing the event emitter
8.1.10. Testing for the .on method
8.1.11. Mocks, spies, and proxies
8.1.12. Mocking
8.1.13. Introducing Sinon.js
8.1.14. Spying on function calls
8.1.15. Proxying require calls
8.2. Testing in the browser
8.2.1. Faking XHR and server communication
8.2.2. Case study: testing DOM interaction
8.3. Case study: unit testing the MVC shopping list
8.3.1. Testing the view router
8.3.2. Testing validation on a view model
8.4. Automating Tape tests
8.4.1. Automating Tape tests for the browser
8.4.2. Continuous testing
8.5. Integration, visual, and performance testing
20. 8.5.1. Integration testing
8.5.2. Visual testing
8.5.3. Performance testing
8.6. Summary
Chapter 9. REST API design and layered service architectures
9.1. Avoiding API design pitfalls
9.2. Learning REST API design
9.2.1. Endpoints, HTTP verbs, and versioning
9.2.2. Requests, responses, and status codes
9.2.3. Paging, caching, and throttling
9.2.4. Documenting an API
9.3. Implementing layered service architectures
9.3.1. Routing layer
9.3.2. Service layer
9.3.3. Data layer
9.3.4. Routing layer
9.3.5. Service layer
9.3.6. Data layer
9.4. Consuming a REST API on the client side
9.4.1. The request handling layer
9.4.2. Shooting down old requests
9.4.3. Consistent AJAX error management
9.5. Summary
Appendix A. Modules in Node.js
A.1. Installing Node.js
21. A.2. The module system
A.3. Exporting functionality
A.4. Regarding packages
Appendix B. Introduction to Grunt
B.1. Grunt plugins
B.2. Tasks and targets
B.3. Command-line interface
B.4. Using Grunt in a project
B.5. Configuring Grunt
B.6. Globbing patterns
B.6.1. Brace expressions
B.6.2. Negation expressions
B.7. Setting up a task
B.8. Creating custom tasks
Appendix C. Picking your build tool
C.1. Grunt: the good parts
C.2. Grunt: the bad parts
C.3. npm as a build tool
C.3.1. Installing npm task dependencies
C.3.2. Using shell scripts in npm tasks
C.3.3. npm and Grunt compared: the good and the bad
C.4. Gulp: the streaming build tool
Running Tests in Gulp
Building a Library in Gulp
Appendix D. JavaScript code quality guide
D.1. Module organization
22. D.1.1. Strict mode
D.1.2. Spacing
D.1.3. Semicolons
D.1.4. Linting
D.2. Strings
Bad Strings
Good Strings
Better Strings
D.2.1. Variable declaration
D.3. Conditionals
Bad conditionals
Good conditionals
Bad coercing equality
Good strict equality
D.3.1. Ternary operators
D.3.2. Functions
D.3.3. Prototypes
D.3.4. Object literals
D.3.5. Array literals
D.4. Regular expressions
Bad regular expressions
Good regular expressions
D.4.1. Debugging statements
D.4.2. Comments
D.4.3. Variable naming
D.4.4. Polyfills
24. Foreword
The process of designing a robust JavaScript web app has gone through a roaring
renaissance in recent years. With the language being used to develop
increasingly ambitious apps and interfaces, this is the perfect time for JavaScript
Application Design. Through concise examples, lessons learned from the field,
and key concepts for scalable development, Nico Bevacqua will give you a
whirlwind tour of taking the process and design of your apps to the next level.
This book will also help you craft build processes that will save you time. Time
is a key factor in staying productive. As web app developers, we want to make
the most of ours, and a Build First philosophy can help us hit the ground running
with clean, testable apps that are well structured from the get-go. Learning
process workflow and how to manage complexity are fundamental cornerstones
of modern JavaScript app development. Getting them right can make a massive
difference in the long run.
JavaScript Application Design will walk you through automation for the front
end. It covers everything from avoiding repetitive tasks and monitoring
production builds to mitigating the cost of human error through a clean tooling
setup. Automation is a big factor here. If you aren’t using automation in your
workflow today, you’re working too hard. If a series of daily tasks can be
accomplished with a single command, follow Nico’s advice and spend the time
you save improving the code quality of your apps.
Modularity is the final crucial concept that can assist with building scalable,
maintainable apps. Not only does this help ensure that the pieces composing our
application can be more easily tested and documented, it encourages reuse and
focus on quality. In JavaScript Application Design, Nico expertly walks you
through writing modular JavaScript components, getting asyncronous flow right,
and enough client-side MVC for you to build an app of your own.
Strap on your seatbelts, adjust your command line, and enjoy a ride through the
process of improving your development workflow.
ADDY OSMANI
26. Preface
Like most people in our field, I’ve always been fascinated with problem solving.
The painful thrill of hunting for a solution, the exhilarating relief of having
found a fix—there’s nothing quite like it. When I was young I really enjoyed
strategy games, such as chess, which I’ve played ever since I was a kid;
StarCraft, a real-time strategy game I played for 10 years straight; and Magic:
The Gathering, a trading card game that can be described as the intersection
between poker and chess. They presented plenty of problem-solving
opportunities.
At primary school I learned Pascal and rudimentary Flash programming. I was
psyched. I would go on and learn Visual Basic, PHP, C, and start developing
websites, reaping the benefits of a masterful handle on <marquee> and
<blink> tags, paired with a modest understanding of MySQL; I was
unstoppable, but my thirst for problem solving didn’t end there, and I went back
to gaming.
Ultima Online (UO), a massively multiplayer online role-playing game (no
wonder they abbreviate that as MMORPG), wasn’t any different than other
games that got me hooked for years. Eventually I found out that there was an
open source[1] implementation of the UO server, which was named RunUO and
written entirely in C#. I played on a RunUO server where the administrators had
no programming experience. They slowly started trusting me to handle minor
bug fixes by literally emailing source code files back and forth. I was hooked.
C# was a wonderful, expressive language, and the open source software for the
UO server was amicable and inviting—you didn’t even need an IDE (or even
need to know what that was) because the server would compile script files
dynamically for you. You’d be essentially writing a file with 10 to 15 lines in it,
inheriting from the Dragon class, and adding an intimidating text bubble over
their head, or overriding a method so they’d spit more fireballs. You’d learn the
language and its syntax without even trying, simply by having fun!
1 You can check out the RunUO website at runuo.com, although the project isn’t maintained anymore.
Eventually, a friend revealed that I could make a living out of writing C# code:
“You know, people actually pay you to do that,” he said. That’s when I started
27. developing websites again, except I wasn’t using only Front Page and piles of
<marquee> tags or Java applets for fun anymore. It still feels like a game to
me, though.
A few years ago I read The Pragmatic Programmer[2], and something clicked.
The book has a lot of solid advice, and I can’t recommend it highly enough. One
thing that particularly affected me: the authors advocate you get out of your
comfort zone and try something you’ve been meaning to do but haven’t gotten
around to. My comfort zone was C# and ASP.NET at that point, so I decided to
try Node.js, an unmistakably UNIX-y platform for JavaScript development on
the server side, certainly a break from my Microsoft-ridden development
experience so far.
2 The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas
(Addison Wesley, 1999) is a timeless classic you should seriously consider reading.
I learned a ton from that experiment and ended up with a blog[3] where I’d write
about everything I learned in the process. About six months later I’d decided that
I’d put my years of experience in C# design into a book about JavaScript. I
contacted Manning, and they jumped at the opportunity, helping me brainstorm
and turn raw ideas into something more deliberate and concise.
3 You can read my blog, “Pony Foo,” at ponyfoo.com. I write articles about the web, performance,
progressive enhancement, and JavaScript.
This book is the result of many hours of hard work, dedication, and love for the
web. In it, you’ll find practical advice about application design, process
automation, and best practices that will improve the quality of your web projects.
28. Acknowledgments
You wouldn’t be holding this book in your hands if it weren’t for everyone who
supported and endured me throughout the writing process. I can only hope that
those who deserve acknowledgment the most, my friends and family, already
know that I can’t put into words how thankful I am for their love, understanding,
and frequent reassurance.
Many more people contributed—directly or indirectly—a great deal of wisdom
and inspiration to this book.
The open source JavaScript community is an endless spring of insight,
encouragement, and selfless contributions. They have opened my eyes to a better
approach to software development, where collaboration isn’t only possible, but
actively encouraged. Most of these people have contributed indirectly by
evangelizing for the web, maintaining blogs, sharing their experience and
resources, and otherwise educating me. Others have contributed directly by
developing tools discussed in the book. Among these individuals are Addy
Osmani, Chris Coyier, Guillermo Rauch, Harry Roberts, Ilya Grigorik, James
Halliday, John-David Dalton, Mathias Bynens, Max Ogden, Mikeal Rogers, Paul
Irish, Sindre Sorhus, and T.J. Holowaychuk.
There are also many book authors and content distributors who have influenced
and motivated me to become a better educator. Through their writing and
sharing, these people have significantly helped shape my career. They include
Adam Wiggins, Alan Cooper, Andrew Hunt, Axel Rauschmayer, Brad Frost,
Christian Heilmann, David Thomas, Donald Norman, Frederic Cambus,
Frederick Brooks, Jeff Atwood, Jeremy Keith, Jon Bentley, Nicholas C. Zakas,
Peter Cooper, Richard Feynmann, Steve Krug, Steve McConnell, and Vitaly
Friedman.
Susan Conant, my developmental editor at Manning, deserves to be singled out.
She held this book to the greatest standard of quality I could possibly create, and
it’s in much better shape than it would’ve been if not for her. On top of that, she
had to hand-hold me through the delicate and intimate process of writing my
first book. Through her relentless, yet gentle, guidance she helped shape my
lumps of ideas into a book that I’m not afraid to publish. I’ve become a better
29. writer because of her, and I’m grateful for that.
She wasn’t alone in that endeavor. All of the staff at Manning wanted this book
to be the best that it could be. The publisher, Marjan Bace—along with his
editorial collective—are to be thanked for that. Valentin Crettaz and Deepak
Vohra, the technical proofreaders, were not only instrumental in ensuring the
code samples were consistent and useful, but provided me with great feedback as
well.
There are also the hordes of anonymous souls that were willing to read through
the manuscript, leaving their impressions and helping improve the book. Thanks
to the MEAP readers who posted corrections and comments in the Author Online
forum, and to the reviewers who read the chapters at various stages of
development: Alberto Chiesa, Carl Mosca, Dominic Pettifer, Gavin Whyte, Hans
Donner, Ilias Ioannou, Jonas Bandi, Joseph White, Keith Webster, Matthew
Merkes, Richard Harriman, Sandeep Kumar Patel, Stephen Wakely, Torsten
Dinkheller, and Trevor Saunders.
Special thanks to Addy Osmani for contributing the foreword, and to everyone
else who played a part. Even if they didn’t make the keystrokes themselves, they
played an instrumental role in getting this book published, and one step closer to
you.
30. About this Book
Web development has grown out of proportion, and today it’s hard to imagine a
world without the web. The web is famously fault
tolerant. While traditional programming teaches us that missing a semicolon,
forgetting to add a closing tag, or declaring
invalid properties will have crippling consequences, the same cannot be said
about the web. The web is a place where it’s
okay to make mistakes, yet there’s increasingly less room for error. This
dichotomy stems from the fact that modern web applications
are an order of magnitude more complex than they used to be. During the
humble beginnings of the web, we would maybe modestly
make a minor change in web pages using JavaScript; whereas on the modern
web, entire sites are rendered in a single page,
powered by JavaScript.
JavaScript Application Design is your guide to a better modern web
development experience, one where you can develop maintainable JavaScript
applications
as you would if you were using any other language. You’ll learn how to leverage
automation as a replacement for tedious and
repetitive error-prone processes, how to design modular applications that are
easy to test, and how to test them.
Process automation is a critical time-saver across the board. Automation in the
development environment helps us focus our
efforts on thinking, writing code, and debugging. Automation helps ensure our
code works after every change that we publish
31. to version control. It saves time when preparing the application for production
by bundling, minifying assets, creating spritesheets,
and adding other performance optimization techniques. It also helps with
deployments by reducing risk and automating away
a complicated and error-prone process. Many books discuss processes and
automation when it comes to back-end languages, but
it’s much harder to find material on the subject when it comes to JavaScript-
driven applications.
The core value of JavaScript Application Design is quality. Automation gives
you a better environment in which to build your application, but that alone isn’t
enough: the
application itself needs to be quality conscious as well. To that end, the book
covers application design guidelines, starting
with a quick rundown of language-specific caveats, teaching you about the
power of modularity, helping you untangle asynchronous
code, develop client-side MVC applications, and write unit tests for your
JavaScript code.
This book relies on specific tools and framework versions, as books about web
technologies usually do, but it separates library-specific
concerns from the theory at hand. This is a concession to the fact that tooling
changes frequently in the fast-paced web development
arena, but design and the processes behind tooling tend to have a much slower
rhythm. Thanks to this separation of concerns,
I hope this book stays relevant for years to come.
32. Road map
JavaScript Application Design is broken into two parts and four appendixes. The
first part is dedicated to the Build First approach, what it is, and how
it can aid your everyday job. This part covers process automation in detail, from
everyday development to automated deployments,
as well as continuous integration and continuous deployments; it spans 4
chapters.
Chapter 1 describes the core principles that drive Build First, and the
different processes and flows you can set up. It then introduces
the application design guidelines that we’ll discuss throughout the book and
lays the foundation for the rest of the book.
In chapter 2 you learn about Grunt, and how you can use it to compose
build flows. Then we look at a few different build tasks that you
can easily perform using Grunt.
Chapter 3 is all about environments and the development workflow. You’ll
learn that not all environments are born the same, and how
you can prioritize debugging and productivity in the development
environment.
Chapter 4 walks you through the release flow and discusses deployments.
You’ll learn about a few more build tasks that are geared toward
33. performance optimization, and discover how to perform automated
deployments. You’ll also learn how to hook up continuous integration
and how to monitor your application once in production.
While part 1 is focused on building applications using Grunt, appendix C teaches
you to choose the best build tool for the job. Once you’ve read past part 1, you’ll
go into the second part of the book, which is dedicated to managing complexity
in your application designs. Modules,
MVC, asynchronous code flows, testing, and a well-designed API all play
significant roles in modern applications and are discussed
in the next chapters.
Chapter 5 focuses on developing modular JavaScript. It starts by expressing
what constitutes a module and how you can design applications
modularly and lists the benefits of doing so. Afterward, you’ll get a crash
course on lexical scoping and related quirks in
the JavaScript language. Later you get a rundown of the major ways to
attain modularity: RequireJS, CommonJS, and the upcoming
ES6 module system. The chapter concludes by going over different package
management solutions such as Bower and npm.
In chapter 6 you learn about asynchronous code flows. If you ever descend
into callback hell, this may be your way out. This chapter discusses
different approaches to deal with complexity in asynchronous code flows,
namely callbacks, Promises, events, and ES6 generators.
You’ll also learn how to do proper error handling under each of those
34. paradigms.
Chapter 7 starts by describing MVC architectures, and then ties them
specifically to the web. You’ll learn how you can use Backbone
to develop rich client-side applications that separate concerns using MVC.
Later, you’ll learn about Rendr, which can be used
to render Backbone views on the server side, optimizing the performance
and accessibility of your applications.
In chapter 8, now that your applications are modular, clean-cut, and
maintainable, you’ll take the next logical step and look into testing
your applications in different ways. To this end we’ll go over an assortment
of JavaScript testing tools and get hands-on
experience using them to test small components. Then we’ll go back to the
MVC application built in chapter 7 and add tests to it. You won’t be doing
unit testing only, you’ll also learn more about continuous integration, visual
testing,
and measuring performance.
Chapter 9 is the last chapter of the book, and it’s dedicated to REST API
design. This is the layer where the client side interacts
with the server, and it sets the scene for everything that we do in the
application. If the API is convoluted and complicated,
chances are the application as a whole will be as well. REST introduces
clear guidelines when designing an API, making sure
the API is concise. Last, we’ll look at consuming these services in the client
35. side in a conventional manner.
The appendixes can be read after you’re done with the book, but you’ll probably
get the most value from them by reading them
if you get stuck with the areas they cover, as they contain answers to questions
you might have. Throughout the book, you’ll
be pointed to the appendixes where it makes sense to expand a little on one of
these subjects.
Appendix A is a soft introduction to Node.js and its module system,
CommonJS. It’ll help you troubleshoot your Node.js installation
and answer a few questions on how CommonJS works.
Appendix B is a detailed introduction to Grunt. Whereas the chapters in
part I only explain what’s absolutely necessary about Grunt,
the appendix covers its inner workings in more detail, and will be handy if
you’re serious about developing a full-blown build
process using Grunt.
Appendix C makes it clear that this book is in no way married to Grunt, and
lists a couple of alternatives, Gulp and npm run. The appendix discusses
the pros and cons of each of the three tools, and leaves it up to you to
determine which one (if
any) fits your needs best.
36. Appendix D presents a JavaScript quality guide containing a myriad of best
practices you may choose to follow. The idea isn’t to force
those specific guidelines down your throat, but rather to arm you with the
idea that consistency is a good thing to enforce
throughout a code base when working in a development team.
37. Code conventions and downloads
All source code is in fixed-size width font like this, and
sometimes grouped under named code listings. Code annotations accompany
many of the listings, highlighting important
concepts. The source code for this book is open source and publicly hosted on
GitHub. You can download it by visiting github.com/buildfirst/buildfirst.
The online repository will always have the most up-to-date version of the
accompanying source code. While source code might
only be discussed at a glance in the book, it’s better documented in the
repository, and I encourage you to check out the
commented code there, if you run into trouble.
You can also download the code from the publisher’s website at
www.manning.com/JavaScriptApplicationDesign.
38. Author Online
Purchase of JavaScript Application Design includes free access to a private web
forum run by Manning Publications, where you can make comments about the
book, ask
technical questions, and receive help from the author and from other users. To
access the forum and subscribe to it, point
your web browser to www.manning.com/JavaScriptApplicationDesign. This
page provides information on how to get on the forum once you are registered,
what kind of help is available, and the
rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialogue between individual readers and between
readers and the author can take place. It is not a commitment to any specific
amount of participation on the part of the author,
whose contribution to the book’s forum remains voluntary (and unpaid). We
suggest you try asking the author some challenging
questions, lest his interest stray!
The Author Online forum and the archives of previous discussions will be
accessible from the publisher’s website as long as
the book is in print.
39. About the Author
Nicolas Bevacqua is an active member of the open source JavaScript
community, a freelance web developer, an occasional public speaker, and a
passionate writer. He maintains many open source projects and blogs about the
web, performance, progressive enhancement, and JavaScript development at
ponyfoo.com. Nico currently lives in Buenos Aires, Argentina, with his beautiful
girlfriend, Marian.
40. About the Cover Illustration
The figure on the cover of JavaScript Application Design is captioned “Winter
Habit of a Kamtchadal in 1760.” The Kamchatka Peninsula is the eastern-most
part of Russia, lying between the Pacific Ocean to the east and the Sea of
Okhotsk to the west. The illustration is taken from Thomas Jefferys’ A
Collection of the Dresses of Different Nations, Ancient and Modern, London,
published between 1757 and 1772. The title page states that these are hand-
colored copperplate engravings, heightened with gum arabic. Thomas Jefferys
(1719–1771) was called “Geographer to King George III.” He was an English
cartographer who was the leading map supplier of his day. He engraved and
printed maps for government and other official bodies and produced a wide
range of commercial maps and atlases, especially of North America. His work as
a mapmaker sparked an interest in local dress customs of the lands he surveyed
and mapped; they are brilliantly displayed in this four-volume collection.
Fascination with faraway lands and travel for pleasure were relatively new
phenomena in the eighteenth century and collections such as this one were
popular, introducing both the tourist as well as the armchair traveler to the
inhabitants of other countries. The diversity of the drawings in Jefferys’ volumes
speaks vividly of the uniqueness and individuality of the world’s nations
centuries ago. Dress codes have changed, and the diversity by region and
country, so rich at one time, has faded away. It is now often hard to tell the
inhabitant of one continent from another. Perhaps, trying to view it
optimistically, we have traded a cultural and visual diversity for a more varied
personal life—or a more varied and interesting intellectual and technical life.
At a time when it is hard to tell one computer book from another, Manning
celebrates the inventiveness and initiative of the computer business with book
covers based on the rich diversity of national costumes two and a half centuries
ago, brought back to life by Jefferys’ pictures.
41. Part 1. Build processes
The first part of this book is dedicated to build processes and provides a practical
introduction to Grunt. You’ll learn the why, how, and what of build processes,
both in theory and in practice.
In chapter 1, we go over what the Build First philosophy entails: a build process
and application complexity management. Then, we’ll start fiddling with our first
build task, using lint to prevent syntax errors in our code.
Chapter 2 is all about build tasks. You’ll learn about the various tasks that
comprise a build, how to configure them, and how to create your own tasks. In
each case, we’ll take a look at the theory and then walk through practical
examples using Grunt.
In chapter 3, we’ll learn how to configure application environments while
keeping sensitive information safe. We’ll go over the development environment
workflow, and you’ll learn how to automate the build step itself.
Chapter 4 then describes a few more tasks we need to take into account when
releasing our application, such as asset optimization and managing
documentation. You’ll learn about keeping code quality in check with
continuous integration, and we’ll also go through the motions of deploying an
application to a live environment.
42. Chapter 1. Introduction to Build First
This chapter covers
Identifying problems in modern application design
Defining Build First
Building processes
Managing complexity within applications
Developing an application properly can be hard. It takes planning. I’ve created
applications over a weekend, but that doesn’t mean they were well-designed.
Improvisation is great for throw-away prototypes and great when concept-
proofing an idea; however, building a maintainable application requires a plan,
the glue that holds together the features you currently have in mind and maybe
even those you might add in the near future. I’ve participated in countless
endeavors where the application’s frontend wasn’t all it could be.
Eventually, I realized that back-end services usually have an architect devoted to
their planning, design, and overview—and often it’s not one architect but an
entire team of them. This is hardly the case with frontend development, where a
developer is expected to prototype a working sketch of the application and then
asked to run with it, hoping that the prototype will survive an implementation in
production. Frontend development requires as much dedication to architecture
planning and design as back-end development does.
Long gone are the days when we’d copy a few snippets of code off the internet,
paste them in our page, and call it a day. Mashing together JavaScript code as an
afterthought no longer holds up to modern standards. JavaScript is now front and
center. We have many frameworks and libraries to choose from, which can help
you organize your code by allowing you to write small components rather than a
monolithic application. Maintainability isn’t something you can tack onto a code
base whenever you’d like; it’s something you have to build into the application,
and the philosophy under which the application is designed, from the beginning.
Writing an application that isn’t designed to be maintainable translates into
stacking feature after feature in an ever-so-slightly tilting Jenga tower.
43. If maintainability isn’t built in, it gets to a point where you can’t add any more
pieces to the tower. The code becomes convoluted and bugs become increasingly
hard to track down. Refactoring means halting product development, and the
business can’t afford that. The release schedule must be maintained, and letting
the tower come crashing down is unacceptable, so we compromise.
44. 1.1. When things go wrong
You might want to deploy a new feature to production, so humans can try it out.
How many steps do you have to take to do that? Eight? Five? Why would you
risk a mistake in a routine task such as a deployment? Deploying should be no
different than building your application locally. One step. That’s it.
Unfortunately that’s rarely the standard. Have you faced the challenging position
I’ve found myself in of having to take many of these steps manually? Sure, you
can compile the application in a single step, or you might use an interpreted
server-side language that doesn’t need any pre-compilation. Maybe later you
need to update your database to the latest version. You may have even created a
script for those updates, and yet you log into your database server, upload the
file, and run the schema updates yourself.
Cool, you’ve updated the database; however, something’s not right and the
application is throwing an error. You look at the clock. Your application has been
down for more than 10 minutes. This should’ve been a straightforward update.
You check the logs; you forgot to add that new variable to your configuration
file. Silly! You add it promptly, mumbling something about wrestling with the
code base. You forget to alter the config file before it deploys; it slipped your
mind to update it before deploying to production!
Sound like a familiar ritual? Fear not, this is an unfortunately common illness,
spread through different applications. Consider the crisis scenarios described
next.
1.1.1. How to lose $172,222 a second for 45 minutes
I bet you’d consider losing almost half a billion dollars a serious issue, and that’s
exactly what happened to Knight’s Capital.[1] They developed a new feature to
allow stock traders to participate in something called the Retail Liquidity
Program (RLP). The RLP functionality was intended to replace an unused piece
of functionality called Power Peg (PP), which had been discontinued for close to
nine years. The RLP code reused a flag, which was used to activate the PP code.
They removed the Power Peg feature when they added RLP, so all was good. Or
45. at least they thought it was good, until the point when they flipped the switch.
1
For more information about Knight’s Capital, see http://bevacqua.io/bf/knight.
Deployments had no formal process and were executed by hand by a single
technician. This person forgot to deploy the code changes to one of their eight
servers, meaning that in the case of the eighth server, the PP code, and not the
RLP feature, would be behind the activation flag. They didn’t notice anything
wrong until a week later when they turned on the flag, activating RLP on all
servers but one, and the nine-year-old Power Peg feature on the other.
Orders routed through the eighth server triggered the PP code rather than RLP.
As a result, the wrong types of orders were sent to trading centers. Attempts to
amend the situation only further aggravated it, because they removed the RLP
code from the servers which did have it. Long story short, they lost somewhere
in the vicinity of $460 million in less than an hour. When you consider that all
they needed to do to avoid their downfall was have a more formal build process
in place, the whole situation feels outrageous, irresponsible, and, in retrospect,
easily averted. Granted, this is an extreme case, but it boldly illustrates the point.
An automated process would have increased the probability that human errors
could be prevented or at least detected sooner.
1.1.2. Build First
In this book, my goal is to teach you the Build First philosophy of designing for
clean, well-structured, and testable applications before you write a single line of
code. You’ll learn about process automation, which will mitigate the odds of
human error, such as those leading to Knight’s Capital’s bankruptcy. Build First
is the foundation that will empower you to design clean, well-structured, and
testable applications, which are easy to maintain and refactor. Those are the two
fundamental aspects of Build First: process automation and design.
To teach you the Build First approach, this book will show you techniques that
will improve the quality of your software as well as your web development
workflow. In Part 1, we’ll begin by learning how to establish build processes
appropriate for modern web application development. Then, you’ll walk through
best practices for productive day-to-day development, such as running tasks
when your code changes, deploying applications from your terminal by entering
46. a single command, and monitoring the state of your application once it’s in
production.
The second part of the book—managing complexity and design—focuses on
application quality. Here I give you an introduction to writing more modular
JavaScript components by comparing the different options that are currently
available. Asynchronous flows in JavaScript tend to grow in complexity and
length, which is why I prepared a chapter where you’ll gain insight into writing
cleaner asynchronous code while learning about different tools you can use to
improve that code. Using Backbone as your gateway drug of choice, you’ll learn
enough about MVC in JavaScript to get you started on the path to client-side
MVC. I mentioned testable applications are important, and while modularity is a
great first step in the right direction, testing merits a chapter of its own. The last
chapter dissects a popular API design mentality denominated REST
(Representational State Transfer), helping you design your own, as well as
delving into application architecture on the server side, but always keeping an
eye on the front end. We’ll begin our exploration of build processes after looking
at one more crisis scenario Build First can avert by automating your process.
1.1.3. Rites of initiation
Complicated setup procedures, such as when new team members come onboard,
are also a sign you may be lacking in the automation department. Much to my
torment, I’ve worked on projects where getting a development environment
working for the first time took a week. A full week before you can even begin to
fathom what the code does.
Download approximately 60 gigabytes worth of database backups, create a
database configuring things you’ve never heard of before, such as collation, and
then run a series of schema upgrade scripts that don’t quite work. Once you’ve
figured that out, you might want to patch your Windows Media Player by
installing specific and extremely outdated codecs in your environment, which
will feel as futile as attempts to cram a pig into a stuffed refrigerator.
Last, try compiling the 130+ project monolith in a single pass while you grab a
cup of coffee. Oh, but you forgot to install the external dependencies; that’ll do
it. Nope, wait, you also need to compile a C++ program so codecs will work
again. Compile again, and another 20 minutes go by. Still failing? Shoot. Ask
47. around, maybe? Well, nobody truly knows. All of them went through that
excruciating process when they started out, and they erased the memory from
their minds. Check out the wiki? Sure, but it’s all over the place. It has bits of
information here and there, but they don’t address your specific problems.
The company never had a formal initiation workflow, and as things started to
pile up, it became increasingly hard to put one together. They had to deal with
giant backups, upgrades, codecs, multiple services required by the website, and
compiling the project took half an hour for every semicolon you changed. If
they’d automated these steps from the beginning, like we’ll do in Build First, the
process would’ve been that much smoother.
Both the Knight’s Capital debacle and the overly complicated setup story have
one thing in common: if they’d planned ahead and automated their build and
deployment processes, their issues would’ve been averted. Planning ahead and
automating the processes surrounding your applications are fundamental aspects
of the Build First philosophy, as you’ll learn in the next section.
48. 1.2. Planning ahead with Build First
In the case of Knight’s Capital, where they forgot to deploy code to one of the
production web servers, having a single-step deployment process that
automatically deployed the code to the whole web farm would’ve been enough
to save the company from bankruptcy. The deeper issue in this case was code
quality, because they had unused pieces of code sitting around in their code base
for almost 10 years.
A complete refactor that doesn’t provide any functional gains isn’t appealing to a
product manager; their goal is to improve the visible, consumer-facing product,
not the underlying software. Instead, you can continuously improve the average
quality of code in your project by progressively improving the code base and
refactoring code as you touch it, writing tests that cover the refactored
functionality, and wrapping legacy code in interfaces, so you can refactor later.
Refactoring won’t do the trick on its own, though. Good design that’s ingrained
into the project from its inception is much more likely to stick, rather than
attempts to tack it onto a poor structure as an afterthought. Design is the other
fundamental aspect of the book, along with build processes mentioned
previously.
Before we dive into the uncharted terrains of Build First, I want to mention this
isn’t a set of principles that only apply to JavaScript. For the most part, people
usually associate these principles with back-end languages, such as Java, C#, or
PHP, but here I’m applying them to the development process for JavaScript
applications. As I mentioned previously, client-side code often doesn’t get the
love and respect it deserves. That often means broken code because we lack
proper testing, or a code base that’s hard to read and maintain. The product (and
developer productivity) suffers as a result.
When it comes to JavaScript, given that interpreted languages don’t need a
compiler, naive developers might think that’s justification enough to ditch the
build process entirely. The problem when going down that road is that they’ll be
shooting in the dark: the developer won’t know whether the code works until it’s
executed by a browser, and won’t know whether it does what it’s expected to,
49. either. Later on, they might find themselves manually deploying to a hosting
environment and logging into it remotely to tweak a few configuration settings
to make it work.
1.2.1. Core principles in Build First
At its core, the Build First approach encourages establishing not only a build
process but also clean application design. The following list shows at a high
level what embracing the Build First approach gives us:
Reduced error proclivity because there’s no human interaction
Enhanced productivity by automating repetitive tasks
Modular, scalable application design
Testability and maintainability by shrinking complexity
Releases that conform to performance best practices
Deployed code that’s always tested before a release
Looking at figure 1.1, starting with the top row and moving down, you can see
Build process: This is where you compile and test the application in an
automated fashion. The build can be aimed at facilitating continuous
development or tuned for maximum performance for a release.
Design: You’ll spend most of your time here, coding and augmenting the
architecture as you go. While you’re at it, you might refactor your code and
update the tests to ensure components work as expected. Whenever you’re
not tweaking the build process or getting ready for a deployment, you’ll be
designing and iterating on the code base for your application.
Deployment and Environment: These are concerned with automating the
release process and configuring the different hosted environments. The
deployment process is in charge of delivering your changes to the hosted
environment, while environment configuration defines the environment and
the services—or databases—it interacts with, at a high level.
Figure 1.1. High-level view of the four areas of focus in Build First: Build process, Design,
Deployment, and Environment
51. LETTER No. VIII.
His governor's visit to Hot Springs, a contretemps
with a British Lord, together with
experiences with a few physicians,
inspire Pierrepont's pen.
Chicago, Jan. 23, 189—
Dear Pa:
There's no doubt that the Hot Springs are great for a good many
ailments, and I'm glad you are improving. Professor Plexus, our old
instructor in calisthenics at Harvard, used to take the trip to
Arkansas with John L. Sullivan, twice a year, and they both said the
treatment was fine. I don't think Sullivan had rheumatism, but your
case may not be the same as his, and the scalding process will
probably do you more good than it does a regular Graham hog. The
boys around the office laugh considerably when they mention you
and the Hot Springs, which makes me rather warm under the collar,
for I can't stand having a father of mine misapprehended. I know
you for what you are, but they know you for what they think you
are, and provisional knowledge, you know, goes a long ways in the
provision business.
Speaking of the Hot Springs reminds me of a story Professor Plexus
used to tell about the Arkansas boiling vats. According to him, there
used to be a morgue connected with the establishment, for the use
of those who were unlucky enough to succumb to the treatment. An
old Irishman was the general factotum of the place, and it happened
that he was afflicted with a bronchial disturbance that was the envy
of every cougher who visited the spot. Meeting him one day in the
abode of the departed, one of the doctors remarked to him, on
hearing a particularly sepulchral wheeze:
52. "Pat, I wouldn't have your cough for five hundred dollars."
"Is thot so, sorr?" retorted the son of Erin. "Well," pointing with his
thumb to the inner room where the departed patients lay on slabs
covered with sheets, "they's a felly in there who wud give five
t'ousand uf he cud hav ut."
I simply mention this little incident in passing to show that all of us
prefer the ills we have to those we know not of. I would rather be a
mailing clerk at eight per than a free man working freight trains for
transportation and relying on hand-outs for sustenance in place of
Ma's frugal, but certain table d'hĂ´te.
I sincerely trust, sir, that your trip to the Springs will do you the
anticipated good. Billy Poindexter says—(by the way, I guess you
didn't know he was back from the Klondike. Not exactly that, either,
for he didn't reach the Klondike. The nearest he got to it was on the
map he bought while he was here. He went no farther than San
Francisco. His only object in starting for the Yukon, he says, was to
see if he couldn't pick up a good thing or two, and as he found them
in 'Frisco he stayed there.) He was much concerned about you when
I told him you had gone to the Springs.
"Too bad for your governor," he said. "He must suffer terribly with
them."
"With them?" I asked. "With what?"
"Why, boils, of course. What would he go to the Hot Springs for, if
not for boils?"
It cost me five minutes' time in a very busy evening to find out that
he had made a very bad joke, a paranomasia as we called it in
college; in other words, a pun or play upon words. I've advised Billy
to publish a chart of this joke. If he does I'll send you one. He says
I'm as dense as that English lord who visited the works while you
were away last fall.
53. Apropos, we met him—the lord—the other night. We were having a
bite to eat at a rathskeller after the theatre when "his ludship"
wandered in. He was built up regardless, with an Inverness coat
with grey plaids, that looked like a country-bred rag carpet. It was
the real thing, of course, and I made up my mind to save the four
dollars that have been added to my stipend until I could get one like
it. I decided, however, that I shall not make my possession of it
public until he has left the country. I should really hate to be
mistaken for him. I even prefer to be known as connected with your
business.
Strange to say, when "his ludship" reached our table, he halted
uncertainly as he saw me, and then stepped forward.
"You'll—aw—pawdon me, doncherknow, but—aw—is not this—aw—
young Mr.—aw—Graham?"
I pleaded guilty, with a mental plea for mercy, and the next thing I
knew his dukelets had made his monocle a part of the set-up of our
table. I was very much embarrassed, for I didn't know how to
introduce him to Billy. But his earlship quickly backed me out of that
corner by calling Billy by name.
"Yaas, old chap," he was saying, "I met you—aw—at the Ring Club,
doncherknow."
Billy didn't know, because his sight is often very bad, especially at
the Ring Club. So the Marquis gave his memory a push.
"I'm Fitz-Herbert," he said.
This gave us the route, for his picture has several times filled up
space between breakfast food ads. in the newspapers. Not that he
ever seems to do anything; he's always being done for, as the guest
of this, that and the other. He was desperately civil, wouldn't have us
"Lord Percying" him, he said. So it was plain Percy after that and
"plain Percy" he surely is. A homelier man I've never seen outside
the comic weeklies. It would be great if you could hire him, dad, to
56. The Son's College Girl.
I think I ought to tell you that Ma is getting uneasy about you. She
even goes so far as to say that she takes no stock in the Hot Springs
business, but thinks you are in St. Louis, having a deuce of a time. I
can't see why she should be so suspicious. When I showed her the
57. postmark on your letter, she sniffed and said it was easy enough to
get some one to mail it from the Arkansas boiling-out place. She
threatens to start for St. Louis in a day or two if you don't show up,
which might be a pretty good thing, for I could telegraph you as
soon as she left, and you could be at home when she returned, and
give her the grand laugh. It's a wise wife who doesn't know her own
husband, after all.
I am getting into the social swim with both hands and feet, spite of
our business. Made a great hit at the De Porque's the other night.
The girls are getting up a new dancing association and wanted me
to name it—because I was a Harvard man. I told them to call it the
St. Vitus Club, and you ought to have seen their faces.
I regret to learn that you are in the hands of a specialist. I had one
of that brand of doctors when I had the grippe at Cambridge. I grew
worse suddenly one night, and as my chum couldn't reach the
regular physician by 'phone he called in another. He had not been in
the room three minutes when doctor No. 1 drew alongside. They
were painfully cordial and had what they called a consultation. My
chum said it was a fight. At all events they decided that a specialist
be called. I was feeling better by that time and began to take notice.
From what I saw then and have since learned from others similarly
afflicted I gather that a specialist always wears gloves and a beard
and speaks with great deliberation and gravity. After feeling my
pulse with excessive care, he turned to each of the medical men in
turn and inquired what they had done and recommended. To each
statement he muttered, "Very good," or "That is well," although the
two regulars had failed to agree on any point. The other two doctors
went away, with lingering glances, as if they hated to give me up.
Then the specialist came out strong. "This young man," he said
slowly and impressively, "has the grippe. You will continue his
medicines regularly to-night—mark me, regularly. I will prescribe for
him in the morning—in the morning." Then he walked out. When he
called in the morning I had done the same thing—walked out. I felt
a moral certainty that if he got after me I should eventually have to
58. be carried out. The bunco business is not confined to gentlemen
with beetle brows, big moustaches and checked trousers.
But doctors have their troubles—the conscientious ones. Doc
Mildmay—my chum Frank's brother, you know—once had an
experience with a chronic invalid—one of the kind that change their
doctor and their disease every two weeks—that was an eye-opener.
A nervous, choleric old man sent for him. He was chock full of
symptoms and his conversation sounded like a patent medicine
folder. He wound up thusly: "When I go upstairs or up a hill I find
difficulty in breathing and often get a stitch in the side. These
conditions, doctor, denote a threatening affection of the heart."
Mildmay, finding the old fellow fat and thick-necked, decided he was
a too liberal feeder, so, with a desire to set his fears at rest, he said:
"I trust not. These are by no means necessary symptoms of heart
trouble." Here the old man switched in, glaring at Mildmay. "I am
sorry, sir," he said fiercely, "to note such lack of discretion. How can
you presume to differ with me as to the significance of my
symptoms? You, a young physician, and I an old and—well, I may
say, a seasoned, experienced invalid."
Doc needed a fee badly enough, but just then needed the air more
and got out.
Ma might send her love if I asked her, but I guess you'd better trim
ship for the home anchorage.
Dutifully, Pierrepont.
P.S. I've just learned that Lord Percy Fitz-Herbert's engagement to
Millicent Wheatleigh has been broken off. It seems she refused to
marry him because of his family. It was a wife and three children in
Maine, which is the nearest he's known to have ever been to
London.
60. LETTER No. IX.
Pierrepont gives his Pa a line on the up-to-date
methods of courtship, relates an episode of
calf-love and has a fling at matrimonial
adages.
Chicago, Feb. 10, 189—
Dear Father:
I realize that you mean well by me and I accept your advice on
courtship, love and marriage, and all that rot, in the spirit in which it
is given. But really, my dear pater, you are hopelessly in arrears in
your information on those subjects. Of course you know a lot about
marriage. I cannot dispute that; it is too obvious; but in matters of
courtship detail you are back in the stagecoach age, hopelessly old
style.
Nowadays, if a fellow is "spoons" on a girl he makes it public in quite
different fashion than when you "sparked Ma"—as you rather
vulgarly, as it seems to me, express it. Methods have changed since
your salad days, when courtship consisted of escorting the same girl
home from singing school three weeks running and then going in the
cherished "best suit" to "keep company" with her one or two
evenings a week. The modern swain has an entirely different
system, although I grant you that he makes an ass of himself quite
as much as his predecessors. There is no more sitting in the back
parlor with the gas low. All reputable back parlors are electrically
illuminated and the situation is therefore changed. I do not say,
however, that lamps are not sometimes provided by thoughtful
parents of large families of daughters of marriageable age. The
average young man, however, would regard the presence of a lamp
in such circumstances as a danger signal, and run on to the first
61. siding. No eligible young man likes to feel that he is walking into a
specially set matrimonial trap.
As you may judge from the florist's bill brought to your attention,
Cupid, nowadays, is very partial to flowers. In your day a straw ride
once or twice a winter, a few glasses of lemonade or plates of ice-
cream, and church sociables and picnics were about the only
obligations attendant upon making a girl think herself your particular
one. To-day hot-house roses and violets, boxes of chocolate,
appreciated only when expensively trade-marked, matinee tickets,
auto rides, dainty luncheons with chaperons on the side—but I could
fill two pages in enumeration of the little, but expensive attentions
which the up-to-date city girl demands. And all these things may
mean much or little. Because a fellow runs up a florist's bill is no
sign that his next purchase will be an engagement ring. Lots of
fellows with lots of money buy lots of things for lots of nice girls and
no questions asked. You certainly don't want your only son and heir
to be a rank outsider.
As a matter of fact, the joke is on you in regard to that bill of $52 for
roses sent to Mabel Dashkam and charged up to me. To be sure, I
don't quite see how the thing reached you at the Springs. Pollen &
Stalk ought to be called down good and plenty for chasing you
around the country with a thing they should have known you took
no interest in. It reflects on me, and I'll see that such a gross insult
isn't repeated. But about the joke. I didn't send the roses to Mabel
Dashkam at all. Since dallying with hogs I seem to have acquired an
improved taste in girls, and her face doesn't warm me in the least.
The fact is that little Bud Hoover, who is just at present in town,
living a life of mysterious ease, has conceived the idea that he could
stand being Job Dashkam's son-in-law. He thinks there is a gold
mine in the old man's backyard, evidently; he isn't at all afraid that
Job will ever borrow money of him—and he's right there.
Well, it came around to Mabel's birthday, and Bud, who'd been doing
the grand social at the house for some time, saw that it was up to
him to celebrate the occasion with a "trifling nosegay," as he put it.
62. He nailed me for the wherewithal, urging that I was in duty bound to
help a struggling young man to a position. When I couldn't quite
focus my approval on that proposition, he declared that I owed the
service to him because his grandfather had saved my father's soul.
That was a clincher, and I let him get the roses and charge 'em to
me. As you say, most young fellows who explode fifty-two for
flowers at one blast will wish they had the money for provisions
some time or other. Not so with Bud, however; he never can be
poorer than he is now, and he calculates to eat on Job for the rest of
his natural life. There's a good deal of his grandfather in Bud.
You needn't worry about my acquaintance with Mabel. She's bully
good sort and always ready for a good time in good company. But
just because a fellow is civil to her doesn't jump her to the
conclusion that he sits up nights trying to fit her name into metre.
That's what I like about her. A fellow can invite her to go golfing
without any danger of her knocking the ball into the first grove she
sights that looks suitable for a proposal. The girls are not as dead
crazy to marry as they were when you were young; I have proof
positive of this. Even mother admits that it is true.
Your matrimonial adages and observations please me quite
considerably, dear father. It's a long time since you had your little
fling with Cupid, and the world has moved a bit since then, but at
the same time you strike twelve pretty often. You warn me against
marrying a poor girl who's been raised like a rich one; I can think of
but one thing worse, and that's marrying a rich girl who's been
raised like a poor one. And what you say about picking out a good-
looking wife is eminently sane, if not always practicable. I'm bound
to observe, however, that if you'd put your theory into practice when
you married, I'd probably be a good bit handsomer than I am. As for
Mabel, she wouldn't marry me if I could move the whole Graham
plant into her father's backyard on the wedding morning. Her
father's curbstone brokerage in wheat may not be as high-class or as
remunerative as trying out hog fat, but it's certainly less malodorous.
63. Besides, Mabel has aspirations. Although I am not in her confidence,
she is known as committed to the theory that love in a cottage—or
its municipal equivalent, a flat—is an obsolete form of existence. The
legitimate inference is that the eligible men who are several times
millionaires in their own right had better wear smoked glasses when
they get up against Mabel. Marriage, to date, does not appeal to me
strongly. I hope to trot quite a number of speedy miles alone before
I have to slow down under a double hitch. Naturally, considering the
fact that I am your son and in view of your business, I have not
escaped a few attacks of "calf love." I suppose it is as inevitable as
the measles.
The worse case I ever had was when, in my first year at Cambridge,
I made desperate love to the accompanist who banged the piano for
the Glee Club rehearsals. She was a widow with a small child who
always accompanied her, and her desolateness appeared to touch a
hidden, sympathetic chord in my nature. Whatever the cause, I was
dippy for fair. I fairly bombarded her with music, and the kid must
have thought me an edition de luxe of Santa Claus. It's only fair to
say that she seemed to try to avoid me, but I was not to be turned
aside. I insisted on seeing her to her door after rehearsals, and then
stood under her window for hours, like a cross between a hitching
post and a jackass. She was courteous, almost maternal, in her
attitude towards me. The boys said she was thirty-five, but I scorned
them. What was age to love, which is eternity.
Sometimes she smiled at me and I bounded up into the seventh
heaven, although I often wondered if she was only too well-bred not
to laugh outright. (Her father and husband had both been connected
with Harvard.) She was pretty; I have no doubt of that, even now;
but her hair was flaming red. I called it Titian then, but love is color-
blind with all the rest. The "fatal day" came in about six weeks. I
proposed in the front hall of her boarding-house and she took me
into the parlor and closed the door. That would have been the
overture to a breach-of-promise suit or a Dakota divorce purchased
by my loving papa, if she had been some women, but she wasn't.
64. She thanked me for the honor—I have since realized that she was
not afraid of a white lie—and then she began to try to argue me out
of it. She referred to the disparity in our ages, to her widowhood and
my youth, to the difference in our stations, etc. Of course I pooh-
poohed it all and vowed everlasting devotion. I dimly recollect that I
made some mention of the Charles River. After I had delivered a
passionate oration that would have given a long-time discount to
Demosthenes and Romeo rolled into one, she looked at me
searchingly a moment and then rose and said:
"Very well, I will marry you—on one condition."
What were conditions to me? I—you know, just the usual. I wanted
to name the day then and there, and the next day at that, but she
insisted upon the condition.
"I will go to my room," she said, "and put the condition in writing,
that there may never be any doubt in the future."
When she returned she placed in my hand a sealed envelope and
exacted a pledge that I would not open it until I reached my room.
"If, when you know the condition," she said at parting, "you are still
determined on marriage, you will find me in till noon to-morrow."
I ran all the way to the dormitory, and when I reached my rooms I
was so nervous that it took me five minutes to unlock the door and
five more to light a match. Then I sat down at my study table,—for
the first time in some weeks—tore open the envelope, spread out
the single sheet of paper it contained, and read:
"The condition upon which I will entertain an offer of marriage from
you is this: I am, unfortunately, unduly sensitive about the color of
my hair. Will you dye yours the same red to keep me in
countenance?"
I scarcely imagine she waited till noon the next day,—that is, if she
had anything to do. She probably explained to the kid that Santa
Claus had died suddenly. I didn't recover my self-respect nor my
65. common sense for a week. When I did I sent her a box of flowers
and enclosed a note in which I said that ever afterwards I should
regard red hair as the accompaniment of strong common sense.
As for now, there is scarcely any danger, as you suggest, of a girl
marrying me for your money—that is, if she has seen you. You look
as if you were a goodly representative of a line of ancestors dating
back to the original Methusalah. Natural demise is evidently afar off,
and really there is nothing about you to suggest that you are likely
to blow out the gas in the next hotel you stop at.
As for love, I've none of the symptoms. There isn't a girl in Chicago
who can boast that I've let her beat me at golf. Almost all girls are
all right to meet occasionally, but when you're picking one to sit
opposite you at breakfast every morning you want to be sure you
will get one who will not take away your appetite. It's safer, I
believe, to select a wife for what she is not rather than for what she
is. Al Packard—you know him—with his father on the Board of Trade
—married his wife, Sophie Trent, because she was a brilliant
conversationalist. Now he has applied for a divorce for the same
reason. A man and his wife should be one, of course, but the
question often is, which one? It is rather trying to the male
disposition to have the wife the one and the husband the cipher on
the other side of the plus sign.
That you may feel more confidence in me, I will make a confession.
I was a bit smitten last fall. I won't tell the girl's name. She had
really done nothing to encourage me. I called one afternoon and her
little sister received me and said, "Sister's out."
"Tell her I called, Susie, will you?"
"I did," she smiled back.
That ended my pool-selling on that race.
You don't say anything about your condition at the Vattery, nor when
you are coming home. You needn't hurry, necessarily, for Ma's
66. disquiet about your whereabouts has quite disappeared. It seems
that old Wheatleigh, who bobbed up at the house the other night,
must have divined her suspicions, for he remarked casually that he'd
just seen you at the Hot Springs and that you were looking out of
sight. The odd part of it was that he hadn't been anywhere near
Arkansas. It's curious how a woman will believe all men but her own
husband.
I think I must be making a hit at this billing business, for I hear a
rumor about the place that I'm to be sent out collecting. I sincerely
hope you'll use what influence you've got to prevent this, for I can't
even collect my thoughts in this porkery, much less gather in
accounts due it outside. I'm afraid I've got too much conscience to
face debtors to Graham & Co.
Your heartwhole son,
P.
P.S.—Talking about women suggests that I tell you that old Mrs. De
Lancey Cartwright is evidently heartbroken over her husband's loss,
although he's been dead six months. Her mourning is so deep that
her hair has turned black again.
LETTER NO. X.
67. LETTER No. X.
First experiences "on the road" inspire little
confidence on the part of Pierrepont either
in himself, the Graham goods, or
country hotels.
Fosterville, Ind., March 4, 189—
My Dear Father:
Although I have not succeeded to date in getting far enough from
Chicago to escape the odors of your refinery and have yet to
ascertain how a man looks when he gives an order, I feel that I am
going to like being a drummer. There is a certain independence
about it which pleases me. While I, of course, shall labor early and
late in the interests of the house, there is a great deal in not having
a time-keeper staring you in the face every morning. The call left at
the hotel office is sufficient reminder to me of the flight of time,
especially after I have sat up till 4 A.M. trying to make things come
my way. I may not, as you hint, be cut out by the Lord for a
drummer. In fact, I don't believe I was, for from what I have seen of
the species I am of the belief that the Lord does not number its
manufacture among His responsibilities. At all events it is sufficient
for me to know that you, the head of the house, have selected me
as one.
Let me reassure you on one point. I may have looked chesty and
important when I started from Chicago the other morning, but my
experience as a drummer for Graham & Co. has so completely
knocked the self-esteem out of me that I don't believe my hat will
ever cock on one side again. It's all right enough to sit in the office
and talk about the big business you have built, but just get out into
the world and stack up against the fact that you've got to sell our
68. stuff to suspicious buyers or lose your job, and you'll find yourself a
first-class understudy for Moses in short order.
The first two days out I felt so proud of the house that I added
"Graham & Co." to my name on the hotel register. But I dropped
that little flourish just as soon as I saw that it got me the worst room
on the key-rack and the toughest steak in the dining-room. What on
earth have we been doing to people for the last thirty years that
makes them all down on us? I see that I'm going to have no trouble
in making the concern known; in fact, if I may venture to say so, it
seems to be too well known.
For some reasons I regret leaving the house. Business may go on
well enough in my absence, but it's a mighty poor fiddler who thinks
the orchestra plays as loud as it did before he breaks a string. I
thank you for your hints as to methods in soliciting trade, but I also
appreciate the truth that, after all, the man on the spot must give
the decision. So far, I see no reason for your belief that a fund of
anecdote is not necessary to the commercial traveller. (I may say in
passing that I much prefer this phrase to drummer, although I am
prepared to admit that after I sell a bill of goods I may be ready to
accept any title.) Jokes may not be profitable as the main stock in
trade, but they are certainly essential as a side line.
So far, I have been utterly unable to get up early enough in the
morning to reach a customer before he has fallen into the clutches
of one or more of my competitors, and when I arrive they are
usually so hilarious over funny stories that business—especially
serious business, like the buying of our products—is the thing
farthest from their thoughts. Because a man who wanted to sell you
a dog once indulged in flippant, but you must admit, clever repartee
about your needing such things in your business, you must not draw
the inference that the sense of humor has entirely departed from
storekeepers.
Of course the joke must not be on the prospective customer, as was
that of the dog fancier in your case. I found that out to my sorrow
69. the other day. I had almost persuaded a country grocer to try a
couple of pails of lard and a ham—not munificent, but a beginning—
when I tipped the fat into the fire by being over keen to take a joke.
A small boy came running in with a wad of paper, apparently
containing money, clutched in one fist and a card in the other hand.
"How much is ten pounds of sugar at 5½ cents a pound?" he asked.
"Fifty-five cents," said the grocer.
"And a quarter of a pound of 60-cent tea?"
"Fifteen cents—to your mother"—smiled the grocer.
"And a half peck of potatoes at 28 cents a peck?" asked the boy.
"Fourteen," said the grocer.
"And four cans of tomatoes at 12½ cents each," said the boy,
consulting his list.
"Just fifty cents," said the grocer.
"And six pounds of rice at 3½ cents?"
"Twenty-one cents. Is that all?" asked the grocer, as the boy put his
card in his pocket.
"Yes," said the boy; "what does it all cost?"
The grocer figured with a bit of charcoal on a bag and said: "A dollar
fifty-five. Will you take the package?"
"Nope," said the boy, edging towards the door. "I'm on my way to
school."
"Very well, I'll send it right up," said the grocer, urbanely.
"Wouldn't if I were you," said the boy. "Ma aint at home. She don't
want the stuff, anyhow. That was only my 'rithmetic lesson."
70. As the lad vanished I laughed and said "bon voyage" to my
prospective order. The worst of it is, the boys say that this story
dates back to Joe Miller's great-grandfather. But it taught me that it
is sometimes wise to be deaf, dumb and blind to the point of a joke.
Unfortunately, I am short on the joke market, and to date have been
unable to meet the keen competition I encounter in this line. Job
Withers, a big-faced, big-voiced chap, who travels for Soper & Co.,
spins yarns with the speed, ease and penetrating quality of a well
greased circular saw. When he goes into a store he looks about,
comments on any changes or improvements that may have occurred
since his last visit, asks the proprietor about his dog, if he has one,
and about his wife, if he has not, sits on a barrel and says: "Did I
ever tell you—?" At that there is a great shuffling of feet and all the
store loungers sit up and take notice. Then he launches into a story
and follows it with another and another. Then, when the boss is
wiping away the tears that come with the laughter, Job pulls out an
order blank and, with a look about the store, says: "I see you're
almost all out of—" and he writes off a list of things. Before the
echoes of the laughter have ceased the order is rolling along
towards "the House" in the custody of a two-cent stamp.
If there is one thing needed more than nerve in this business it is
hypnotism; and in the practical part of this science Job Withers has
Mesmer and Professor Carpenter backed clear over the divide. It's
no trick to sell a man anything he wants, but unfortunately no one
ever wants anything. The Job Witherses see to that by their delicate
attentions in keeping everybody stocked up. A man'll never get the
V. H. C. from "the House" till he learns how to sell goods that his
customer doesn't want, and I tell you, pater, a good swift game of
talk—the right kind—is what gives the shelves and refrigerators of
country stores indigestion. If you pursued a different policy I do not
wonder that when you tried travelling you had, as you hint, to run
the last quarter in record time in order to anticipate a request for
your resignation.
71. But I have a suspicion that you have not dealt squarely by me. I will
be frank and tell you why. In view of the paucity of my supply of
stories—and nothing, I assure you, but extremity would have
induced me to do it—I overhauled your letters the other day and
weeded out the best of your anecdotes and tried them on some of
my intended customers. It immediately became clear to me why you
do not believe in story-telling as an adjunct to trade. You must have
been less philosophical during your brief stay on the road than you
are now, otherwise you would have realized that the failure of your
crop of anecdotes to yield a harvest does not prove the futility of
planting a different class of seed. The well-known facts concerning
our hams do not demonstrate that there are no good hams in the
market.
One thing is sure. I shall send "the House" an order before the week
is out, even if I have to eat the stuff myself. It really can't be worse
than the food I get at some of the hotels. The hotel in the town
before this was a wonder. I asked for a napkin and the table girl said
they used to have them, but the boarders took so many with them
that it was too expensive. I guess they ate them in preference to the
food. I told the girl I'd have a piece of steak and an egg. She
returned, cheerful but empty-handed.
"I am sorry, sir," she lisped, "but cook says the last piece of steak
has been used for a hinge on the landlord's daughter's trunk. She is
to be married to-day," she added, with a smile evidently intended to
be engaging. But I didn't care to be engaged, at least not to her.
"Well, bring an egg and some toast," I said, amiably.
"Sorry, sir," chirped up Bright Eyes, "but cook's just beaten up the
egg. She says you can have your share of it in the meringue pudding
at dinner."
"What have you got, then?" I demanded with some acrimony.
"Hot lamb, cold lamb, roast lamb, and minced lamb," she gurgled. I
subsequently ascertained that they sheared the lamb a few days
72. before and that the poor innocent caught cold and died.
If they were as strict in their menu in these country hotels as they
are in their rules, it would be all right. No hotel is complete without a
long list of "Don'ts for Guests," plastered on the inside of the door.
Here are a few that appealed to me with especial force:
"Please do not tip the waiters or the porter." (As the waiters did
nothing for me and the porter weighed 285 pounds I conformed to
this rule.)
"In event of fire an alarm will be sounded on the gongs if the night
clerk is awake. The fire-escapes are in the office safe. In case of fire
you can have one after you have paid your bill."
It is hard to get a decent night's rest in these hostelries. If it isn't
one thing it's another. Last Saturday I was so tired that I felt I
wouldn't care if I jumped Sunday right out of the calendar. Sunday
morning I was sleeping beautifully when there was a rap on the
door.
"Been't you a goin' to git up?" came a squeaky voice.
"What time is it?" I asked.
"Half past seven," was the reply.
"Get up? No, go away," I shouted.
"Breakfast comes in half an hour," said the squeak.
"Don't want any breakfast," I thundered back.
"All right, the other boarders do."
"What in blazes is that to me?" I snarled.
"We want your sheets for tablecloths."
Do not worry. I shall not write long letters to "the House." They will
be as short as my expense account will permit.
73. 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!
ebooknice.com