100% found this document useful (6 votes)
236 views

Full Download Learning JavaScript Design Patterns Addy Osmani PDF DOCX

JavaScript

Uploaded by

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

Full Download Learning JavaScript Design Patterns Addy Osmani PDF DOCX

JavaScript

Uploaded by

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

Download the full version of the ebook at ebookname.

com

Learning JavaScript Design Patterns Addy Osmani

https://ebookname.com/product/learning-javascript-design-
patterns-addy-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 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/

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 Python Design Patterns 2nd Edition Chetan


Giridhar

https://ebookname.com/product/learning-python-design-patterns-2nd-
edition-chetan-giridhar/

ebookname.com

The Body Politic in Roman Political Thought 1st Edition


Julia Mebane

https://ebookname.com/product/the-body-politic-in-roman-political-
thought-1st-edition-julia-mebane/

ebookname.com
Cambridge English for Nursing Pre intermediate Student s
Book with Audio CD Cambridge English For Series 1st
Edition Allum
https://ebookname.com/product/cambridge-english-for-nursing-pre-
intermediate-student-s-book-with-audio-cd-cambridge-english-for-
series-1st-edition-allum/
ebookname.com

Smart Buildings Systems for Architects Owners and Builders


James M Sinopoli

https://ebookname.com/product/smart-buildings-systems-for-architects-
owners-and-builders-james-m-sinopoli/

ebookname.com

Dietary Modulation of Cell Signaling Pathways 1st Edition


Zigang Dong

https://ebookname.com/product/dietary-modulation-of-cell-signaling-
pathways-1st-edition-zigang-dong/

ebookname.com

Global Politics 9th Edition James Ray

https://ebookname.com/product/global-politics-9th-edition-james-ray/

ebookname.com

Materials Degradation and Its Control by Surface


Engineering 3rd Edition Andrew W Batchelor

https://ebookname.com/product/materials-degradation-and-its-control-
by-surface-engineering-3rd-edition-andrew-w-batchelor/

ebookname.com
WHO Guidelines for the Management of Postpartum
Haemorrhage and Retained Placenta 1st Edition World Health
Organization
https://ebookname.com/product/who-guidelines-for-the-management-of-
postpartum-haemorrhage-and-retained-placenta-1st-edition-world-health-
organization/
ebookname.com
Learning JavaScript Design
Patterns

Addy Osmani

Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo


Learning JavaScript Design Patterns
by Addy Osmani

Copyright © 2012 Addy Osmani. All rights reserved.

Revision History for the :


2012-05-01 Early release revision 1
See http://oreilly.com/catalog/errata.csp?isbn=9781449331818 for release details.

ISBN: 978-1-449-33181-8
1335906805
Table of Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2. What is a Pattern? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
We already use patterns everyday 4

3. 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three . . . . . . . . . . . . . . . . . . . . . . 7

4. The Structure Of A Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

5. Writing Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

6. Anti-Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

7. Categories Of Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15


Creational Design Patterns 15
Structural Design Patterns 16
Behavioral Design Patterns 16

8. Design Pattern Categorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


A brief note on classes 17

9. JavaScript Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21


The Creational Pattern 22
The Constructor Pattern 23
Basic Constructors 23
Constructors With Prototypes 24
The Singleton Pattern 24
The Module Pattern 27

iii
Modules 27
Object Literals 27
The Module Pattern 29
The Revealing Module Pattern 36
The Observer Pattern 37
Advantages 38
Disadvantages 39
Implementations 39
The Mediator Pattern 49
Advantages & Disadvantages 50
Mediator Vs. Observer 51
Mediator Vs. Facade 51
The Prototype Pattern 52
The Command Pattern 54
The Facade Pattern 56
The Factory Pattern 58
When To Use The Factory Pattern 59
When Not To Use The Factory Pattern 59
The Mixin Pattern 60
The Decorator Pattern 61
Subclassing 61
Decorators 63
Example 1: Basic decoration of existing object constructors with new
functionality 63
Example 2: Simply decorate objects with multiple decorators 64
Pseudo-classical decorators 65
Interfaces 65
This variation of decorators and abstract decorators 66
Implementing decorators with jQuery 69
Pros and cons of the pattern 70

10. Flyweight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Flyweight and the data layer 72
Converting code to use the Flyweight pattern 72
A Basic Factory 74
Managing the extrinsic states 74
The Flyweight pattern and the DOM 76
Example 1: Centralized event handling 76
Example 2: Using the Flyweight for Performance Gains 77

11. MV* Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79


MVC 79
Smalltalk-80 MVC 79

iv | Table of Contents
MVC For JavaScript Developers 80
Models 81
Views 82
Controllers 85
Controllers in another library (Spine.js) vs Backbone.js 86
What does MVC give us? 87
Delving deeper 88
Summary 88
MVP 88
Models, Views & Presenters 89
MVP or MVC? 90
MVC, MVP and Backbone.js 90
MVVM 92
History 92
Model 93
View 94
ViewModel 96
Recap: The View and the ViewModel 98
Recap: The ViewModel and the Model 98
Pros and Cons 98
Advantages 98
Disadvantages 98
MVVM With Looser Data-Bindings 99
MVC Vs. MVP Vs. MVVM 103
Backbone.js Vs. KnockoutJS 103
Namespacing Patterns 104
What is namespacing? 104
Advanced namespacing patterns 105
Automating nested namespacing 105
Dependency declaration pattern 107
Deep object extension 108
Namespacing Fundamentals 110
1.Single global variables 111
2. Prefix namespacing 111
3. Object literal notation 112
4. Nested namespacing 114
5. Immediately-invoked Function Expressions (IIFE)s 115
6. Namespace injection 117

12. Design Patterns in jQuery Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121


Module Pattern 121
Lazy Initialization 122
The Composite Pattern 123

Table of Contents | v
The Adapter Pattern 123
The Facade Pattern 124
The Observer Pattern 125
The Iterator Pattern 126
The Strategy Pattern 127
The Proxy Pattern 127
The Builder Pattern 128
The Prototype Pattern 128

13. Modern Modular JavaScript Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131


The Importance Of Decoupling Your Application 131
A Note On Script Loaders 132
AMD 132
A Format For Writing Modular JavaScript In The Browser 132
Getting Started With Modules 133
AMD Modules With Dojo 137
AMD Module Design Patterns (Dojo) 138
AMD Modules With jQuery 139
AMD Conclusions 141
CommonJS 141
A Module Format Optimized For The Server 141
Getting Started 141
AMD && CommonJS Competing, But Equally Valid Standards 144
Basic AMD Hybrid Format (John Hann) 145
AMD/CommonJS Universal Module Definition (Variation 2, UMDjs) 145
Extensible UMD Plugins With (Variation by myself and Thomas Davis). 146
ES Harmony 148
Modules Of The Future 148
Modules With Imports And Exports 148
Modules Loaded From Remote Sources 149
Module Loader API 150
CommonJS-like Modules For The Server 150
Classes With Constructors, Getters & Setters 150
Conclusions And Further Reading A Review 152

14. Bonus: jQuery Plugin Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153


Patterns 154
Note 154
A Lightweight Start 155
Further Reading 156
“Complete” Widget Factory 157
Further Reading 159
Namespacing And Nested Namespacing 159

vi | Table of Contents
Further Reading 161
Custom Events For Pub/Sub (With The Widget factory) 161
Further Reading 162
Prototypal Inheritance With The DOM-To-Object Bridge Pattern 162
Further Reading 164
jQuery UI Widget Factory Bridge 164
Further Reading 166
jQuery Mobile Widgets With The Widget factory 167
RequireJS And The jQuery UI Widget Factory 169
Further Reading 172
Globally And Per-Call Overridable Options (Best Options Pattern) 172
Further Reading 174
A Highly Configurable And Mutable Plugin 174
Further Reading 176
UMD: AMD And CommonJS-Compatible Modules For Plugins 176
Further Reading 179
What Makes A Good Plugin Beyond Patterns? 179

15. Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

16. References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

Table of Contents | vii


Preface

Design patterns are reusable solutions to commonly occurring problems in software


design. They are both exciting and a fascinating topic to explore in any programming
language.
One reason for this is that they help us build upon the combined experience of many
developers that came before us and ensure we structure our code in an optimized way,
meeting the needs of problems we're attempting to solve.
Design patterns also provide us a common vocabulary to describe solutions. This can
be significantly simpler than describing syntax and semantics when we're attempting
to convey a way of structuring a solution in code form to others.
In this book we will explore applying both classical and modern design patterns to the
JavaScript programming language.

Target Audience
This book is targeted at professional developers wishing to improve their knowledge
of design patterns and how they can be applied to the JavaScript programming lan-
guage.
Some of the concepts covered (closures, prototypal inheritance) will assume a level of
basic prior knowledge and understanding. If you find yourself needing to read further
about these topics, a list of suggested titles is provided for convenience.
If you would like to learn how to write beautiful, structured and organized code, I
believe this is the book for you.

Acknowledgments
I will always be grateful for the talented technical reviewers who helped review and
improve this book, including those from the community at large. The knowledge and
enthusiasm they brought to the project was simply amazing. The official technical re-

ix
viewers tweets and blogs are also a regular source of both ideas and inspiration and I
wholeheartedly recommend checking them out.
• Luke Smith (http://lucassmith.name, @ls_n)
• Nicholas Zakas (http://nczonline.net, @slicknet)
• Andrée Hansson (http://andreehansson.se, @peolanha)
• Alex Sexton (http://alexsexton.com, @slexaxton)
I would also like to thank Rebecca Murphey (http://rebeccamurphey.com, @rmur-
phey) for providing the inspiration to write this book and more importantly, continue
to make it both available on GitHub and via O'Reilly.
Finally, I would like to thank my wonderful wife Ellie, for all of her support while I was
putting together this publication.

Credits
Whilst some of the patterns covered in this book were implemented based on personal
experience, many of them have been previously identified by the JavaScript community.
This work is as such the production of the combined experience of a number of devel-
opers. Similar to Stoyan Stefanov's logical approach to preventing interruption of the
narrative with credits (in JavaScript Patterns), I have listed credits and suggested reading
for any content covered in the references section.
If any articles or links have been missed in the list of references, please accept my
heartfelt apologies. If you contact me I'll be sure to update them to include you on the
list.

Reading
Whilst this book is targeted at both beginners and intermediate developers, a basic
understanding of JavaScript fundamentals is assumed. Should you wish to learn more
about the language, I am happy to recommend the following titles:
• JavaScript: The Definitive Guide by David Flanagan
• Eloquent JavaScript by Marijn Haverbeke
• JavaScript Patterns by Stoyan Stefanov
• Writing Maintainable JavaScript by Nicholas Zakas
• JavaScript: The Good Parts by Douglas Crockford

x | Preface
CHAPTER 1
Introduction

One of the most important aspects of writing maintainable code is being able to notice
the recurring themes in that code and optimize them. This is an area where knowledge
of design patterns can prove invaluable.
In the first part of this book, we will explore the history and importance of design
patterns which can really be applied to any programming language. If you're already
sold on or are familiar with this history, feel free to skip to the chapter 'What is a
Pattern?' to continue reading.
Design patterns can be traced back to the early work of a civil engineer named Chris-
topher Alexander. He would often write publications about his experience in solving
design issues and how they related to buildings and towns. One day, it occurred to
Alexander that when used time and time again, certain design constructs lead to a
desired optimal effect.
In collaboration with Sara Ishikawa and Murray Silverstein, Alexander produced a
pattern language that would help empower anyone wishing to design and build at any
scale. This was published back in 1977 in a paper titled 'A Pattern Language', which
was later released as a complete hardcover book.
Some 30 years ago, software engineers began to incorporate the principles Alexander
had written about into the first documentation about design patterns, which was to be
a guide for novice developers looking to improve their coding skills. It's important to
note that the concepts behind design patterns have actually been around in the pro-
gramming industry since its inception, albeit in a less formalized form.
One of the first and arguably most iconic formal works published on design patterns
in software engineering was a book in 1995 called Design Patterns: Elements Of Reusable
Object-Oriented Software. This was written by Erich Gamma,Richard Helm,Ralph
Johnson andJohn Vlissides - a group that became known as the Gang of Four (or GoF
for short).
The GoF's publication is considered quite instrumental to pushing the concept of de-
sign patterns further in our field as it describes a number of development techniques

1
and pitfalls as well as providing twenty-three core Object-Oriented design patterns
frequently used around the world today. We will be covering these patterns in more
detail in the section ‘Categories of Design Patterns’.
In this book, we will take a look at a number of popular JavaScript design patterns and
explore why certain patterns may be more suitable for your projects than others. Re-
member that patterns can be applied not just to vanilla JavaScript (i.e standard Java-
Script code), but also to abstracted libraries such as jQuery or dojo as well. Before we
begin, let’s look at the exact definition of a ‘pattern’ in software design.

2 | Chapter 1: Introduction
CHAPTER 2
What is a Pattern?

A pattern is a reusable solution that can be applied to commonly occurring problems


in software design - in our case - in writing JavaScript-powered applications. Another
way of looking at patterns are as templates for how you solve problems - ones which
can be used in quite a few different situations.
So, why is it important to understand patterns and be familiar with them?. Design
patterns have three main benefits:
1. Patterns are proven solutions: They provide solid approaches to solving issues
in software development using proven solutions that reflect the experience and
insights the developers that helped define and improve them bring to the pattern.
2. Patterns can be easily reused:A pattern usually reflects an out of the box solution
that can be adapted to suit your own needs. This feature makes them quite robust.
3. Patterns can be expressive:When you look at a pattern there’s generally a set
structure and ‘vocabulary’ to the solution presented that can help express rather
large solutions quite elegantly.
Patterns are not an exact solution. It’s important that we remember 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, however, they do support them. Next
we’ll take a look at some of the other advantages patterns have to offer.
• Reusing patterns assists in preventing minor issues that can cause major
problems in the application development process.What this means is when
code is built on proven patterns, we can afford to spend less time worrying about
the structure of our code and more time focusing on the quality of our overall
solution. This is because patterns can encourage us to code in a more structured
and organized fashion avoiding the need to refactor it for cleanliness purposes in
the future.
• Patterns can provide generalized solutions which are documented in a fash-
ion that doesn't require them to be tied to a specific problem. This generalized
approach means that regardless of the application (and in many cases the pro-

3
gramming language) you are working with, design patterns can be applied to im-
prove the structure of your code.
• Certain patterns can actually decrease the overall file-size footprint of your
code by avoiding repetition.By encouraging developers to look more closely at
their solutions for areas where instant reductions in repetition can be made, e.g.
reducing the number of functions performing similar processes in favor of a single
generalized function, the overall size of your codebase can be decreased.
• Patterns add to a developers vocabulary, which makes communication
faster.
• Patterns that are frequently used can be improved over time by harnessing
the collective experiences other developers using those patterns contribute
back to the design pattern community. In some cases this leads to the creation
of entirely new design patterns whilst in others it can lead to the provision of im-
proved guidelines on how specific patterns can be best used. This can ensure that
pattern-based solutions continue to become more robust than ad-hoc solutions
may be.

We already use patterns everyday


To understand how useful patterns can be, let's review a very simple element selection
problem that the jQuery library solves for us everyday.
If we imagine that we have a script where for each DOM element on a page with class
"foo" we want to increment a counter, what's the simplest efficient way to query for
the list we need?. Well, there are a few different ways this problem could be tackled:
1. Select all of the elements in the page and then store them. Next, filter this list and
use regular expressions (or another means) to only store those with the class "foo".
2. Use a modern native browser feature such as querySelectorAll() to select all of
the elements with the class "foo".
3. Use a native feature such as getElementsByClassName() to similarly get back the
desired list.
So, which of these is the fastest?. You might be interested to know that it's actually
number 3. by a factor of 8-10 times the alternatives. In a real-world application however,
3. will not work in versions of Internet Explorer below 9 and thus it's necessary to use
1. where 3. isn't supported.
Developers using jQuery don't have to worry about this problem, as it's luckily ab-
stracted away for us. The library opts for the most optimal approach to selecting ele-
ments depending on what your browser supports.
Core internally uses a number of different design patterns, the most frequent one
being a facade. This provides a simple set of abstracted interfaces (e.g $el.css(),
$el.animate()) to several more complex underlying bodies of code.

4 | Chapter 2: What is a Pattern?


We're probably all also familiar with jQuery's $('selector'). This is significantly more
easy to use for selecting HTML elements on a page versus having to manually handle
opt for getElementById(), getElementsByClassName(), getElementByTagName and so on.
Although we know that querySelectorAll() attempts to solve this problem, compare
the effort involved in using jQuery's facade interfaces vs. selecting the most optimal
selection paths ourselves. There's no contest! abstractions using patterns can offer real-
world value.
We'll be looking at this and more design patterns later on in the book.

We already use patterns everyday | 5


CHAPTER 3
'Pattern'-ity Testing, Proto-Patterns &
The Rule Of Three

Remember that not every algorithm, best-practice or solution represents what might
be considered a complete pattern. There may be a few key ingredients here that are
missing and the pattern community is generally weary of something claiming to be one
unless it has been heavily vetted. Even if something is presented to us which appears
to meet the criteria for a pattern, it should not be considered one until it has undergone
suitable periods of scrutiny and testing by others.
Looking back upon the work by Alexander once more, he claims that a pattern should
both be a process and a ‘thing’. This definition is obtuse on purpose as he follows by
saying that it is the process should create the ‘thing’. This is a reason why patterns
generally focus on addressing a visually identifiable structure i.e you should be able to
visually depict (or draw) a picture representing the structure that placing the pattern
into practice results in.
In studying design patterns, you may come across the term ‘proto-pattern’ quite fre-
quently. What is this? Well, a pattern that has not yet been known to pass the ‘pattern’-
ity tests is usually referred to as a proto-pattern. Proto-patterns may result from the
work of someone that has established a particular solution that is worthy of sharing
with the community, but may not have yet had the opportunity to have been vetted
heavily due to its very young age.
Alternatively, the individual(s) sharing the pattern may not have the time or interest of
going through the ‘pattern’-ity process and might release a short description of their
proto-pattern instead. Brief descriptions or snippets of this type of pattern are known
as patlets.
The work involved in fully documenting a qualified pattern can be quite daunting.
Looking back at some of the earliest work in the field of design patterns, a pattern may
be considered ‘good’ if it does the following:

7
• Solves a particular problem: Patterns are not supposed to just capture principles
or strategies. They need to capture solutions. This is one of the most essential
ingredients for a good pattern.
• The solution to this problem cannot be obvious: You can often find that prob-
lem-solving techniques attempt to derive from well-known first principles. The
best design patterns usually provide solutions to problems indirectly - this is con-
sidered a necessary approach for the most challenging problems related to design.
• The concept described must have been proven: Design patterns require proof
that they function as described and without this proof the design cannot be seri-
ously considered. If a pattern is highly speculative in nature, only the brave may
attempt to use it.
• It must describe a relationship: In some cases it may appear that a pattern de-
scribes a type of module. Although an implementation may appear this way, the
official description of the pattern must describe much deeper system structures
and mechanisms that explain its relationship to code.
We would be forgiven for thinking that a proto-pattern which fails to meet guidelines
isn't worth learning from, however, this is far from the truth. Many proto-patterns are
actually quite good. I’m not saying that all proto-patterns are worth looking at, but
there are quite a few useful ones in the wild that could assist you with future projects.
Use best judgment with the above list in mind and you’ll be fine in your selection
process.
One of the additional requirements for a pattern to be valid is that they display some
recurring phenomenon. This is often something that can be qualified in at least three
key areas, referred to as the rule of three. To show recurrence using this rule, one must
demonstrate:
1. Fitness of purpose - how is the pattern considered successful?
2. Usefulness- why is the pattern considered successful?
3. Applicability - is the design worthy of being a pattern because it has wider ap-
plicability? If so, this needs to be explained.When reviewing or defining a pattern,
it is important to keep the above in mind.

8 | Chapter 3: 'Pattern'-ity Testing, Proto-Patterns & The Rule Of Three


CHAPTER 4
The Structure Of A Design Pattern

You may be curious about how a pattern author might approach outlining structure,
implementation and purpose of a new pattern. Traditionally, a pattern is initially be
presented in the form of a rule that establishes a relationship between:
• A context
• A system of forces that arises in that context and
• A configuration that allows these forces to resolve themselves in context
With this in mind, lets now take a look at a summary of the component elements for
a design pattern. A design pattern should have a:
• Pattern name and a description
• Context outline – the contexts in which the pattern is effective in responding to
the users needs.
• Problem statement – a statement of the problem being addressed so we can un-
derstand the intent of the pattern.
• Solution – a description of how the user’s problem is being solved in an under-
standable list of steps and perceptions.
• Design – a description of the pattern’s design and in particular, the user’s behavior
in interacting with it
• Implementation– a guide to how the pattern would be implemented
• Illustrations – a visual representation of classes in the pattern (e.g. a diagram))
• Examples – an implementation of the pattern in a minimal form
• Co-requisites – what other patterns may be needed to support use of the pattern
being described?
• Relations – what patterns does this pattern resemble? does it closely mimic any
others?
• Known usage – is the pattern being used in the ‘wild’?. If so, where and how?
• Discussions – the team or author’s thoughts on the exciting benefits of the pattern

9
Design patterns are quite a powerful approach to getting all of the developers in an
organization or team on the same page when creating or maintaining solutions. If you
or your company ever consider working on your own pattern, remember that although
they may have a heavy initial cost in the planning and write-up phases, the value re-
turned from that investment can be quite worth it. Always research thoroughly before
working on new patterns however, as you may find it more beneficial to use or build
on top of existing proven patterns than starting afresh.

10 | Chapter 4: The Structure Of A Design Pattern


CHAPTER 5
Writing Design Patterns

Although this book is aimed at those new to design patterns, a fundamental under-
standing of how a design pattern is written can offer you a number of useful benefits.
For starters, you can gain a deeper appreciation for the reasoning behind a pattern being
needed. You can also learn how to tell if a pattern (or proto-pattern) is up to scratch
when reviewing it for your own needs.
Writing good patterns is a challenging task. Patterns not only need to provide a sub-
stantial quantity of reference material for end-users (such as the items found in the
structure section above), but they also need to be able to defend why they are necessary.
If you’ve already read the previous section on ‘what’ a pattern is, you may think that
this in itself should help you identify patterns when you see them in the wild. This is
actually quite the opposite - you can’t always tell if a piece of code you’re inspecting
follows a pattern.
When looking at a body of code that you think may be using a pattern, you might write
down some of the aspects of the code that you believe falls under a particular existing
pattern.In many cases of pattern-analysis you’ll find that you’re just looking at code
that follows good principles and design practices that could happen to overlap with the
rules for a pattern by accident. Remember - solutions in which neither interactions nor
defined rules appear are not patterns.
If you’re interested in venturing down the path of writing your own design patterns I
recommend learning from others who have already been through the process and done
it well. Spend time absorbing the information from a number of different design pattern
descriptions and books and take in what’s meaningful to you - this will help you ac-
complish the goals you have laid out for yours. Explore structure and semantics - this
can be done by examining the interactions and context of the patterns you are interested
in so you can identify the principles that assist in organizing those patterns together in
useful configurations.
Once you’ve exposed yourself to a wealth of information on pattern literature, you may
wish to begin your pattern using an existing format and see if you can brainstorm new
ideas for improving it or integrating your ideas in there. An example of someone that

11
did this is in recent years is Christian Heilmann, who took the existing module pattern
and made some fundamentally useful changes to it to create the revealing module pat-
tern (this is one of the patterns covered later in this book).
If you would like to try your hand at writing a design pattern (even if just for the learning
experience of going through the process), the tips I have for doing so would be as
follows:
• Bear in mind practicability: Ensure that your pattern describes proven solutions
to recurring problems rather than just speculative solutions which haven’t been
qualified.
• Ensure that you draw upon best practices: The design decisions you make
should be based on principles you derive from an understanding of best-practices.
• Your design patterns should be transparent to the user: Design patterns should
be entirely transparent to any type of user-experience. They are primarily there to
serve the developers using them and should not force changes to behavior in the
user-experience that would not be incurred without the use of a pattern.
• Remember that originality is not key in pattern design: When writing a pattern,
you do not need to be the original discoverer of the solutions being documented
nor do you have to worry about your design overlapping with minor pieces of other
patterns.If your design is strong enough to have broad useful applicability, it has
a chance of being recognized as a proper pattern
• Know the differences between patterns and design: A design pattern generally
draws from proven best practice and serves as a model for a designer to create a
solution. The role of the pattern is to give designers guidance to make the best design
choices so they can cater to the needs of their users.
• Your pattern needs to have a strong set of examples: A good pattern description
needs to be followed by an equally strong set of examples demonstrating the suc-
cessful application of your pattern. To show broad usage, examples that exhibit
good design principles are ideal.
Pattern writing is a careful balance between creating a design that is general, specific
and above all, useful. Try to ensure that if writing a pattern you cover the widest possible
areas of application and you should be fine. I hope that this brief introduction to writing
patterns has given you some insights that will assist your learning process for the next
sections of this book.

12 | Chapter 5: Writing Design Patterns


CHAPTER 6
Anti-Patterns

If we consider that a pattern represents a best-practice, an anti-pattern represents a


lesson that has been learned. The term anti-patterns was coined in 1995 by Andrew
Koenig in the November C++ Report that year, inspired by the GoF's book Design
Patterns. In Koenig’s report, there are two notions of anti-patterns that are presented.
Anti-Patterns:
• Describe abad solution to a particular problem which resulted in a bad situation
occurring
• Describe how to get out of said situation and how to go from there to a good
solution
On this topic, Alexander writes about the difficulties in achieving a good balance be-
tween good design structure and good context:
“These notes are about the process of design; the process of inventing physical things which
display a new physical order, organization, form, in response to function.…every design
problem begins with an effort to achieve fitness between two entities: the form in question
and its context. The form is the solution to the problem; the context defines the problem”.
While it’s quite important to be aware of design patterns, it can be equally important
to understand anti-patterns. Let us qualify the reason behind this. When creating an
application, a project’s life-cycle begins with construction however once you’ve got the
initial release done, it needs to be maintained. The quality of a final solution will either
be good or bad, depending on the level of skill and time the team have invested in it.
Here good and bad are considered in context - a ‘perfect’ design may qualify as an anti-
pattern if applied in the wrong context.
The bigger challenges happen after an application has hit production and is ready to
go into maintenance mode. A developer working on such a system who hasn’t worked
on the application before may introduce a bad design into the project by accident. If
said bad practices are created as anti-patterns, they allow developers a means to rec-
ognize these in advance so that they can avoid common mistakes that can occur - this

13
is parallel to the way in which design patterns provide us with a way to recognize
common techniques that are useful.
To summarize, an anti-pattern is a bad design that is worthy of documenting. Examples
of anti-patterns in JavaScript are the following:
• Polluting the global namespace by defining a large number of variables in the global
context
• Passing strings rather than functions to either setTimeout or setInterval as this
triggers the use of eval() internally.
• Modifying the Object class prototype (this is a particularly bad anti-pattern)
• Using JavaScript in an inline form as this is inflexible
• The use of document.write where native DOM alternatives such as document.cre-
ateElement are more appropriate. document.write has been grossly misused over
the years and has quite a few disadvantages including that if it's executed after the
page has been loaded it can actually overwrite the page you're on, whilst docu-
ment.createElement does not. You can see here for a live example of this in action.
It also doesn't work with XHTML which is another reason opting for more DOM-
friendly methods such as document.createElement is favorable.
Knowledge of anti-patterns is critical for success. Once you are able to recognize such
anti-patterns, you will be able to refactor your code to negate them so that the overall
quality of your solutions improves instantly.

14 | Chapter 6: Anti-Patterns
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Master Rockafellar's
Voyage
This ebook is for the use of anyone anywhere in the United States and most
other parts of the world at no cost and with almost no restrictions whatsoever.
You may copy it, give it away or re-use it under the terms of the Project
Gutenberg License included with this ebook or online at www.gutenberg.org.
If you are not located in the United States, you will have to check the laws of
the country where you are located before using this eBook.

Title: Master Rockafellar's Voyage

Author: William Clark Russell

Illustrator: Gordon Browne

Release date: June 7, 2020 [eBook #62336]

Language: English

Credits: Produced by The Online Distributed Proofreading Team at


https://www.pgdp.net (This file was produced from images
generously made available by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK MASTER ROCKAFELLAR'S


VOYAGE ***
MASTER ROCKAFELLAR’S VOYAGE

BY THE SAME AUTHOR


MY DANISH SWEETHEART
HIS ISLAND PRINCESS
ABANDONED

“BE PLEASED TO GET IN AND GO AWAY.”

See page 175.


MASTER ROCKAFELLAR’S
VOYAGE

BY
W. CLARK RUSSELL
AUTHOR OF “MY DANISH SWEETHEART,” ETC., ETC.

WITH 27 ILLUSTRATIONS BY GORDON BROWNE

FIFTH EDITION

METHUEN & CO. LTD.


36 ESSEX STREET W.C.
LONDON

First Published October 1890


Second Edition November 1894
Third Edition August 1906
Fourth Edition November 1910
Fifth Edition 1913
CONTENTS
PAGE

CHAPTER I.
HE BEGS TO GO TO SEA 1

CHAPTER II.
HIS FIRST DAY ON BOARD SHIP 17

CHAPTER III.
HE SAILS FROM GRAVESEND 30
CHAPTER IV.
HE GOES ALOFT 45

CHAPTER V.
HE SIGHTS A SHIP 59

CHAPTER VI.
HE IS STRUCK BY LIGHTNING 74

CHAPTER VII.
HE HEARS A BELL 88

CHAPTER VIII.
HE SEES THE EQUATOR 103
CHAPTER IX.
HE SEES AN ICEBERG 209

CHAPTER X.
HE SIGHTS A WRECK 227

CHAPTER XI.
HE SEES A STRANGE LIGHT 243

CHAPTER XII.
HE ARRIVES HOME 259
Master Rockafellar’s Voyage
CHAPTER I.
HE BEGS TO GO TO SEA.

My name is Thomas Rockafellar; father and mother always called me


Tommy, and by that name was I known until I grew too old to be called by
anything more familiar than Tom. I have seen people look at one another, and
smile, perhaps, when they have heard the name Rockafellar mentioned as
that of a family; but I here beg leave to state that the Rockafellars are an
exceedingly ancient race, who, if they do not claim to have arrived in this
country with William the Conqueror, can excuse themselves for not having
landed with that chieftain by being able to prove that they had been many
years established when the keels of the Norman galleys grounded on the
Hastings shore.
Amongst my ancestors were several
sailors, who had served the king or queen
of their times in the navy of the state. A
portrait of Ebenezer Rockafellar, who was
a rear-admiral in the early years of
George the Second’s reign, hung in the
dining-room at home, and represented a
face like that of the man in the moon
when the planet rises very crimson out of
the sea on a hot summer’s evening. He
had a tail on his back and a great copper
speaking-trumpet under his arm and his
forefinger, on which was a huge ring,
rested upon a globe of the world. The
artist had painted in a picture of a
thunderstorm happening through a
window, with the glimpse of a rough sea, EBENEZER ROCKAFELLAR.
and an old-fashioned ship like a castle
tumbling about in it resembling a toy
Noah’s ark tossing on the strong ripples of a pond.
It might have been my looking at this red-faced ancestor of mine, and
admiring his speaking-trumpet, and the noble colour of weather which stained
his face that first put it into my head to go to sea. I cannot say. Who can tell
where little boys get their notions from? I would stand before that picture,
and in my small way dream about the ocean, about sharks, tropic islands full
of cocoa-nut trees, and monkeys, and parrots gorgeous as shapes of
burnished gold; and I would dream also, all in my small way, of flying-fish like
little lengths of pearl flashing out of the dark-blue brine on wings of gossamer,
and elephants and ivory tusks, and of black men in turbans and robes
glittering with jewels, like the dark velvet sky on a midsummer night; and so
on, and so on, until there arose in me a passion to go to sea, and behold with
my own little eyes the wonders of the world.
Father and mother tried hard to conquer my desire; and then, when they
found I would still be a sailor, they pretended to consent, secretly meaning to
weary me out, or to give me a good long chance of changing my views by
delaying to take any steps to humour my wishes. At last, finding my mind to
be wonderfully resolved, my father talked to my mother gravely about my
disposition for the sea—told her that when a boy exhibited a strong inclination
for a walk, no matter of what nature if honest, he should not be baulked—that
I might have the makings of another Captain Cook in me, or at all events of a
Vancouver, and end my days as a great man.
“Besides, my dear,” said he, “one voyage at least cannot harm him; it will fill
his mind with new experiences, it will also test his sincerity; it will act as the
strongest possible persuasion one way or the other. It will be cheaper too
than a year of schooling, and more useful, I don’t doubt. So, my dear, let us
make up our minds to send him into the Merchant Service for one voyage.”
However, it was some time before my mother consented. She would not
very strongly have objected to the Royal Navy, she said, but she considered
the Merchant Service too vulgar for a Rockafellar.
“Vulgar, my dear!” cried my father; “why, do you forget that your own Uncle
Martin was in the service of the Honourable East India Company?”
“Ah but,” she answered, “Uncle Martin was always a perfect gentleman, and
even had he been a common sailor on board a barge, he would have carried
himself with as much dignity and been as fully appreciated by people capable
of distinguishing as if he had been an Admiral of the Blues.”
“MY FATHER TALKED TO MY MOTHER.”

“Of the Blue, I think it is,” said my father.


“The Red is cock of the walk,” said I, who had been listening to this
conversation with much interest.
Well, it ended, after many talks, in my mother agreeing with my father that
one voyage could do me no harm, and that if I returned as eager for the sea
life as I now was, it might prove as good a calling for me as any other
vocation that could be named. So after making certain inquiries, my father
one day took me to London with him, to call upon a shipowner who lived
close by Fenchurch Street. He had five vessels, three of them large ships, of
which two had formerly been Indiamen, and the others were barques. They
were all regular traders to Australia: that is to say, to the different ports of
that colony, and one or more of them were always to be found in the East
India Docks discharging the wool with which they returned home full of, or
taking in merchandise for the outward passage.
The shipowner, Mr. Duncan, was a large, fat, cheerful man, “with a very
knowing eye, and supposed to be already worth, my dear, about a million and
a half,” as I afterwards heard my father tell my mother. We passed through an
office full of clerks into a little back room, where we were received by Mr.
Duncan, who seemed delighted to make our acquaintance. He patted me on
the head, said that he was always fond of boys whose hair curled, declared
that he could not remember ever having set eyes on a more likely sailorly-
looking lad, promised me that I should become the captain of a ship if I
worked hard, and then he and my father went to business.
The terms were a premium of sixty guineas for the first voyage, together
with ten guineas for what was called mess-money; “and with regard to pocket
money,” said Mr. Duncan, “I should say if you give the captain enough to
enable him to put half-a-crown a week into the lad’s pocket whilst he’s in
harbour the boy will have more than he needs for simple enjoyment, and too
little,” said he, closing one eye, “for what Jack calls larks.”
The name of the ship was the Lady Violet, and Mr. Duncan told us that she
was commanded by Captain Tempest, who, notwithstanding his stormy name,
was a gentleman-like person of a mild disposition, one of the best navigators
out of the Port of London, and beloved by all who sailed with him.
“There is no flogging now, I think, sir, at sea?” said my father.
“Oh dear no,” cried Mr. Duncan, smiling all over his immense crimson face:
“a barbarous practice, sir, very happily suppressed ages ago.”
“How are boys punished,” asked my father, “at sea when they deserve it?”
“Why, sir,” answered Mr. Duncan, “the captain usually sends for them to his
cabin, and lectures them paternally and tenderly. His admonitions rarely fail,
but if there be great perversity, then possibly a little extra duty of a trifling
kind is given to them. But there is very little naughtiness amongst boys at sea,
sir! very little naughtiness indeed. Perhaps I should add, in my ships, where
no bad language is allowed, where sobriety is strictly encouraged, and where
even smoking is regarded as objectionable, though of course,” added Mr.
Duncan, drawing a deep breath that sounded like a sigh, “we do not prohibit
it.”
A good deal more to this effect passed between my father and Mr. Duncan,
and then certain arrangements having been made, we took our leave.
The ship was to sail in three weeks; she lay in the East India Docks, and as
she would not be hauling out of the gates until the afternoon, there was no
need for me to present myself on board sooner than the morning of the day
of her sailing.
My outfit was procured at a well-known marine establishment in Leadenhall
Street. I very well recollect the pride with which I tried on a blue cloth jacket,
embellished with brass buttons, and surveyed my appearance in a large pier-
glass. I had never before been dressed in brass buttons, and felt, now that I
was thus decorated, that I was a man indeed. Also the glittering badge of a
sort of wreath of gold, embracing a gorgeous little flag on the cap which the
outfitter placed on my head, enchanted me. Indeed, I could not but think that
the privilege of wearing so beautiful a decoration would be cheaply earned by
years of exposure and hardship, not to mention shipwreck, and even famine
and thirst in an open boat.
“It seems to me,” said my father to the outfitter, “to judge by your list, that
it is the practice of young gentlemen when they first go to sea to take a great
number of shirts and fine duck trousers with them.”
“They need all their fathers allow them, sir,” said the outfitter, with a bow.
“Is it,” asked my father, “that they must always appear very clean?”
“No, sir,” answered the outfitter. “I regret to say that it is the habit of most
young gentlemen when first they go to sea to swap their trousers and shirts
with the baker for what is termed ‘soft-tack.’”
“What is soft-tack?” said I.
“Bread, the likes of which we eat ashore,” answered the outfitter.
“Don’t they get the same at sea?” said I.
“No, young gentleman,” answered the outfitter; “there’s nothing but biscuit
eaten at sea by sailors, and it’s sometimes rather wormy. When it is so, soft-
tack grows into a delicacy, compared with which midshipmen’s trousers and
shirts count for nothing.”
“I’d rather have a biscuit any day,” said I, “than a slice of bread.”
I thought the smile the outfitter bestowed upon me a rather singular one.
My father looked pleased, and said to the outfitter, “Master Rockafellar will
keep his clothes, I know.”
“Not a doubt of it, sir,” responded the outfitter, and forthwith proceeded to
show us the oilskins, sou’wester, sea-boots, bars of marine soap, clasp-knife,
and the other articles which were to form the contents of the brand-new
white-wood sea-chest, with grummets for handles, and with a little shelf for
“curios,” and upon the lid of which my name, Thomas Rockafellar, was to be
painted in strong, large black letters.
I will pass over my parting with my mother and sisters and little brother. My
uniform came down a week before I sailed, and my wearing of the clothes
greatly helped to sustain my spirits, whilst they made me feel that I was a
sailor, and must not betray any sort of weakness that might seem girlish. I
tried hard not to cry as my mother strained me to her heart, and I said good-
bye with dry eyes; but I broke down when I was in the railway carriage as the
engine whistled, and the familiar scene of the station slipped away. My father,
who was accompanying me to the ship, put his hand upon mine, and said
something in a low voice, that was, I think, a prayer to God that He would
protect and bless and guard his boy, and then turned his face to the window,
and when presently I peeped at him, I saw that he had been weeping too.
Ah, dear little friends! let us always love our father and mother, and be
grateful to them. They suffer much for us when we are young, and when we
are incapable of understanding their anxieties and griefs. Later on in life we
find it all out ourselves, and it is as sweet as a blessing sent to us by them
from heaven if we can remember that we were always good, and loving, and
tender to them when we were little ones, and when they were alive to be
made happy by our behaviour.
When I look back from the hour of my trotting into the docks at my father’s
side, down to the time when I felt the ship heaving and plunging under me
upon the snappish curl of the Channel waters, all that happened takes so
misty a character that it is like peering at objects through a fog. Everything, of
course, was new to me, and all was startling in its way, confusing my little
brains; and it was a sort of Wonderland also.
The docks were full of business, and movement and hurry; huge cranes
were swiftly swinging out tons’ weight of cargo from the holds of ships to the
snorting accompaniment of steam machinery; dockyard labourers were
chorussing on the decks of the vessels, or bawling to one another on the
quayside; the earth trembled to the passage of heavy waggons; and the ear
was distracted by the shrill whistling and roaring puffing of locomotives. There
were fellows aloft on the ships, dismantling them of their spars, and rigging,
or bending sails, and sending up masts, and crossing-yards, and reeving gear
for a fresh voyage.
It was a brilliant October morning, with a keen shrill wind that made even
the dirty Thames water of the docks tremble into a diamond-bright flashing,
and in this wind you seemed to taste the aromas of many countries—coffee,
and spices, and fragrant produce, the mere flavour of which in the
atmosphere sent the fancy roaming into hot and shining lands.
The Lady Violet still lay alongside the quay. I recollect thinking her an
immense ship as we approached. Aloft she looked as heavy and massive as a
man-of-war, with her large tops, her canvas rolled up on the yards, and all her
sea-gear—a bewildering complication of ropes—in its place. She had a broad
white band along her sides, upon which were painted black squares to imitate
portholes. She was an old-fashioned ship, as I know now—though then I saw
but little difference between her and the rest of them that lay about. Her
stern was square and very handsomely gilt; there were large windows in it,
and the sunlight flashing in them made the long white letters of her name
stare out as though they were formed of silver. She had a handsome flag
flying at the mainmast head, exactly like the one that I wore in the badge on
my cap. The red ensign floated gaily at her peak, and at the fore-royalmast
head the Blue Peter—signal for sailing—was rippling against the light azure of
the sky.
My father seemed as much confused as I was by the bustle and novelty. He
grasped my hand, and we stepped over a broad gangway bridge on to the
ship’s deck. Here was confusion indeed! all sorts of ropes’ ends knocking
about, men on deck shouting to men in the hold, pigs grunting, babies crying,
cocks crowing, and hens cackling; steerage passengers bound out as
emigrants wandering dejectedly about; unshorn, melancholy men in slouched
hats, pale-faced women with hollow cheeks stained by recent tears, cowering
under the break of the poop, and gazing forlornly around them; and drunken
sailors on the forecastle bawling out coarse joking farewells to friends ashore.
We went up a ladder that conducted us to the upper-deck or poop, and I
noticed that along the rails on either side were stowed a great number of
bales of compressed hay as fodder for the sheep, which were bleating
somewhere forward, and for a cow that was now and then giving vent to a
sullen roar, as though she were vexed at being imprisoned in a great box.
There were several midshipmen on the poop running about. They glanced
at me out of the corner of their eyes as they passed. I could not but envy
them, for they seemed quite at home, whilst here was I, trembling nervously
by the side of my papa, staring up at the masts, and wondering if ever I
should be made to creep up those great heights, and if so, what was to
become of me when I had reached the top? There was no need, indeed, to
glance at my buttons to know that I was a “first voyager.” My wandering eyes
and open mouth were assurance as strong as though I had been labelled
“greenhorn.” My father, stepping up to one of the midshipmen, asked if the
captain was on board.
“I don’t think he is,” said the youngster.
“This is my son,” said my father, “who has come to join the Lady Violet. Are
there any formalities to go through—any book to be signed by him—we are
rather at a loss?”
All too young as I was to be an observer, I could yet see a spirit of laughing
mischief flash into the lad’s brown handsome face, and I have no doubt that
he would have told me to go forward and seek for the cook and report myself,
or have started me on some other fool’s errand of a like sort, but for a
sunburnt man in a blue-cloth coat coming up to us, and asking my father
what he wanted; on which the midshipman slunk away and joined two other
midshipmen, who, on his speaking to them, began to shake with laughter.
“No, there is nothing to be done, sir,” said the weather-stained man in
answer to my father’s question. “I suppose your chest is aboard?” he
exclaimed, looking at me. “Better go below and see that your kit’s arrived. We
shall be warping out in a few minutes.”
“Are you one of the officers, sir,” asked my father.
“I am the second mate, sir, and my name is Jones,” answered the other.
My father was about to put some further questions to him, but just then Mr.
Jones, bawling out “Right you are!” to some one who had called to him from
some part of the ship or the shore, rushed away.
CHAPTER II.
HIS FIRST DAY ON BOARD SHIP.

“Well, Tommy,” said my father, “as the ship will soon be leaving I had better
be off, as I do not want to go to Australia with you. God bless thee, my son.
Be a good lad; do not forget your prayers; remember to write to us as often
as you can send a letter”—and here his voice breaking, he ceased and
stooped to kiss me; but I drew away. I did not like to be kissed by my father
in the presence of the little bunch of midshipmen who were viewing us from
near the wheel. I feared they would regard it as an unmanly act, and sneer at
me afterwards as being girlish.
My father, with a sad smile, squeezed my hand and left me. Little boys are
often very sensitive on points of what they consider manliness. They will
laugh at this weakness when they grow older, but I think it is wise to humour
them. I afterwards heard—but I did not then know—that my father when he
stepped ashore walked straight to the building that was then called the
Brunswick Hotel, and posting himself at a window where I could not see him,
sat watching me with the tears in his eyes, until the ship had hauled through
the lock gates and I was no longer visible.
No one who has stood on board a large sailing ship for the first time, and
witnessed the proceeding of getting her under way, will wonder at the
confusion my mind was in as the Lady Violet hauled out into the river, and at
my inability therefore to recollect all that passed, I took very little heed of my
father’s leaving the vessel. I stood lost in amazement, staring about me like a
fool, my mouth wide open. I remember noticing the pier heads gliding past
the ship as we warped out stern first; people standing on the quayside
shouting to us, waving hats and handkerchiefs, some of them weeping; whilst
our passengers in groups along the line of bulwarks responded to these
farewells with kissing of hands, broken cries of “God bless you!” “Good-bye!”
and the like. I remember the sharp shouts of the mate on the forecastle
repeating the pilot’s orders, the half-tipsy chorusing of seamen heaving at the
capstan, the figure of a fellow at the helm revolving the spokes, first one way,
then another, the manœuvring of a little snorting tug to receive the line for
the hawser by which our great ship was to be towed down the river. Nobody
took any notice of me. I stood at the head of one of the poop ladders leaning
against the rail, wondering at the swiftness with which the people on the pier
heads, who continued to gesticulate towards us, were diminished into dwarf-
like proportions.
Four or five midshipmen hung about the poop, but they seemed too busy
with their thoughts, now that we were in the actual throes of leave-taking,
and had started in earnest upon our long voyage, to favour me with their
glances and grins.
The river was full of life—of barges and wherries, of dark-winged colliers,
swarming along under full breasts of sail; of Thames steamers cutting through
the sparkling grey waters with knife-like stems; of ships in tow like ourselves,
bound up or down; of huge majestic metal fabrics, gliding to their homes in
the docks after days of thunderous passage through the great oceans, or
floating regally past us on the way to the distant west or far more distant
east.
I know not how long I had thus stood staring, when a big, broad-
shouldered young fellow, with a face like a prize-fighter’s, yet of a kindly
expression, stepped up to me, and said, in a gruff, deep-sea note—
“Well, youngster, and who are you?”
“I am Master Rockafellar, sir,” I answered.
“That’s our livery you’ve got on,” said he; “you’re one of the midshipmen, I
suppose?”
“Yes, sir,” said I; “and are you a midshipman, please?”
“No,” he answered; “I’m third mate. What’s your name, again?”
“Master Rockafellar,” said I.
“Ha!” he exclaimed; “the right sort of name to go to sea with. Every ‘wave,’
as one’s grandmother calls it, would speak of itself as a ‘rock-a-fellow.’” He
burst into a mighty laugh, and then said kindly, “Well, well; I’ve heard of even
queerer names than ‘Rockafellar.’ Been below yet?”
“No, sir,” said I.
“Haven’t you seen your bedroom?”
“No, sir,” I answered again.
“Well, take my advice,” said he, “and jump below at once, and secure a
bunk, and see that your chest is all right—I suppose you’ve brought one—or
some of those ’tween-deck passengers down there will be borrowing your
mattress and forgetting to return it, and rigging themselves out in your
clothes.”
“My chest is locked, sir,” said I.
“And what of that?” he roared. “D’ye think there never was a handspike
aboard a ship since the days of Nelson? Jump below, jump below, I tell ye!”
“Please, sir, which is the way?” said I, trembling.
“Go down those steps,” said he, pointing to the poop ladder, “and just over
against the cuddy front there’s a black hole. Drop down it, for that’s the way.”
I at once stepped on to the main-deck, and saw a square aperture, which I
was afterwards informed was called the “booby hatch.” There was a little
crowd of third-class passengers standing round it, looking very wretched and
melancholy, two or three of the women holding babies, who cried incessantly.
I looked into the hatch; it seemed very dark beneath, and a close, most
unpleasant, but quite indescribable smell rose up through it—a sort of
atmosphere of onions, yellow soap, fumes of lamp-oil, the whole tinctured
with a peculiar flavour of shipboard. A short flight of perpendicular steps fell
to the bottom. I was too manly to ask my way of the women; so, perceiving a
sailor coiling away a rope upon a pin near the main-shrouds, I went up to
him, and said, “I want my bedroom; d’ye know where it is?”
He turned his eyes slowly on me, took a somewhat sneering survey of my
buttons, spat a mouthful of tobacco-juice into a scupper-hole, and then said,
whilst he proceeded with his work, “Better ask the capt’n.”
The sailor was too grumpy and surly a man for a little boy like me to
address a second time; so I made my way to the hatch, and put my leg over
into it, concluding that I should find somebody to tell me where my bedroom
was when I had descended. The ladder was perpendicular, and I was very
slow in stepping down it.
“Now then!” bawled a powerful voice: “up or down; one ways or t’other.
There ain’t too much light here; and who’s bin and made you think you’re
made o’ sheet glass?”
This remark, I found, was uttered by a seafaring man, one of the sailors of
the ship, I afterwards came to know, who had been told off to help our
handful of emigrants to secure their boxes. I think he was slightly in liquor; at
all events, I grew sensible of a distinct taste of rum-and-water on the air as I
jumped backwards on to the lower deck close beside him.
“Where is my bedroom?” said I.
“No bedrooms at sea, young ’un,” he
answered. “What callin’s yourn? Are ’ee a
sailor man? My precious eyes! there’s
buttons! See here, my lively: when the
shanks of them buttons is worn off, I’ll
give ye the value of a fardenswuth of
silver spoons for the whole boiling of
’em.”
“I promised my father not to sell my
clothes,” I answered, with dignity.
“Where’s my bedroom, I say?”
“Why, there,” said he, pointing with a
tar-stained stump of forefinger into the
dusk. “Shut your eyes and walk straight,
and your nose’ll steer ye the right course,
I lay.”
I spied a door to the right some little
“HE TURNED HIS EYES SLOWLY UPON
distance abaft the part of the deck that
ME.”
was pierced by the great mainmast, and
making for it, entered, and found myself
in a long narrow cabin fitted on either hand with a double row of bunks, or
sleeping-shelves, and lighted by three little round portholes, called “scuttles.”
Bright as the day was outside, in this cabin it was no better than twilight, and
I hung for some moments in the doorway, scarcely able to distinguish objects.
When presently I could fairly use my sight I took notice of a thin slip of a
table, penetrated by stanchions, up or down which it could be made to travel
as space happened to be wanted. At the aftermost extremity athwart this
interior were two or three shelves containing tin dishes, pannikins, coarse
black-handled knives and forks, jars of pickles, red tins of preserved potatoes,
and other such commodities: the produce, as I afterwards heard, of the
amount which each midshipman had to subscribe in a sum of ten guineas to
what was called “the mess”—and a mess it was!
Under these shelves stood a cask of flour, and another of exceedingly moist
sugar, and an immense jar of vinegar. Here and there against the bulkhead
partitions between the bunks hung a sou’wester or a coat of oilskin; whilst
under the lower tier of bunks you caught a glimpse of the soles and heels of
sea boots and shoes, with a thin canvas bag, perhaps, like a man’s leg. In
most of the bunks lay a heap of rude bedding, roughly-made mattresses, and
stout blankets.
Immediately facing the door there was stretched, in one of the upper
sleeping-shelves, a young red-faced youth. He was in his shirt and trousers,
and was smoking a short sooty clay pipe. He eyed me out of a pair of little
black eyes, which winked drowsily on either side of his immense nose, the
polished point of which caught the ruddy glow of his pipe-bowl as he sucked
at it, and shone over the edge of his bunk as though it were a glowworm.
There was nobody else in the cabin but this youth.

“‘IS THIS A BEDROOM?’ SAID I.”

“Is this a bedroom?” said I.


He expelled several mouthfuls of smoke before answering, and then
exclaimed, “Yeth.”
“Am I to sleep here, do you know?” said I.
“Can’t thay,” said he, lazily. “If you’re a midthipman, you do; if you aint,
you’ll be kicked out.” Saying which, he closed his eyes, and refused to answer
other questions, though, by his continuing to smoke, I knew he had not fallen
asleep.
I entered the cabin, and after peering a bit into the bunks, saw my bedding
in one of the two sleeping-places which ran athwartships. At this point my
memory grows misty again. I have some dim recollection of attempting to
make my bed, of hunting about for the sheets—not then knowing that sailors
do not use sheets at sea—of moodily getting into the bunk, and wishing that I
was at home again; of stretching myself, after a little, and falling asleep; of
being awakened by a hubbub of voices, and discovering that the berth was
full of midshipmen—nine “young gentlemen” in all, including myself—who
were sitting round the table, using the edge of their bunks for chairs, and
drinking tea out of pannikins, and hacking at a lump of cold roast meat.
This, I say, I recollect; also that I was invited by the third mate, who sat on
a cask at the head of the table, to arise and join the others, and drink tea
with them, which I did; that the handsome young fellow whom my father had
spoken to on the poop began with a grave face to ask me questions intended
to raise a laugh at my expense, and that he was abruptly silenced by the third
mate (whose name was Cock), who said to him, “See here, my lad: this is
your second voyage, and you are giving yourself airs on the strength of it.
Now, what are your talents as a sailor? Could you put a ship about? Could you
send a yard down? Could you take a star? D’ye know anything about stowing
a hold? See here, my heart of oak!—until you’ve got some knowledge of your
calling, don’t you go and try and make a fool of a lad who comes fresh to it.
Everybody’s got to begin, and so I tell you; and if before six months of
shipboard this young Master Rockafellar hasn’t more seamanship in any one
of his fingers than you’ve got in all your body, though this is your second year
at sea, then you shall call me a Chinaman, without risk of earning a kick for
the compliment.”
The lad blushed to the roots of his hair, and looked subdued. He was a
great powerful man was this third mate, and I seemed to feel with the
instincts of a boy that no sort of bullying or mean sneaking tyranny was likely
to be attempted so long as he made one of our company.
The tea was very strong, and the bottom of my pannikin was full of black
leaves. The liquor had a flavour of old twigs and stale molasses; the beef was
so hard that I could scarcely make my teeth meet in it, yet it was fresh, and it
was not long before the salt food upon which we had to live made me think
yearningly of it as a delicacy—as something for even a bite of which I would
have gladly “swapped” a shirt.
All this while the ship was being towed down the river. I was still in the
midshipman’s cabin when there was a great noise on deck—voices of men
shouting, sounds of feet running hastily—and on looking through one of the
portholes I saw the houses of a town just abreast, and noticed that they
moved slowly, and yet more slowly, until they came to a dead halt. We had
come to a mooring-buoy, for the night, off Gravesend; but one of the
midshipmen told me that we should be underway again long before this side
of the world was awake; by which he meant that the tug would take us in tow
at daybreak.
It was dark by this time. A boy who acted as our servant lighted a lamp
that was shaped like a coffee-pot, with the end of the wick coming out of the
spout. By this weak and fitful light the scene of the berth looked very strange
to my young, inexperienced eyes. All the midshipmen were below, some
smoking, some cutting up pipefuls from squares of black tobacco, jabbering
loudly about the pleasures they had taken during three months ashore. The
language was not of the choicest, and my young ears were frequently startled
by terms and expressions which I had never before heard. The third mate sat
with his legs over the edge of his bunk listening grimly.
“Well, young gentlemen,” he presently roared out, “three of you are new to
this ship this voyage, but there are six of you who sailed in her last year, and
when those six went ashore they were a deal more gentlemanly and careful in
their language than I now find ’em. Where, pray, did you pick up these fine
words? Not in your homes, I’ll warrant. Now hearken to me, mates; you’re not
going to make the better sailors for employing language which you wouldn’t
tolerate in the mouth of any man, speaking in the presence of your mothers
and sisters. You’re in my charge understand, and since you come to me as
young gentlemen, young gentlemen you shall be; so stand by and mind your
words!” saying which he looked at them one after the other, directing an
emphatic nod at each of the lads as he stared. After this I heard no more bad
words, and if I except a slip or two, I may truthfully say that when the voyage
had fairly commenced, and the lads had come well under the influence of Mr.
Cock, there never was afloat a better spoken body of youths than those which
occupied the midshipmen’s berth aboard the Lady Violet.
CHAPTER III.
HE SAILS FROM GRAVESEND.

The ship lay motionless as a rock on the smooth water off Gravesend;
nevertheless, owing to the strong fumes of the tobacco, probably coupled
with the close atmosphere of the berth, and its warm flavouring of lamp oil,
water-proof clothes, pickled onions, and black tea, I felt somewhat sick and
crept quietly out of the cabin, trusting that the fresh air on deck might revive
me. Just outside our berth, in the open space of ’tween-decks, which was
entered from above by means of the booby-hatch, were the emigrants’
quarters. We carried about thirty of these poor people, and here they now
were all of a jumble, using mine as well as the chests of the other
midshipmen for seats and tables, the women talking vehemently, some of
them still crying, here and there a man smoking in a sullen posture, others
sitting over greasy packs of cards, whilst a few children played at hide-and-
seek in and out of the sleeping-places, and amongst the emigrant’s bundles;
three or four quite young babies meanwhile setting the whole picture to music
with shrill, melancholy cries. A single lamp of the same pattern as ours
illuminated this grimy grotesque scene.
A SCENE IN THE EMIGRANTS’ QUARTERS.

I pushed my way on deck, but on my arrival found that it was raining hard,
which accounted for the emigrants being crowded below. There was shelter to
be had under the break of the poop, as the ledge of deck is called that
overhangs the entrance to the cuddy; and there I stood awhile, gazing along
the dark length of gleaming, streaming deck that was deserted, and listening
to the complaining of the wind, amid the stirless shadow of the spars and
rigging on high, or watching the damp and dusky winking of the lamps
ashore, or of the lights of ships at anchor round about us. Ah! thought I, this
is not so comfortable as being in my father’s snug parlour at home, with a
sweet and airy bedroom all to myself to pass the night in, and a kind mother
at the fresh and fragrant breakfast table next morning to help me to a plateful
of eggs and bacon, and a cup of fine aromatic coffee and cream! Maybe I
shed a tear or two; I was but a little boy fresh from home, and amidst a great
strange scene, with the darkness and the sobbing of the rain and the deserted
deck, and the cold noise of the running waters of the river washing along the
ship’s side to bitterly increase the sense of loneliness in my childish heart.
It was not long before I went below. Most of the midshipmen were turned
in, that is to say, they were lying down in their clothes and shoes with nothing
but their jackets removed. I thought I could not do better than follow their
example and how wearied I was I could not have imagined till I put my head
down upon the bolster at the end of my bunk, when I almost instantly fell
asleep.
Being a very green, raw, quite young hand, I could be of no use on deck for
the present, and it was for this reason, I suppose, they let me sleep in the
morning, for when I woke I was the only midshipman in the cabin. There was
a queer noise of scraping overhead, sounds as of the flinging down of coils of
rope, the noises of water being swooshed along the planks; and the sunlight
that shone through the portholes was tremulous with the play of glittering,
moving waters. I went on deck and found the ship in tow of the tug, with the
land a long way past Gravesend gliding astern, and the river so wide that over
the bows it looked like the ocean. There were jibs and staysails hoisted, and
the ship appeared to be sailing along. It was a fresh, windy morning; there
were great white clouds rolling from off the distant land over our mast-heads,
and the dark brown smoke of the tug ahead fled in a wild scattering low down
upon the waters. The decks were being “washed down” as it is called at sea;
sailors on legs naked to the knees were scrubbing and pounding away with
brushes, buckets of water were being emptied over the planks, and a sturdy
mariner with a whistle round his neck and great whiskers standing out from
his cheeks, went about amongst the seamen, directing them in a voice that
sounded like a roll of thunder. He was the boatswain. I was not a little
surprised to find the midshipmen with scrubbing brushes in their hands
washing down the poop. I mounted the ladder and stood a moment looking
on. One of them worked a pump just before the mizzen-mast, whilst another
filled buckets at it, the third mate threw the water about, and the middies
plied their brooms with the energy of a crossing-sweeper. The youth with a
great nose who spoke with a lisp was polishing the brass-rail that ran
athwartship in front of the poop. A man in a long coat and a tall rusty hat
paced the deck alone. His face might have been carved out of a large piece of
mottled soap. I afterwards found out that he was the pilot. There was another
man standing near the wheel. He had a ginger-coloured beard that forked out
from under his chin, pleasant dark-blue eyes and a copper-coloured face. It
was not long before I discovered that he was Mr. Johnson, the chief officer. He
came along in a pleasant way to where I stood staring.
“How is it you’re not at work, youngster?” said he.
“I’ve just woke up,” said I.
“Look here,” said he, “if you don’t call me sir, I shall have to call you sir, and
I am sure it’s easier for you to say it than for me. Pull your boots and
stockings off like a man, put them in that coil of rope there upon the hencoop,
tuck your trousers up, lay hold of that scrubbing brush yonder and see what
sort of job you’re going to make at whitening these decks.”
In a minute I was scrubbing with the rest of them, and it made me feel as if
I was on the Margate sands to be trotting about with bare feet, with the salt
brine sparkling and flashing about my ankles.
My memory at this point grows dim again, for I was rapidly approaching the
unpleasant experience of sea-sickness. I recollect that I helped to dry the
decks with a swab that was so heavy I could scarcely flourish it, and that I
was shown by the third mate how to coil away a rope over a pin, also that I
dragged with the others upon some gear which caused a staysail between the
mainmast and the mizzen-mast to ascend; I then went below to breakfast, at
which there was served up a dish of hissing brown steaks, each of them wide
enough to have served as a garment for my young ribs. But by this time
something of the weight of the wide sea beyond was in the river, the ship was
faintly pitching, much too faintly perhaps to be taken notice of by anything
but a delicate young stomach like mine. I felt that I was pale, and the sight of
the heap of great brown steaks floating handsomely in grease, which took a
caking of white, even as the eye watched, added not a little to the
uncomfortable sensation that possessed me. The others plunged their knives
and forks into the layers of meat and ate with avidity; but for my part I could
only look on.
“Take and turn in, my lad,” said the third mate kindly; “it’s bound to occupy
you a day or two to get rid of your longshore swash, and then we’ll be having
you jockeying the weather mizzen-topsail yard-arm, and bawling ‘haul out to
leeward’ in a voice loud enough to be heard at Blackwall.”
I was glad to take his advice, and was presently at my length in the bunk,
too ill to speak, yet with a glimmering enough of mind in me to bitterly
deplore that I had not heeded my mother’s counsel and remained at home.
The wind hardened as the river widened, and much dismal creaking and
groaning rose out of the hold and sides, the bulkheads, strong fastenings and
freight of the lofty fabric as she went rolling stately in the wake of the tug
that was thrashing through the hard green Channel ridges in a smother of
foam. The wind was south-east, I heard some of our fellows say, with a lot of
loose black scud flying along the marble face of the sky, and a gloomy
thickness to windward, that was promise of tough weather, ere we should
have settled the South Foreland well down upon the quarter. One of the lads
said that if the wind headed us yet more, we should bring up in the Downs,
and lie there till it blew a fair breeze, which might signify a fortnight’s waiting.
“If so,” says he, “I shall put on a clean shirt and go straight ashore, then
button my ears behind me, and never stop running till I get to London town;
for twenty miles of salt water’s enough for me; and here we are bound away
for six thousand leagues of it, with all the way back again on top!”
In this fashion the lads would talk as they came below from the deck, and
sick as I was I managed to heed enough of their conversation to pick up what
was going forward. I cannot express how I envied their freedom from sea-
sickness. Some were making their third voyage, others their second. I was the
only “first-voyager” as they call it. It sometimes rained on deck, and the
fellows would come below gleaming in oilskins, the sight of which made me
feel pitifully girlish, insomuch that on three several occasions I made a
desperate effort to get up and act my part of a sailor as they did theirs; but
the oppression of nausea was too violent, and down I lay again, saving the
third time when, contriving to feel my feet, the ship at the instant gave a
lurch which sent me headlong into one of the fore and aft bunks where I lay
half stunned, and so miserably sick that the third mate had to lift me in his
arms to enable me to return to my own bed.
Sea-nausea is at all times distressing, and I do not know that one is easier
for suffering in a fine saloon, with looking-glasses and flowers and the
electric-light, and the fresh breezes of heaven blowing through the open
skylights to keep the place sweet. But if this mal de mer, as the French call it,
is more unendurable in one interior than in another it must be so I think in a
midshipmen’s berth—at least such a berth as ours was:—Twelve sleeping
shelves and nine lads to sleep in them, with a huge giant of a third mate to fill
the tenth; a sort of twilight draining in through the three scuttles, the
immensely thick glass of which was often eclipsed by the roaring wash of a
green sea sweeping along the sides; a lamp burning night and day, from
whose untrimmed flame there arose to the ceiling of the cabin a pestilential
coil of smoke.
In these narrow gloomy quarters we lived and moved, and had our being.
Here we ate our meals, here we slept, here we washed ourselves, here the
youngsters smoked. Hardest part of all were the confusing noises made by
the emigrants just outside our berth. Unlashed chests slided to and fro;
children were incessantly falling down and squealing; many heart-disturbing
lamentations arose from such of the poor wretches as lay sick and helpless in
their dark bulkheaded compartments. They had to fetch their meals from the
galley, and not yet having acquired the art of walking on a tumbling deck,
those who had to bring the rations of beef or pork along, would repeatedly
come with a run through the booby-hatch, and lie at the bottom of the ladder
badly scalded in a little lake of pease-soup, or with the beef rolling away
among the chests, whilst the air resounded with execrations, scarcely stifled
by the complaining sounds of the ship’s fabric.
The third mate was very kind to me; told me there was no hurry; I was
welcome to lie in my bunk till I felt equal to coming on deck.
“I was sick for a fortnight when I first went to sea,” I heard him say. “I was
one of four apprentices. Those shipmates of mine were brutes, and the very
first night we were out they hauled me from my hammock and ran me to the
mizzen shrouds, up which they forced me to go, saying that the topgallant sail
would be clewing up shortly, and I must be in the cross-trees in readiness to
help furl it. A ratline carried away, and I fell through the rigging on to the
deck. I broke no bones, but I lay senseless, which so terrified the young
bullies that when I was taken to my hammock they never more offered to
trouble me. I was ill for a fortnight, I say, and the memory of it makes me
sorry for every youngster when he first comes to the life and is sea-sick.”
However, on the morning of the third day from our quitting Gravesend,
though I was still very ill, I could stand no longer the miseries of my
confinement to the cabin. Since I was bound to suffer, I thought it was better
to feel wretched in the open air than amid the smells and noise and gloom of
the midshipmen’s berth.
It was the forenoon watch, as the hours from eight to twelve are called.
The fellows who had been on deck since four o’clock had come below at eight
bells, and after breakfasting had turned in to smoke a pipe and then get some
sleep. They were in the port or chief mate’s watch, to which division of the
ship’s company I was supposed to belong, though I don’t remember how I

You might also like