Programming Reactive Extensions and LINQ 1st Edition Jesse Liberty
Programming Reactive Extensions and LINQ 1st Edition Jesse Liberty
Programming Reactive Extensions and LINQ 1st Edition Jesse Liberty
Programming Reactive Extensions and LINQ 1st Edition Jesse Liberty
1. Programming Reactive Extensions and LINQ 1st Edition
Jesse Liberty download pdf
https://ebookfinal.com/download/programming-reactive-extensions-and-
linq-1st-edition-jesse-liberty/
Visit ebookfinal.com today to download the complete set of
ebook or textbook!
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Learning C 3 0 3rd Edition Jesse Liberty
https://ebookfinal.com/download/learning-c-3-0-3rd-edition-jesse-
liberty/
Programming Microsoft LINQ in NET Framework 4 1st Edition
Pialorsi
https://ebookfinal.com/download/programming-microsoft-linq-in-net-
framework-4-1st-edition-pialorsi/
Learning ASP NET 2 0 with Ajax 1st ed Edition Jesse
Liberty
https://ebookfinal.com/download/learning-asp-net-2-0-with-ajax-1st-ed-
edition-jesse-liberty/
Reactive Programming with RxJS Untangle Your Asynchronous
JavaScript Code 1st Edition Sergi Mansilla
https://ebookfinal.com/download/reactive-programming-with-rxjs-
untangle-your-asynchronous-javascript-code-1st-edition-sergi-mansilla/
3. Beginning Java 8 APIs Extensions and Libraries Swing
JavaFX JavaScript JDBC and Network Programming APIs 1st
Edition Kishori Sharan
https://ebookfinal.com/download/beginning-java-8-apis-extensions-and-
libraries-swing-javafx-javascript-jdbc-and-network-programming-
apis-1st-edition-kishori-sharan/
Sams Teach Yourself C in 24 Hours Complete Starter Kit 3rd
Edition Sams Teach Yourself in 24 Hours Jesse Liberty
https://ebookfinal.com/download/sams-teach-yourself-c-in-24-hours-
complete-starter-kit-3rd-edition-sams-teach-yourself-in-24-hours-
jesse-liberty/
LINQ For Dummies John Paul Mueller
https://ebookfinal.com/download/linq-for-dummies-john-paul-mueller/
Lotman and Cultural Studies Encounters and Extensions 1st
Edition Andreas Schonle
https://ebookfinal.com/download/lotman-and-cultural-studies-
encounters-and-extensions-1st-edition-andreas-schonle/
LINQ for Visual C 2008 1st Edition Fabio Claudio
Ferracchiati
https://ebookfinal.com/download/linq-for-visual-c-2008-1st-edition-
fabio-claudio-ferracchiati/
5. Programming Reactive Extensions and LINQ 1st Edition
Jesse Liberty Digital Instant Download
Author(s): Jesse Liberty, Paul Betts
ISBN(s): 9781430237471, 1430237473
Edition: 1
File Details: PDF, 6.14 MB
Year: 2011
Language: english
7. For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
8. iv
Contents at a Glance
About the Authors......................................................................................................xi
About the Technical Reviewer..................................................................................xii
Acknowledgments...................................................................................................xiii
Foreword ................................................................................................................. xiv
Introduction............................................................................................................. xvi
■Chapter 1: Introducing LINQ and Rx ........................................................................1
■Chapter 2: Core LINQ .............................................................................................19
■Chapter 3: Core Rx.................................................................................................41
■Chapter 4: Practical Rx..........................................................................................57
■Chapter 5: Inside Rx ..............................................................................................77
■Chapter 6: LINQ to SQL...........................................................................................91
■Chapter 7: Reactive Extensions for JavaScript ...................................................111
■Chapter 8: ReactiveUI ..........................................................................................125
■Chapter 9: Testing With Rx ..................................................................................145
Index.......................................................................................................................153
9. xvi
Introduction
Right now, we as programmers are at an impasse—a transition period between the well-understood
world of imperative programming, and a world that is increasingly at odds with this model. In the ’80s,
everything was simple: one machine, one thread, no network.
CPUs are now scaling horizontally, adding more and more cores, instead of scaling the CPU speeds.
Network and disk performance are now increasingly requiring asynchronous I/O in order to build high-
performance solutions.
Our tools to write asynchronous code, however, haven’t kept up with the rest of the world—threads,
locks, and events are the assembly language of asynchronous programming. They are straightforward to
understand, but as the complexity of the application becomes larger, it becomes extremely difficult to
determine if a given block of code will run correctly with respect to the rest of the application.
We need a way to retain the asynchronous nature of modern applications, while also retaining the
deterministic nature of traditional imperative programming.
A compelling solution to these problems is functional reactive programming. This term sounds
academic and overwhelming, however, if you’ve ever written a formula in Excel, good news—you’ve
already done functional reactive programming.
Let’s go through that title piece by piece, starting with the word “functional.” Many people have a
definition of functional programming, often from their college computer science course that covered
Scheme or Common Lisp, usually something along the lines of, “it means never using variables.”
Instead, think of FP as a mindset: “How is the output of my program related to my input, and how
can I describe that relation in code?” In this book, we’ll examine Language Integrated Queries (LINQ), a
powerful technology that allows us to describe a result list based on an input list and a set of
transformations on that input.
The disadvantage to LINQ is that this technology only works on lists, not data that is incoming or
changing. However, there is a type of list that is hiding in plain sight, only disguised—events. Consider
the KeyUp event: for every key that the user presses, an object representing the key will be generated—
“H”–“e”–“l”–“l”–“o”.
What if we thought of an event as a list? What if we could apply everything we know about lists to
events, like how to filter them or create new lists based on existing lists?
Reactive Extensions allow you to treat asynchronous sources of information, such as events, and
reason about them in the same way that you currently can reason about lists. This means, that once you
become proficient with using LINQ to write single-threaded programs, you can apply your knowledge
and write similar programs that are completely asynchronous.
A warning: this book is not easy to understand on first grasp. Rx will stretch your brain in ways it’s
not used to stretching, and you, like the authors, will almost certainly hit a learning curve.
The results, however, are most definitely worth it, as programs that would be incredibly difficult to write
correctly otherwise, are trivially easy to write and reason with Reactive Extensions.
10. C H A P T E R 1
1
Introducing LINQ and Rx
In a sentence, LINQ is a powerful way to interact with and extract data from collections, while Rx is an
extension of LINQ targeted at asynchronous collections; that is, collections that will be populated
asynchronously, typically from web services or elsewhere in the cloud.
LINQ was introduced to C# programmers with C# 3.0. On the other hand, Reactive Extensions (Rx)
is an emerging technology, born in Microsoft DevLabs and adopted as part of a standalone full product
from Microsoft in 2011.
We believe that the use of LINQ will expand greatly in the next few years, especially in conjunction
with Reactive Extensions. Rx extends many of the principles and features of LINQ to a wide set of
platforms (including JavaScript) and will be a vital part of Windows Phone programming, where
asynchronous events are the rule. As the data we deal with becomes more complex, LINQ will help bring
order and clarity to .NET programming. Similarly, as more and more data is retrieved asynchronously
from the cloud, and elsewhere, Rx will help you create simpler, cleaner, and more maintainable code.
In this chapter you will learn why LINQ and Rx are important and you’ll examine some of the
fundamental operators of both LINQ and Rx. This will provide a context for the coming chapters in
which we’ll dive deeper into both LINQ and Reactive Extensions.
■ Note Throughout this book we use Rx as shorthand for Reactive Extensions, just as we use LINQ for Language
Integrated Query.
What LINQ Is
LINQ (Language Integrated Query)—pronounced “link”—extends .NET to provide a way to query and
transform collections, relational data, and XML documents. It provides a SQL-like syntax within C# for
querying data, regardless of where that data originates.
LINQ also brings a much more declarative or functional approach to programming than previously
available in .NET.
11. CHAPTER 1 ■ INTRODUCING LINQ AND RX
2
■ Note Functional programming is one approach to creating declarative code.
In declarative programming, the logic and requirements are expressed but the execution steps
are not.
LINQ and Rx are functional aspects of the C# language, in that they focus more on what you are
trying to accomplish than on the steps required to get to that goal. Most programmers find that the
functional approach makes it cleaner and easier to maintain code than the more traditional, imperative
style of programming.
With the imperative approach, a program consists of a series of steps—often steps within loops—
that detail what to do at any given moment. In declarative programming, we’re able to express what is
required at a higher level of abstraction.
It is the difference between saying on the one hand (imperative): “Open this collection, take each
person out, test to see if the person is a manager, if the person is a manager—increase the salary by 20
percent, and put the person back into the collection;” and, on the other hand saying (declarative): “Raise
the salary of all the managers by 20 percent.”
The imperative style tells you how to accomplish the goal; the declarative style tells you what the
goal is. Using concrete programming examples of Rx and LINQ, this book will demonstrate differences
that are more declarative than imperative.
What Rx Is
Reactive Extensions provide you with a new way to orchestrate and integrate asynchronous events, such
as coordinating multiple streams as they arrive asynchronously from the cloud. With Rx you can
“flatten” these streams into a single method, enormously simplifying your code. For example, the classic
async pattern in .NET is to initiate each call with a BeginXXX method and end it with an EndXXX
method, also known as the Begin/End pattern. If you make more than a few simultaneous asynchronous
calls, following the thread of control becomes impossible very quickly. But with Rx, the Begin/End
pattern is collapsed into a single method, making the code much cleaner and easier to follow.
Reactive Extensions have been described as a library for composing asynchronous and event-based
programs using observable collections.1
Let’s take a closer look at each of these attributes.
• Composing: One of the primary goals of Reactive Extensions is to make the work
of combining asynchronous operations significantly easier. To do this, the data
flow must be clarified and the code consolidated so that it is less spread out
throughout your application.
• Asynchronous: While not everything you’ll do in Rx is asynchronous, the async
code you write will be simpler, easier to understand, and thus far easier to
maintain.
1
MSDN Data Developer Center, “Reactive Extensions,” http://msdn.microsoft.com/
en-us/data/gg577609.
12. CHAPTER 1 ■ INTRODUCING LINQ AND RX
3
• Event-based: Rx can simplify even traditional event-based programs, as you’ll see
later in the book when we examine implementation of drag and drop.
• Observable collections: The bread and butter of Rx. An observable collection is a
collection whose objects may not be available at the time you first interact with it.
We will return to this topic throughout this book. For now, the most useful
analogy is that observable collections are to Rx what enumerable collections are to
LINQ.
■ Caution There is significant potential for confusion between the Silverlight ObservableCollection and
Observable Collections in Rx. The former is a specific generic collection and the latter is any collection that
implements IObservable, which will be described in detail later in this book.
Getting Rx and LINQ
If you have .NET 4 or later, you have LINQ—it is built into the framework. Similarly, if you have the
Windows Phone tools installed, you have Rx for Windows Phone. To obtain the latest edition of Rx for
other .NET platforms, you can go to the Rx site (http://msdn.microsoft.com/en-us/data/gg577610) on
MSDN. There you will find complete instructions for downloading and installing Rx for Phone,
Silverlight, WPF (Windows Presentation Foundation), Xbox, Zune, and JavaScript.
You can also install Rx on a project basis in Visual Studio 2010 (and above) using NuGet. For more
information, visit the NuGet project page at http://nuget.codeplex.com/.
Distinguishing Rx and LINQ
LINQ is brilliant at working with static collections, allowing you to use a SQL-like syntax to query and
manipulate data from disparate sources. On the other hand, Rx’s forté is in working with what we call
future collections—that is collections that have been defined, but not yet fully populated.
LINQ requires that all the data be available when we first start writing our LINQ statements. That is,
to build a new collection with LINQ, we need a starting collection.
What happens, however, if we don’t have all the data? Imagine trying to write a service that operates
on live, stock-trading data, in which case we want to operate on incoming streams of data in real-time.
LINQ would not know what to do with this, as a stream is not a static collection—its contents will arrive,
but they’re not there yet, and the timing of their arrival is not predictable. Rx allows us to operate on this
kind of data just as easily as we can operate on static data with LINQ.
There is a cognitive boot-strap problem for anyone learning Reactive Extensions, just as there is
with LINQ. At first, the Rx code appears confusing and convoluted, and thus difficult to understand and
maintain. Once you become comfortable with the syntax and the “mind set,” however, the code will
seem simpler than “traditional” programming; and many complex problems devolve to rather simple
solutions.
The comparison between LINQ and Rx is not coincidental; these are deeply-related technologies.
And, you can see the relationship in very practical ways.
In LINQ, we take an input collection, and build a pipeline to get a new collection. A pipeline is
assembled in stages, and at each stage something is added, removed, or refined—until we end up with a
13. CHAPTER 1 ■ INTRODUCING LINQ AND RX
4
new collection. The truth is, however, that the new collection is really just a modified version of the
original collection.
At first glance, collections and streams are very different, but they are related in key ways, which is
why we refer to streams as future collections. Both streams and collections are sequences of items in a
particular order. LINQ and Rx let us transform these sequences into new sequences.
Throughout this book and when you are trying out the examples, always have this question in your
head: “How is the sequence that I want related to the sequence that I have?” In other words, the LINQ or
Rx pipeline that you build describes how the output is created from the input.
Why Bother?
After all is said and done, the practical programmer wants to know if the benefits of learning LINQ and
Rx are worth the investment of time and effort. What do these technologies bring to the party that you
can’t get elsewhere?
LINQ and Rx are:
• First-class members of .NET. This allows for full support from IntelliSense and
syntax highlighting in Visual Studio and LINQPad.
• Designed to work with all forms of data, from databases to XML to files.
• Highly extensible. It allows you to create your own libraries in order to extend
their functionality.
• Composable. As noted, both LINQ and Rx are used to combine and compose more
complex operations out of simpler building blocks.
• Declarative. LINQ and Rx bring a bit of functional programming to your code, as
described later in this chapter.
• Simplifying. Many constructs that take just a line or two of LINQ or Rx would
otherwise take many complex lines of confusing code.
We’ll take a closer look at Rx and LINQ throughout the rest of the book, but first, you need to get
acquainted with the tools you’ll use: Visual Studio and LINQPad.
Choosing your IDE
The examples in this book can be run in any version of Visual Studio 2010 or later, or, with very minor
modifications, in LINQPad, a free utility (download at http://linqpad.net) that provides an easy way to
quickly try out sets of LINQ statements without the overhead of a complete development environment.
Let’s look at a simple example, first using Visual Studio and then LINQPad. To begin, open Visual
Studio and create a new Console Application named QueryAgainstListOfIntegers. The complete source
code is as follows:
14. CHAPTER 1 ■ INTRODUCING LINQ AND RX
5
using System;
using System.Collections.Generic;
using System.Linq;
namespace QueryAgainstListOfIntegers
{
internal class Program
{
private static void Main( string[ ] args )
{
var list = new List<int>( ) { 1, 2, 3, 5, 7, 11, 13 };
var enumerable = from num in list
where num < 6
select num;
foreach ( var val in enumerable )
Console.WriteLine( val );
}
}
}
This small program illustrates a number of important things about LINQ syntax and features that
appeared for the first time in C# 3.0 and 4.0. Before we begin our analysis, however, let’s take a look at
how the tools can make it easy to create and run the code.
You can copy and paste the LINQ statements at the heart of the program from Visual Studio into
LINQPad to try them out in that utility. To do this, first set the language in LINQPad to “C# Statements”
and copy in the following code:
var list = new List<int>( ) { 1, 2, 3, 5, 7, 11, 13 };
var enumerable = from num in list
where num < 6
select num;
foreach ( var val in enumerable )
Console.WriteLine( val );
■ Note You do not need the using statements or the method structures; just the LINQ statements that you want
to run.
Run this code with Visual Studio and then with LINQPad. You’ll see that they both produce the
same result, as follows:
15. CHAPTER 1 ■ INTRODUCING LINQ AND RX
6
1
2
3
5
C# and .NET Fundamentals
Now that you have both tools working, let’s take this small program apart line by line and examine the
constructs it uses. In the next section, we’ll review some features of C# and .NET, whose mastery is
fundamental to Rx and LINQ.
Var
Let’s consider the program from the beginning. The first line could have been written as follows:
List<int> list = new List<int>( ) { 1, 2, 3, 5, 7, 11, 13 };
The results would have been identical. The advantages of the var keyword are that you avoid
redundancy and that it is a bit terser. Further, there are times when you, as the programmer, may not
know the type and letting the compiler infer the type (as is done with var) can be a tremendous time-
saver—why look up the type when the compiler can figure it out?
Make no mistake, however; variables and objects declared with var are type safe. If you were to
hover your cursor over the variable name list, you’d find that it is of type List<int>, as shown in
Figure 1-1.
Figure 1-1. Showing that list is type safe
You can assign list to another List<int>, but if you try to assign it to anything else (for example, a
string) the compiler will complain.
Collection Initialization
A second thing to note in this very first line of the program is the use of initialization for the list.
new List<int>( ) { 1, 2, 3, 5, 7, 11, 13 };
Initialization follows the new keyword and the parentheses and is surrounded by braces. The
initialization has the same effect as if you had it written as follows:
16. CHAPTER 1 ■ INTRODUCING LINQ AND RX
7
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7);
list.Add(11);
list.Add(13);
But again, initialization is easier to read and to maintain.
The following three lines constituted a LINQ query expression:
var enumerable = from num in list
where num < 6
select num;
This begins with the use of the keyword var, this time for the variable named enumerable. Once
again enumerable is type safe, in this case the variable enumerable’s true type is IEnumerable<int>.
The first line of the LINQ query is a from statement, in this case creating the temporary variable
number and indicating that we are selecting from a list of integers named list.
The second line is a where clause which narrows the answer space to those values that are less than
six. The final line is a select statement or projection of the results.
The net effect of these three lines of code is that enumerable is an IEnumerable of integers that
contains all of the values from the list whose value is less than six.
IEnumerable
Because enumerable is an IEnumerable, you can run a foreach loop over it, as done here.
As will be noted many times in this book, IEnumerable is the heart of LINQ, and as we will see,
IObservable is the heart of Reactive Extensions.
IEnumerable is an interface; classes that implement that interface will provide MoveNext(), Current()
and Reset().
Typically you can ignore this implementation detail, as you do when using for each, but
understanding how IEnumerable works is critical to seeing the connection between Link and Reactive
Extensions.
You can, in fact, rewrite the foreach loop using the following operators:
var e = enumerable.GetEnumerator( );
while ( e.MoveNext( ) )
{
Console.WriteLine( e.Current );
}
This will produce the same result, and in fact, the foreach construct should best be thought of as
shorthand.
Properties
Properties have the wonderful characteristic of appearing to be member-fields to the client of the class,
allowing the client to write, for example, the following:
17. CHAPTER 1 ■ INTRODUCING LINQ AND RX
8
int x = thePerson.Age; // Age is a property that appears to be a field
In this case, Age will appear to the author of the class as a method, allowing the owner of the class to
write the following:
public int Age
{
get { return birthdate – DateTime.Now; }
set { //... }
}
Automatic Properties
In a normal property, there is an explicit getter and setter; however, it is very common to find yourself
writing something like the following:
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
In this common idiom, you have a backing variable and the property does nothing but return or set
the backing variable. To save typing, C# now lets you use automatic properties.
public int Age { get; set; }
The IL code produced is identical—the automatic property is just shorthand for the idiom.
Note that automatic properties require both a setter and a getter (though one can be private) and
you cannot do any work in either. That is, if your getter or setter needs to do any work (for example, call
a method) then you must revert to using normal syntax for properties.
Object Initialization
Assume that you create a Person class that looks like the following:
public class Person
{
public string FullName { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
18. CHAPTER 1 ■ INTRODUCING LINQ AND RX
9
The traditional way to instantiate an object and set its values is as follows:
var person = new Person();
person.FullName = "Jesse Liberty";
person.Address = "100 Main Street, Boston, MA";
person.Email = "jliberty@microsoft.com";
person.Phone = "617-555-1212";
Object initialization lets you initialize the properties in the Person instance, as follows:
var per = new Person()
{
FullName = "Jesse Liberty",
Address = "100 Main Street, Boston, MA",
Email = "jliberty@microsoft.com",
Phone = "617-555-1212"
};
Delegates
Much ink has been spilled attempting to explain delegates, but the concept is really fairly simple. A
delegate type is the definition of an object that will “hold” a method. At the time you create a delegate
type, you don’t necessarily know exactly which method it will hold, but you do need to know the return
type and parameters of that method.
A delegate instance is an instance of a delegate type. By creating an instance of the delegate, you
can use that instance to invoke the method it “holds.” For example, you might know that you are going
to invoke one or another method that determines which shape to draw, but you have a number of such
methods. Each of these methods returns a string (with the name of the shape) and each takes an integer
(used to decide which shape will be drawn). You would declare the delegate type as follows:
public delegate string Shaper (int x);
You would declare the instance as follows:
Shaper s = Shape;
Shape is the name of a method. The following is shorthand for:
Shaper s = new Shaper(Shape);
You would invoke the Shape method through the delegate with the following:
s(3);
This, again, is shorthand for the following:
s.Invoke(3);
The result would be identical to calling the following:
Shape(3);
The following is a complete program you can drop into LINQPad to see this at work:
19. CHAPTER 1 ■ INTRODUCING LINQ AND RX
10
public delegate string Shaper (int x);
void Main()
{
Shaper s = Shape;
string result = s( 3 );
Console.WriteLine( result );
}
static string Shape(int x)
{
if ( x % 2 == 0 )
return "Circle";
else
return "Square";
}
Anonymous Methods
Anonymous methods allow you to use an inline, unnamed delegate. Thus, the previous program could
be rewritten as follows:
public delegate string Shaper (int x);
void Main()
{
Shaper s = delegate(int x)
{
if ( x % 2 == 0 )
return "Circle";
else
return "square";
};
string result = s( 3 );
Console.WriteLine( result );
}
Lambda Expressions
Anonymous methods are made somewhat obsolete by lambda expressions. The previous could be
rewritten as follows:
public delegate string Shaper (int x);
void Main()
{
Shaper s = x =>
{
if ( x % 2 == 0 )
return "Circle";
else
return "Square";
20. CHAPTER 1 ■ INTRODUCING LINQ AND RX
11
};
string result = s( 3 );
Console.WriteLine( result );
}
Lambda expressions are just a shorthand notation for declaring delegates.
To see this at work, let’s begin by creating a very simple (if absurd) program that declares a delegate
to a method that takes two integers and returns a string, and then uses that delegate to call the method.
public MainPage( )
{
InitializeComponent( );
Func<int, int, string> AddDelegate = Add;
string result = AddDelegate( 5, 7 );
TheListBox.Items.Add( result );
}
private string Add( int a, int b )
{
return ( a + b ).ToString( );
}
Taking this apart, on line 4 we declare AddDelegate to be a delegate to a method that takes two
integers and returns a string, and we assign that delegate to the Add method declared at the bottom of
the listing. We then invoke the method through that delegate on line 5, and on line 6 we add the result to
the list box we created in MainPage.xaml.
Lambda syntax allows us to write the same thing much more tersely.
Func<int, int, string> AddLambda = ( a, b ) => ( ( a + b ).ToString( ) );
result = AddLambda( 3, 8 );
TheListBox.Items.Add( result );
The first line (broken over two lines to fit) declares AddLambda to be a lambda expression for a
method that takes two integers and returns a string, and then replaces the body of the method it points
to with what is written to the right of the equal sign. Immediately to the right of the equal sign, in
parentheses are the parameters. This is followed by the lambda symbol (=>) usually pronounced “goes
to” and that is followed by the work of the anonymous method.
Lay them out side by side and the left-hand side is identical, as follows:
Func<int, int, string> AddDelegate =
Func<int, int, string> AddLambda =
To the right of the equal sign, the method takes its parameters and the lambda takes its parameters,
as follows:
( int a, int b )
( a, b )
The lambda, however, uses type inference to infer the type of the parameters.
The body of the method and the body of the lambda expression are nearly identical.
21. CHAPTER 1 ■ INTRODUCING LINQ AND RX
12
private string Add( int a, int b )
{
return ( a + b ).ToString( );
}
=> ( ( a + b ).ToString( ) );
Once you have the mapping in your head, it all becomes a trivial exercise, and you quickly become
very fond of lambda expressions because they are easier to type, shorter, and easier to maintain.
Note that if you do not have any parameters for the lambda, you indicate that with empty
parentheses, as follows:
() => ( // some work );
Hello LINQ
Let’s take a look at another very simple LINQ program in which we extract the even numbers from a list
of numbers (which, admittedly, can be done even more easily without LINQ!), as shown in Listing 1-1.
Listing 1-1. Not Hello World
List<int> ints = new List<int>()
{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
var query = from i in ints
where i % 2 == 0
select i;
foreach ( var j in query )
Console.Write ("{0} ", j);
The output is as follows:
2 4 6 8 10 12 14
The structure of this program is basic to almost any LINQ program. We begin with an enumerable
collection (our List of integers). The heart of the program is the LINQ query, which begins (always) with
a from statement and ends (always) with a select (projection) statement, as shown here or with group
by. In the middle are filters (the where statement) or one or more of the LINQ operators that we’ll be
discussing throughout the book.
The result of the query is stored in the local variable query and is itself an IEnumerable, which is why
you can iterate over it in the foreach loop.
We’ll say this repeatedly throughout the book: in LINQ and Rx you begin with a collection and you
end with a collection.
22. CHAPTER 1 ■ INTRODUCING LINQ AND RX
13
Hello Rx
The problem with creating your first Rx program is that if it is simple enough to qualify for the job, then
it is too simple to do anything more useful than what could be done without it. The following is an
example:
var input = Observable.Range(1,15);
input.Subscribe(x => Console.WriteLine("The number is {0}", x));
As you’ll learn in Chapter 3, the Range operator takes two parameters: a starting value and the
number of values to generate. In this case, it will generate the numbers 1 through 15. The return of
Observable.Range is of type IObservable of the inferred type int. If you hover over the input in the first
line —in LINQPad or Visual Studio, but not, unfortunately, in this book—you will see that it is of the
following type:
System.IObservable<int>
As an IObservable you can subscribe to it, which we do on the second line. The lambda statement
can be read as “for each value in the IObservable I subscribe to, run the statement
Console.WriteLine(...).” The output is as follows:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10
The number is 11
The number is 12
The number is 13
The number is 14
The number is 15
You’ll read much more about observable collections and how to subscribe to them in this and future
chapters.
Collections
Both LINQ and Rx work with collections. LINQ works with collections that implement IEnumerable,
which we will call enumerable collections. Rx works with collections that implement an extension to
IEnumerable, IQueryable, which will refer to as observable collections.
The enumerable collection is familiar, as it is the basis for foreach loops in C#. Each enumerable
collection is able to provide the Next item in the collection until the collection is exhausted. The details
of how this is done will be covered later in the book.
23. CHAPTER 1 ■ INTRODUCING LINQ AND RX
14
Enumerable Collections
Every generic collection provides the ability to enumerate the values. This means that each collection
allows you to ask for the first element, then the next, and the following and each element in turn until
you stop asking or the collection runs out of elements.
The underlying mechanism is that these collections implement IEnumerable. The IEnumerable
interface is as follows:
Public interface IEnumerable<T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
The GetEnumerator method returns an IEnumerator. The IEnumerator interface is as follows:
Public interface IEnumerator
{
Object Current { get; }
Bool MoveNext();
Void Reset();
}
You can rewrite Listing 1-1 with an explicit enumerator, as follows:
List<int> ints = new List<int>()
{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
var query = from i in ints
where i % 2 == 0
select i;
IEnumerator<int> e = ints.GetEnumerator();
while (e.MoveNext())
{
Console.WriteLine(e.Current);
}
In fact, the foreach loop is just a shorthand way of writing these examples.
Observable Collections
Rx works with an observable collection, itself based on the Observer design pattern (see the upcoming
sidebar).
As noted, a Reactive Extensions observable collection is not the same thing as a Silverlight
ObservableCollection control, though both are based on the observer design pattern.
■ Note Unless specifically stated otherwise, for the remainder of this book, if we use the term “observable
collection,” we mean the Rx collection type, not the Silverlight control.
24. CHAPTER 1 ■ INTRODUCING LINQ AND RX
15
THE OBSERVER DESIGN PATTERN
The Observer design pattern was first codified in Design Patterns: Elements of Reusable Object-Oriented
Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1994). The
four authors are affectionately known as the “Gang of Four” and the book is often referred to as the “GOF
(pronounced goff ) Book.”
The essence of the Observer pattern is that there is an observable object (such as a clock), and there are
observers who wish to be informed when the observable changes (e.g., when a second passes).
An ObservableCollection in Silverlight implements this pattern in that it automatically raises
PropertyChanged notifications for any object in the collection that is altered.
The observable collection used by Rx, on the other hand, is a more general implementation of the Observer
pattern, allowing for other objects to subscribe to any change whatsoever in the collection (including the
arrival of new entries).
The term subscribe comes from the closely related Publish and Subscribe design pattern. In fact, the
Observer pattern is a subset of Publish/Subscribe. The observable (clock) can be said to publish certain
events (e.g., a clock tick) and the observers can be said to subscribe to those events. This is very much
the pattern with event handling in .NET, in which interested objects might subscribe to a button’s click
event.
For more coverage of the Publish/Subscribe and its patterns, please see the Wikipedia articles at
http://en.wikipedia.org/wiki/Publish/subscribe and at
http://en.wikipedia.org/wiki/Observer_pattern, respectively.
Observable Collections vs. Enumerable Collections
Enumerable collections have all their members present at the moment that you are ready to work with
them. You can “pull” each item from the collection when you are ready for it, adding, for example, each
in turn to a list box.
An observable collection, however, does not have its members available when first created; the
members will be added to the collection over time (perhaps by acquiring them from a web service). In
this sense, an observable collection is a “future collection.” As the members of the observable collection
are added, they are pushed out to the subscribers who have registered with the collection, who may then
work with these members as they each become available.
In the next section we’ll work through an example that will clarify this discussion.
Example: Working with Enumerable and Observable Collections
In this example, we’re going to create a pair of ListBoxes for a Windows Phone. We’ll populate one from
an enumerable collection and the other from an observable collection.
25. CHAPTER 1 ■ INTRODUCING LINQ AND RX
16
The following tells how:
1. Fire up Visual Studio, create a new Windows Phone project, and on the first
page divide the Content panel into two columns. Place a ListBox in each of
the two columns, naming the first list box, lbEnumerable, and the second,
lbObservable.
2. Add a reference to each of the following libraries:
Microsoft.Phone.Reactive
System.Observable
3. Add a using statement, as follows:
using Microsoft.Phone.Reactive
4. Next, we need some data so let’s initialize a List<string> with the names of
the first five American presidents, as follows:
public partial class MainPage :
PhoneApplicationPage
{
readonly List<string> names =
new List<string>
{
"George Washington",
"John Adams",
"Thomas Jefferson",
"James Madison",
"James Monroe",
"John Quincy Adams"
};
■ Note Read List<string> as “list of string.”
This list will be the source for populating both list boxes. We’ll do all of the work in a method called
PopulateCollection(), which we’ll call from the page’s constructor.
5. In the first part of PopulateCollection(), we’ll take the traditional approach
and iterate through each member of the collection, adding each president’s
name to the list box. To do that, add the following code in MainPage.xaml.cs.:
private void PopulateCollection( )
{
foreach ( string pName in names )
{
lbEnumerable.Items.Add( pName );
}
27. regicides on their shoulders that has brought these visitations on our
people. He discoursed largely of the matter of the Gibeonites, and
exhorted us to quick vengeance.”
Dr. Reede could not remember any text which taught that
wreaking vengeance on man was the way to propitiate God. He
could not suppose that this disastrous defeat abroad would have
been averted by butchering the regicides in celebration of the King’s
marriage, as had been proposed.
The King had not yet had time to comprehend the news of this
defeat. On hearing of it, he seemed in a transient state of
consternation; marvelled, as his subjects were wont to do, what was
to become of the kingdom at this rate; and signified his wish to be
left with the messenger, the Duke of York alone remaining to help
him to collect all the particulars. The company accordingly withdrew
to curse the enemy, wonder who was killed and who wounded, and
straightway amuse themselves, the ladies with the dice-box, the
gentlemen with betting on their play, and all with the feats of a
juggler of rare accomplishments, who was at present under the
patronage of one of the King’s favourites.
When Palmer had told his story and was dismissed, Edmund was
called in, and, at his own request, was attended by his brother-in-
law,—the discreet gentleman of excellent learning, who might aid
the project to be now discoursed of. The King did, at length, look
grave. He supposed Edmund knew the purpose for which his
presence was required.
“To receive his Highness the Duke’s pleasure respecting the navy
accounts that are to be laid before Parliament.”
“That is my brother’s affair,” replied the King. "I desire from you,—
your parts having been well commended to me,—some discreet
composure which shall bring our government into less disfavour with
our people than it hath been of late."
Edmund did not doubt that this could easily be done.
"It must be done; for in our present straits we cannot altogether
so do without the people as for our ease we could desire. But as for
the ease,—there is but little of it where the people are so
changeable. They have forgot the flatteries with which they hailed
28. us, some short while since, and give us only murmurs instead. It is
much to be wished that they should be satisfied in respect of their
duty to us, without which we cannot satisfy them in the carrying on
of the war."
The Duke of York thought that his Majesty troubled himself
needlessly about the way in which supplies were to be obtained from
the people. Money must be had, and speedily, or defeat would follow
defeat; for never were the army and navy in a more wretched
condition than now. But if his Majesty would only exert his
prerogative, and levy supplies for his occasions as his ancestors had
done, all might yet be retrieved without the trouble of propitiating
the nation. The King persisted however in his design of making his
government popular by means of a pamphlet which should flatter
the people with the notion that they kept their affairs in their own
hands. It was the shortest way to begin by satisfying the people’s
minds.
And how was this to be done? Dr. Reede presumed to inquire.
Charles, thoroughly discomposed by the news he had just heard, in
addition to a variety of private perplexities, declared that nothing
could be easier than to set forth a true account of the royal poverty.
No poor gentleman of all the train to whom he was in debt could be
more completely at his wit’s end for money than he. His
wardrobeman had this morning lamented that the King had no
handkerchiefs, and only three bands to his neck; and how to take up
a yard of linen for his Majesty’s service was more than any one
knew.
Edmund glanced at his own periwig in the opposite mirror, and
observed that it would be very easy to urge this plea, if such was his
Majesty’s pleasure.
“Od’s fish! man, you would not tell this beggarly tale in all its
particulars! You would not set the loyal housewives in London to
offer me their patronage of shirts and neckbands!”
“Besides,” said the Duke, “though it might be very easy to tell the
tale of our poverty, it might not be so easy to make men believe it.”
Dr. Reede here giving an involuntary sign of assent, the King
would know what was in his mind. Dr. Reede, as usual, spoke his
29. thoughts. The people, being aware what sums had within a few
months fallen into the royal treasury, would be slow to suppose that
their king was in want of necessary clothing.
“What! the present to the Queen from the Lord Mayor and
Aldermen? That was but a paltry thousand pounds.”
Dr. Reede could not let it be supposed that any one expected the
King to benefit by gifts to his Queen.
Charles looked up hastily to see if this was intended as a reproach,
for he had indeed appropriated every thing that he could lay his
hands on of what his dutiful subjects had offered to his Queen, as a
compliment on her marriage. The clergyman looked innocent, and
the King went on,—
"And as for her portion,—twenty such portions would not furnish
forth one war, as the people ought to know. And there is my sister’s
portion to the Prince of Orleans soon to be paid. If the people did
but take the view we would have them take of our affairs at home
and abroad, we should not have to borrow of France, and want
courage to tell our faithful subjects that we had done so."
Edmund would do his best to give them the desired opinions. Dr.
Reede thought it a pity they could not be by the King’s side,—aye,
now on board this very boat, to understand and share the King’s
views, and thus justify the government. As a burst of admiration at
some of the juggler’s tricks made itself heard in the cabin at the very
moment this was said, the King again looked up to see whether
satire was intended.
Edmund supposed that one object of his projected pamphlet was
to communicate gently the fact of a secret loan of 200,000 crowns
from France, designed for the support of the war in Portugal, but so
immediately swallowed up at home that it appeared to have
answered no more purpose than a loan of so many pebbles, while it
had subjected the nation to a degradation which the people would
not have voluntarily incurred. This communication was indeed to be
a part of Edmund’s task; but there was a more important one still to
be made. It could not now long remain a secret that Dunkirk was in
the hands of the French——
30. “Dunkirk taken by the French!” exclaimed Dr. Reede, not crediting
what he heard. “We are lost indeed, if the French make aggressions
like this.”
“Patience, brother!” whispered Edmund. “There is no aggression in
the case. The matter is arranged by mutual agreement.”
Dr. Reede looked perplexed, till the Duke carelessly told him that
Dunkirk had been sold to the French King. It was a pity the nation
must know the fact. They would not like it.
“Like it! Dunkirk sold! Whose property was Dunkirk?” asked Dr.
Reede, reverting to the time when Oliver’s acquisition of Dunkirk was
celebrated as a national triumph.
“We must conduct the bargains of the nation, you know,” replied
the Duke. “In old times, the people desired no better managers of
their affairs than their kings.”
“’Tis a marvel then that they troubled themselves to have
Parliaments. Pray God the people may be content with what they
shall receive for a conquest which they prized! Some other goodly
town, I trust, is secured to us; or some profitable fishing coast; or
some fastness which shall give us advantage over the enemy, and
spare the blood of our soldiers.”
“It were as well to have retained Dunkirk as taken any of these in
exchange,” said the King;—a proposition which Dr. Reede was far
from disputing. “Our necessities required another fashion of
payment.”
"In money!—and then the taxes will be somewhat lightened. This
will be a welcome relief to the people, although their leave was not
asked. There is at least the good of a lifting up of a little portion of
their burdens."
“Not so. We cannot at present spare our subjects. This 400,000l.
come from Dunkirk is all too little for the occasions of our dignity.
Our house at Hampton Court is not yet suitably arranged. The
tapestries are such that the world can show nothing nobler, yet the
ceilings, however finely fretted, are not yet gilt. The canal is not
perfected, and the Banqueting House in the Paradise is yet bare.”
“The extraordinary wild fowl in St. James’s Park did not fly over
without cost,” observed the Duke.
31. "Some did. The melancholy water-fowl from Astracan was
bestowed by the Russian Ambassador; and certain merchants who
came for justice brought us the cranes and the milk-white raven. But
the animals that it was needful to put in to make the place
answerable to its design,—the antelopes, and the Guinea goats, and
the Arabian sheep, and others,—cost nearly their weight of gold.
Kings cannot make fair bargains."
“For aught but necessaries,” interposed the divine.
"Or for necessaries. Windsor is exceedingly ragged and ruinous. It
will occupy the cost of Dunkirk to restore it——"
“According to the taste of the ladies of the court,” interrupted the
Duke. “They will have the gallery of horns furnished with beams of
the rarest elks and antelopes that there be in the world. Then the
hall and stairs must be bright with furniture of arms, in festoons,
trophy-like: while the chambers have curious and effeminate
pictures, giving a contrast of softness to that which presented only
war and horror.”
“Then there is the demolishing of the palace at Greenwich, in
order to build a new one. Besides the cost of rearing, we are advised
so to make a cut as to let in the Thames like a square bay, which will
be chargeable.”
“And this is to be ordered by Parliament? or are the people to be
told that a foreign possession of theirs is gone to pay for water-fowl
and effeminate pictures?”
“Then there is the army,” continued the King. “I have daily news of
a lack of hospitals, so that our maimed soldiers die of the injuries of
the air. And this very defeat, with which the city will presently be
ringing, was caused by the failure of ammunition. And not
unknowingly; for this young clerk had the audacity to forewarn us.”
“Better have sold the troops and their general alive into the hands
of the enemy, than send them into the field without a sufficiency of
defence,” cried Dr. Reede.
“So his Majesty thinks,” observed the Duke; “and has therefore
done wisely in taking a goodly sum from the Dutch to delay the
sailing of the fleet for the east till the season is too far gone for
action. Nay! is it not a benefit for the King to have the money he so
32. much needs, and for the lives to be saved which must be otherwise
lost for want of the due ammunition?”
Dr. Reede was too much affected at this gross bartering away of
the national honour to trust himself to speak; Edmund observed that
he should insist, in his pamphlet, on the exceeding expensiveness of
war in these days, in comparison of the times when men went out,
each with his bow and arrow, or his battle-axe, and his provision of
food furnished at his own charge. Since gunpowder had been used,
and engines of curious workmanship,—since war had become a
science, it had grown mightily expensive, and the people must pay
accordingly, as he should speedily set forth.
“Setting forth also how the people should therefore be the more
consulted, before a strife is entered upon,” said the clergyman.
“Nay,” said the Duke, “I am for making the matter short and easy.
An expensive army we must have; and a troublesome Parliament to
boot is too much. I am for getting up the army into an honourable
condition, and letting down the Parliament. His Majesty will be
persuaded thereto in time, when he has had another taste of the
discontents of his changeable people.”
Dr. Reede imagined that such an innovation might not be the last
change, if the nation should have more liking to be represented by a
Parliament than ruled by an army. But the Duke did not conceal his
contempt for the new fashion of regarding the people and their
representatives. There was no telling what pass things might come
to when monarchs were reduced to shifts to get money, and the
people fancied that they had a right to sit in judgment on the use
that was made of it. He seemed to forget that he had had a father,
and what had become of him, while he set up as an example worthy
of all imitation the spirited old king, bluff Harry, that put out his hand
and took what he pleased, and amused himself with sending
grumblers to seek adventures north, south, east, or west. If the King
would take his advice, he would show the nation an example of the
first duty of a king,—to protect his people from violence,—in such a
fashion as should leave the Parliament little to say, even if allowed to
meet. Let his Majesty bestow all his paternal care on cherishing his
army.
33. “It is true,” said Dr. Reede, “that a ruler’s first duty is to give
security to his people; and in the lowest state in which men herd
together, the danger is looked for from without; and the people who
at home gather food, each for himself, go out to war, each with his
own weapon. Their ruler does no more than call them out, and point
the way, and lead them home. Afterwards, when men are settled on
lands, and made the property of the rich and strong, they go out to
war at the charge of their lords, and the King has still nothing to do
but to command them. Every man is or may be a warrior; and it is
for those who furnish forth his blood and sinews, his weapons and
his food, to decide about the conduct of the war. But, at a later time,
when men intermingle and divide their labour at will, and the time of
slavery is over, every man is no longer a warrior, but some fight for
hire, while those who hire them stay at their business at home.”
“Or at their pleasures,” observed the Duke, glancing at his brother.
“Under favour, no,” replied Dr. Reede. "It is not, I conceive, the
King that hires the army to do his pleasure, but the people who hire
it for their defence, the King having the conduct of the enterprises.
If the will of the nation be not taken as to their defence,—if they
should perchance think they need no armed defence, and lose their
passion for conquest, whence must come the hire of their servants,
—the soldiery?"
“They must help themselves with it,” replied the Duke, carelessly.
"And if they find a giant at every man’s door,—a lion in the path to
every one’s field?" said the divine.
“Thy learning hath perplexed thee, man. These are not the days
of enchantment, of wild beasts, and overtopping men.”
“Pardon me; there are no days when men may not be
metamorphosed, if the evil influence be but strong enough. There
are no days when a man’s household gods will not make a giant of
him for the defence of their shrine. There are no days when there
are not such roarings in the path of violence as to sink the heart of
the spoiler within him.”
“Let but the art of war improve like other arts,” said the Duke,
“and our cannon will easily out-roar all your lions, and beat down the
giants you speak of.”
34. “Rather the reverse, I conceive,” said the plain-spoken clergyman.
“The expense of improved war is aggravated, not only in the outfit,
but in the destruction occasioned. The soldier is a destructive
labourer, and, as such, will not be overlong tolerated by an
impoverished nation, whose consent to strife is the more necessary
the more chargeable such strife becomes to them. Furthermore,
men even now look upon blood as something more precious than
water, and upon human souls as somewhat of a higher nature than
the fiery bubbles that our newly-wise chemists send up into the
ether, to wander whither no eye can follow them. Our cannon now
knock down a file where before a battle-axe could cleave but a
single skull. Men begin already to tremble over their child’s play of
human life; and if the day comes when some mighty engine shall be
prepared to blow to atoms half an army, there may be found a
multitude of stout hearts to face it; but where is he who will be
brave enough to fire the touch-hole, even for the sure glory of being
God’s arch enemy?”
“Is this brother of thine seeking a patent for some new device of
war-engines?” inquired Charles of the divine. “Methinks your
discourse seems like a preface to such a proposal. Would it were so!
for patents aid the exchequer.”
“Would it were so!” said the Duke, “for a king might follow his own
will with such an engine in his hand.”
“Would it were so!” said Dr. Reede, “for then would the last days
of war be come, and Satan would find much of his occupation gone.
Edmund, if thou wilt invent such an engine as may mow down a
host at a blow, I will promise thee a triumph on that battle-field, and
the intercession of every church in Christendom. Such a deed shall
one day be done. War shall one day be ended; but not by you,
Edmund. Men must enact the wild beast yet a few centuries longer,
to furnish forth a barbarous show to their rulers, till men shall call
instead for a long age of fasting, and sackcloth, and ashes.”
“Meantime,” said Edmund, “they call impertinently for certain
accounts of the charges of our wars which his Majesty is over
gracious in permitting them to demand.”
“Do they think so?”
35. “They cannot but see,” said the Duke, “by the way his Majesty
gave his speech to the Parliament, that he desires no meddling from
them.”
“And how did I speak?” asked the King. “Did I not assure the
Commons that I would not have asked for their subsidies if I had not
had need; and that through no extravagance of my own, but the
disorder of the times? And is not that much to say when I am daily
told by my gentlemen of the palace, and others who know better
still, that my will is above all privilege of Parliament or city, and that
I have no need to account to any at all? How did I speak?”
"Only as if your wits were with your queen, or some other lady,
while the words of your speech lay under your eye. Some words
your Commons must needs remember, from the many times they
were said over; but further——"
“Pshaw!” cried the King, vexed at the description he had himself
asked for. “This learned divine knows not what our Parliament is
made of. There are but two seamen and about twenty merchants,
and the rest have no scruple in coming drunk to the house, and
making a mockery of the country people when they are sober. How
matters it how I give my speech to them?”
“They are indeed not the people,” observed Reede; "and I
forewarn your Majesty that their consent is not the consent of the
people; and that however they may clap the hands at your Majesty’s
enterprises and private sales, the people will not be the less
employed in looking back upon Oliver——"
“And forward to me?” inquired the Duke, laughing.
"And forward to the time when the proud father shall not be liable
to see his only son return barefoot and tattered from a war where he
has spilled his blood; or a daughter made the victim, first of
violence, and then of mockery, through the example of the King’s
court; and no justice to be had but by him who brings the heaviest
bribe:—forward to the time when drunken cavaliers shall be thought
unfitting representatives of a hungering people; and when the
money which is raised by the toils of the nation shall be spent for
the benefit of the nation; when men shall inquire how Rome fell, and
why France is falling; and shall find that decay ensues when that
36. which is a trust is still pertinaciously used as prerogative, and when
the profusion in high places is answerable to the destitution below!"
“Nay; I am sure there is destitution in high places,” cried the King,
“and luxury in the lower. I see not a few ladies outshining my Queen
in gallantry of jewels; and if you like to look in at certain low houses
that I could tell you of, you will see what vast heaps of gold are
squandered in deep and most prodigious gaming.”
“True; and therein is found the excuse of the court; that whenever
the nation is over-given to luxury, the court is prodigious in its
extravagance.”
“Hold, man!” cried the King. “Wouldst thou be pilloried for a libel?”
“Such is too common a sight to draw due regard,” coolly replied
the divine. “Libels are in some sort the primers of the ignorant
multitude, scornfully despised for their ignorance. There are not
means wherewith to give the people letters in an orderly way; so
that they gape after libels first, and then they gape to see them
burned by the hangman; and learn one sort of hardness by flinging
stones at a pilloried wretch, and another sort of hardness by
watching the faces of traitors who pray confidently on the scaffold,
and look cheerfully about them on the hangman’s hellish
instruments; and all this hardness, which may chance to peril your
Majesty, is not always mollified by such soft things as they may
witness at the theatres which profanely give and take from the
licentious times. If the people would become wise, such is the
instruction that awaits them.”
“Methinks you will provoke us to let the people see how cheerfully
you would look on certain things that honest gazers round a scaffold
shrink from beholding. It were better for you to pray for me from
your pulpit, like a true subject of Christ and your King.”
“Hitherto I have done so; but it pleases your Majesty that from my
pulpit I should pray no longer. Alas!” cried he, casting a glance
through the window as he perceived that the vessel drew to land,
“alas! what a raging fire! And another! And a third!”
“The bonfires for the victory,” quietly observed Edmund.
Dr. Reede was forbidden to throw any doubts abroad on the
English having gained a splendid victory. The King had ordered these
37. bonfires at the close of the fast day. They were lighted, it appeared,
somewhat prematurely, as the sun yet glittered along the Thames;
but this only showed the impatient joy of the people. The church
bells were evidently preparing to ring merry peals as soon as the last
hour of humiliation should have expired. The King’s word had gone
forth. It suited his purposes to gain a victory just now; and a victory
he was determined it should be, to the last moment. When the
people should discover the cheat, the favours occasioned by it would
be past recall. They could only do what they had done before,—go
home and be angry.
This was all that now remained for Dr. Reede, the King’s landing
being waited for by a throng of persons whose converse had little
affinity with wise counsel. Certain courtiers, deplorably ennuyés by
the king’s absence, sauntered about the gardens, and looked abroad
upon the river, in hopes of his approach. An importation of French
coxcombs from Dunkirk, in fantastical habits, was already here to
offend the eyes of the insulted English people. It was not till Edmund
(who was not dismissed with Dr. Reede) began to exhibit at home
the confidence with which he had been treated, that Dr. Reede and
his lady became aware how much these accomplished cadets could
teach Charles on the part of their own extravagant master. Louis the
Fourteenth knew of more ways of raising money than even Charles.
He had taken to creating offices for sale, for which the court ladies
amused themselves in making names. The pastime of divining their
object and utility was left to the people who paid for them. They
read, or were told,—and it made a very funny riddle,—that the
inspector of fresh-butter had kissed hands on his appointment; that
the ordainer of faggots had had the honour of dining with his
Majesty; and that some mighty and wealthy personage had been
honoured with the office of licenser of barber-wig-makers.
The example of Louis in this and other matters was too good not
to be followed by one in circumstances of equal necessity. Edmund
was not by any means to delay the “discreet composure” by which
the minds of the people were to be propitiated and satisfied. He was
to laud to the utmost the Duke’s conduct of naval affairs,—(whose
credit rested on the ability of his complaisant Clerk of the Acts.) He
38. was to falsify the navy accounts as much as could be ventured,
exaggerating the expenses and extenuating the receipts, while he
made the very best of the results. He was to take for granted the
willingness of a grateful people to support the dignity of the
sovereign, while he insinuated threats of the establishment of a civil
list,—(a thing at that time unknown.) All this was to be done not the
less for room being required for eloquence about the sale of
Dunkirk, and the loan from France, and the bribe from Holland;—
monuments of kingly wisdom all, and of paternal solicitude to spare
the pockets of the people. All this was to be done not the less for
the bright idea which had occurred to some courtier’s mind that the
making of a few new ambassadors might bring money to his
Majesty’s hands. There was more than one man about the court who
was very willing to accept of the dignity of such an office, and to pay
to the power that appointed him a certain fair proportion of the
salary which the people must provide. One gentleman was
accordingly sent to Spain, to amuse himself in reading Calderon, and
another to some eastern place where he might sit on cushions, and
smoke at the expense of the people of England, and to the private
profit of their monarch. Amidst all these clever arrangements,
nothing was done for the security or the advancement of the
community. No new measures of defence; no better administration
of justice; no advantageous public works, no apparatus of education,
were originated; and, as for the dignity of the sovereign, that was a
matter past hope. But by means of the treacherous sale of the
nation’s property and of public offices, by bribes, by falsification of
the public accounts, breaches of royal credit were for the present
stopped, and the day of reckoning deferred. If the Duke of York
could have foreseen from whom and at what time this reckoning
would be demanded, he might have been less acute in his
suggestions, and less bold in his advice; and both he and the King
might have employed to less infamous purpose this day of solemn
fast and deprecation of God’s judgments. But, however true might
be Dr. Reede’s doctrine that the sins of government are the sins of
the nation, it happened in this case, as in a multitude of others, that
39. the accessaries to the crime offered the atonement, while the
principals made sport of both crime and atonement.
The false report about the late engagement had gained ground
sufficiently to answer the temporary purposes of those who spread
it. As Dr. Reede took his way homewards, bonfires gleamed reflected
in the waters of the river, and exhibited to advantage the
picturesque fronts of the wooden houses in the narrow streets, and
sent trains of sparks up into the darkening sky, and illuminated the
steeples that in a few more seasons were to fall into the surging
mass of a more awful conflagration. On reaching the comfortable
dwelling which he expected to be soon compelled to quit, he gave
himself up, first to humiliation on account of the guilt against which
he had in vain remonstrated, and then to addressing to the King a
strong written appeal on behalf of the conscientious presbyterian
clergy, who had, on the faith of the royal word, believed themselves
safe from such temptations to violate their consciences as they were
now suffering under.
On a certain Saturday of the same month might be seen the most
magnificent triumph that ever floated on the Thames. It far
exceeded the Venetian pageantry on occasion of espousing the
Adriatic. The city of London was entertaining the King and Queen;
and the King was not at all sorry that the people were at the same
time entertained, while he was making up his mind whether, on
dissolving the Parliament, he should call another which would
obligingly give him the dean and chapter lands, or whether he
should let it be seen, according to the opinion of his brother, that
there was no need of any more parliaments. As he sat beside his
Queen, in an antique-shaped vessel, under a canopy of cloth of gold,
supported by Corinthian pillars, wreathed with flowers, festoons, and
garlands, he meditated on the comfort that would accrue, on the
one hand, from all his debts being paid out of these church lands,
and, on the other, from such an entire freedom from responsibility as
he should enjoy when there should be no more speeches to make to
his Commons, and no more remonstrances to hear from them,
grounded on dismal tales of the distresses of his people which he
had rather not hear. The thrones and triumphal arches might do for
40. the corporation of London to amuse itself with, and for the little boys
and girls on either side of the river to stare at and admire: but it was
in somewhat too infantine a taste to please the majority of the
gazers otherwise than as a revival of antique amusements. The most
idly luxurious about the court preferred entertainments which had a
little more meaning in them,—dramatic spectacles, pictures, music,
and fine buildings and gardens. War is also a favourite excitement in
the middle age of refinement; and the best part of this day’s
entertainments, next to the music, was the peals of ordnance both
from the vessels and the shore, which might prettily remind the
gallants, amidst their mirth and their soft flirtations, of the
cannonading that was going on over the sea. Within a small section
of the city of London, many degrees of mirth might be found this
day.
In the royal barge, the Queen cast her “languishing and excellent
eyes” over the pageant before her, and returned the salutations of
the citizens who made obeisances in passing, and now and then
exchanged a few words with her Portuguese maids of honour, the
King being too thoughtful to attend to her;—altogether not very
merry.
In the barge immediately following, certain of the King’s favourites
made sport of the Queen’s foretop,—turned aside very strangely,—of
the monstrous fardingales and olivada complexions and unagreeable
voices of her Portuguese ladies,—and of the old knight, her friend,
whose bald pate was covered by a huge lock of hair, bound on by a
thread, very oddly. The King’s gravity also made a good joke; and
there was an amusing incident of a boat being upset, which
furnished laughter for a full half hour. A family of Presbyterians,
turned out of a living because the King had broken his word, were
removing their chattels to some poor place on the other side of the
river, and had unawares got their boat entangled in the procession,
and were run down by a royal barge. It was truly laughable to see
first the divine, and then his pretty daughters, with their dripping
long hair, picked up from the water, while all their little wealth went
to the bottom: and yet more so to witness how, when the King, of
his bounty, threw gold to the sufferers, the clergyman tossed it back
41. so vehemently that it would have struck the Duke of York on the
temple, if he had not dexterously contrived to receive it on the
crown of his periwig. It was a charming adventure to the King’s
favourites;—very merry.
In the mansions by the river side, certain gentlemen from the
country were settling themselves, in preparation for taking office
under the government. They and their fathers had been out of
habits of business for fourscore years, and were wholly incapable of
it, and knew themselves to be so; the best having given themselves
to rural employments, and others to debauchery; but, as all men
were now declared incapable of employment who had served
against the King, and as these cavaliers knew that their chief
business was to humour his Majesty, they made themselves easy
about their responsibilities, looked after their tapestries, plate, and
pictures, talked of the toils and cares of office, and were—very
merry.
In the narrow streets in their neighbourhood might be hourly seen
certain of the King’s soldiers, belted and armed, cursing, swearing,
and stealing; running into public-houses to drink, and into private
ones to carry off whatever they had a mind to; leaving the injured
proprietors disposed to reflect upon Oliver, and to commend him,—
what brave things he did, and how safe a place a man’s own house
was in his time, and how he made the neighbour princes fear him;
while now, a prince that came in with all the love, and prayers, and
good-liking of his people, who had given greater signs of loyalty and
willingness to serve him with their estates than ever was done by
any people, could get nothing but contempt abroad, and discontent
at home; and had indeed lost all so soon, that it was a miracle how
any one could devise to lose so much in so little time. These
housekeepers, made sage by circumstance, looked and spoke with
something very little like mirth. Those who had given occasion to
such thoughts were, meantime,—very merry.
It was not to these merry men, wise people thought, that the King
must look for help in the day of war, but to the soldiers of the
republican army, who had been declared by act of parliament for
evermore incapable of serving the kingdom. But where were these
42. men to be found, if wanted? Not one could be met with begging in
the streets to tell how his comrades might be reached. One captain
in the old parliament army was turned shoemaker, and another a
baker. This lieutenant was now a haberdasher; that a brewer. Of the
common soldiers, some were porters, and others mechanics in their
aprons, and husbandmen in their frocks, and all as quiet and
laborious as if war had never been their occupation. The spirits of
these men had been trained in contentment with God’s providences;
and though, as they sat at the loom and the last, they had many
discontented thoughts of man’s providences, it was clear to
observers among the King’s own servants that he was a thousand
times safer from any evil meant by them than from his own
unsatisfied and insatiable cavaliers. While the staid artizans who had
served under Cromwell looked out upon the river as the procession
passed, they dropped a few words in their families about the snares
of the Evil One, and were—not very merry.
Within hearing of the ordnance in which the young gallants of the
court delighted was an hospital, meagrely supplied with the comforts
which its inmates required, where languished, in a crowded space,
many of the soldiers and sailors who had been set up to be fired at
while it was known in high quarters that there was such a deficiency
of ammunition as must deprive the poor fellows of the power of
effectual self-defence. This fact had become known, and it had sunk
deep into the souls of the brave fellows who, maimed, feverish, and
heart-sore,—in pain for want of the proper means of cure, and half
suffocated from the number of their fellow-sufferers, listened with
many a low-breathed curse to the peals of ordnance that shook their
crazy place of refuge, and forswore mirth and allegiance together.
Within hearing of the shouts and of a faint occasional breath of
music from the royal band, were certain of the two thousand clergy,
who were to resign their livings the next morning, and whose
families were taking advantage of the neighbourhood being deserted
for the day to remove their furniture, and betake themselves to
whatever place they might have found wherein the righteous could
lay his head. Dr. Reede was one of these. He had been toiling all day
with his wife, demolishing the tout ensemble of comfort which had
43. been formed under her management. He was now, while she was
engaged with her infants, sitting alone in his study for the last time.
He was doing nothing; for his business in this place was closed. He
let his eye be amused by the quick flickering in the breeze of the
short, shining grass of his little court, which stretched up to his
window. The dark formal shrubs, planted within the paling by his
own hand, seemed to nod to him as the wind passed over their
heads. The summer flowers in the lozenge-shaped parterres which
answered to each other, danced and kissed unblamed beneath the
Rev. Doctor’s gaze. All looked as if Nature’s heart were merry,
however sad might be those of her thoughtful children. The Doctor
stepped out upon the grass. There was yet more for him to do there.
He had, with his own hands, mowed the plat, and clipped the
borders; and the little hands of the elder of his two children had
helped to pluck out the very few weeds that had sprung up. But the
weather had been warm and dry, and, in order to leave the place in
the beauty desired by its departing tenant, it was necessary to water
the flower-court. It was not a very inspiriting thing to glance at
doors and windows standing wide, displaying the nakedness of an
empty dwelling within: so the Doctor hastened to the well to fill his
bucket. Mrs. Reede heard the jingle of the chain, and showed herself
at an upper window, while the child that could walk made her way
down stairs with all speed to help papa, and wonder at her own
round little face in the full bucket. Mrs. Reede was glad that her
husband had turned out of his study, though she could not bring
herself to sympathize in his anxiety to leave all in a state of the
greatest practicable beauty. If a gale had torn up the shrubs, or the
hot sun of this summer day had parched the grass and withered the
flowers, she did not think she could have been sorry. But it was very
well that her husband had left his study open for the further
operations necessary there. This room had remained the very last in
its entireness. The time was now come when she must have asked
her husband to quit his chair and desk, and let his books be
dislodged. She would make haste to complete the work of spoliation,
and she hoped he would make a long task of watering the flower-
court.
44. He was not likely to do that when he had once perceived that she
and one of her damsels were lifting heavy loads of books, while
another was taking care of the baby. He hastened to give their final
draught to his favourite carnations, placed a chair for Esther on the
grass just outside the window, where she might sit with the infant,
and, while resting herself, talk to him as he finished her laborious
task.
Mrs. Reede did not remember to have ever started so incessantly
at the sound of guns; and the air-music of the window-harp that she
had seen in the pavilions of great men’s gardens had never come so
mournfully over her spirit as the snatches of harmony that the wind
now brought from the river to make her infant hold up his tiny finger
while his sister said “hark!” She was, for once, nervous. It might be
seen in her flushed face and her startled movements; and the poor
baby felt it in the absence of the usual ease with which he was held
and played with. A sharp sudden cry from him called the attention of
the doctor from his task. In a moment, mamma’s grief was more
tumultuous than the infant’s.
“O, my child! my child! I have hurt my child! my own little baby!”
cried she, weeping bitterly, and of course redoubling the panic of the
little one.
“My dear love,” said her husband, trying to prove to her that the
baby had only been frightened by a jerk; “my dear love, you alarm
yourself much more than the child. See!” and he held up in the
evening sunlight the brass plate on which his study lamp stood. Its
glittering at once arrested the infant’s terrors: but not so soon could
the tears of the mother be stopped.
“My love, there must be some deeper cause than this trifling
accident,” said he, sitting down on the low window sill beside her
chair. “Is it that you have pent up your grief all day, and that it will
have way?”
Mrs. Reede had a long train of sad thoughts to disclose, in the
intervals of her efforts to compose herself. The children, she said,
amused themselves as if nothing was the matter; while who could
tell what they might think hereafter of being thus removed from a
fair and honourable home, and carried where—O, there was no
45. telling what lot might await them! If everybody had thought the
sacrifice a right one, she could have gone through it without any
regret: but some of her husband’s oldest friends thought him wrong
——
“Towards God, or towards you, my love?”
"O, towards these children, I suppose. They dare not think that
you would do anything wrong towards me. I am sure I only think of
you first, and then of the children. How you have preached here,
with the souls of your people in your hand, to mould them as you
would! and now, you must go where your gift and your office will be
nothing; and you will be only like any other man. And, as for the
children, we do not know——"
“When the bird leads forth her brood from their warm nest,
because springes are set round about them, does she know what
shall befall them? There may be hawks abroad, or a sharp wind that
may be too strong for their scarce-plumed wings. Or they may
gather boldness from their early flight, and wave in the sunshine on
a high bough, and pour out there a grateful morn and even song
from season to season. The parent bird knows not: but she must
needs take them from among the springes, however soft may be the
nest, and cool the mossy tree. We know more than this parent bird;
even that no sparrow falleth unheeded to the ground.”
Mrs. Reede’s tears began to flow again as another faint breath of
music reached her.
“Is it that you will be more composed when the sounds of mirth,
to us unseasonable, have passed away?” asked Dr. Reede, smiling.
“It does seem hard that our spoilers should be making merry while
we are going forth we know not whither,” said the wife.
“How would it advantage the mother bird that the fowlers should
lie close while she plumes her pinions to be gone? Will she stoop in
her flight for all their mirth? As for us, music may be to us a rare
treat henceforth. Let our ears be pleased with it, whencesoever it
may come.”
And he made the children hearken, till they clapped their little
hands, and their mother once more smiled. Her husband then said
to her,
46. “If this mirth be ungodly, there is no reason why we should be
more scandalized at it than on any other day, only because we
ourselves are not merry. If it be innocent, we should thank God that
others are happier than ourselves. Yet I am not otherwise than
happy in the inward spirit. I shall never repent this day.”
"They say you will, when——But it is not as if we stood alone. It is
said that there will be a large number of the separated."
“Thank God! not for the companionship to ourselves, so much as
for the profit to his righteousness. It will be much to meet here and
there eyes that tell back one’s own story, and to clasp hands that are
undefiled by the world’s lucre. But it is more to know that God’s
truth is so hymned by some thousand tongues this night, that the
echo shall last till weak voices like ours shall be wanted no more.”
“Let us go,” cried Mrs. Reede, dispersing her last tears, and lifting
up one child while the other remained in her husband’s arms. He
took advantage of her season of strength, and resolved to convey
her at once to the humble lodging which was to be their present
abode, and to return himself to see that all was done. He detained
her only to join him in a brief thanksgiving for the happiness they
had enjoyed there since their marriage day, and to beseech a
blessing on him who was to succeed to the dwelling and to the
pastoral office. Courageous as was Mrs. Reede’s present mood, she
was still at the mercy of trifles. The little girl’s kitten would not bear
them company. It had been removed twice, and had returned, and
now was not to be found. It had hidden itself in some corner
whence it would come out when they were gone; and the child
departed in a very unchristian state of distress. Her mamma found
that both she and her child had yet to learn Dr. Reede’s method of
not fretting because of evil-doers.
Though he could not trouble himself with personal resentments,
no man could more strenuously rebuke and expose guilt,—especially
guilt in high places, which is so much worse than other guilt, in as
far as it desolates a wider region of human happiness. In his farewell
discourse, the next day, he urged some considerations on behalf of
society far more eagerly than he ever asked anything for himself.
47. “It is no new thing,” said he, "for men to be required to set their
hand to that which they believe not, or to affirm that they believe
that which they understand no more in the expression than in the
essence. It is no new thing for a mistake to be made as to such
protestation, so that if a man say he believes that a sown field will
bear corn, though he knows not the manner of its sprouting nor the
order of its ripening, he shall be also required to believe a
proposition in an unknown tongue, whereof he knows not even what
it is that should be proposed. It is no new thing that men should
start at such a requisition, as a sound-witted man would start from
the shows and babble of the magician; or as a modest wise man
would shrink from appointing the way to a wandering comet, lest he
should unawares bring the orderly heavens to a mighty wreck. It is
no new thing for the searchers of God’s ways to respect his
everlasting laws more than man’s presumptuous bidding: or for Him
whom they serve so to change the face of things to them as to make
his extremest yoke easy, and his heaviest burden light:—to cast a
shade over what must be foregone,—whether it be life itself, or only
the goodly things in which maybe too much of our life hath been
found,—or to beam a light from his own highest heaven on the
wilderness-path, which may seem horrid to those who are not to
tread it, but passable enough to such as must needs take this way to
their everlasting home. These things being not new, are a sign to us
recusants of this day not to be in anywise astonished or dismayed,
and also not to allow a dwelling upon the part we have taken, as if it
were any mighty merit to trust to God’s providence, which waits only
to be trusted, or required any marvellous faith to commit ourselves
to Christ’s word, which, if it be Christ’s, must stand when the
heavens themselves shall be dissolved. It behoves us rather to look
to things less clear than these, and more important than the putting
forth of a few of Christ’s meanest shepherds from their folds;—for
whom the chief Shepherd may perhaps find other occasions; and, if
not, they may be well content to lie down among the sheep,
remembering that he once had not where to lay his head. The true
occasion of this day is not to break one another’s hearts with griefs
and tears, (which may but puff out or quench the acceptable fire of
48. the altar;) but so to fan the new-kindled flame as that it may seize
and consume whatsoever of foul and desecrating shows most
hideous in its light. Is it not plain that powers whose use is ushered
in with prayers, and alternated with the response of God’s most holy
name,—the powers of government,—are used to ensnare those who
open their doors to whatsoever cometh in that name? It is well that
governments should be thus sanctified to the ears and eyes of the
governed; for, if there be a commission more certainly given straight
from the hand of God than another it is that of a ruler of men. Who
but he opens the eyes of the blind, and unstops the ears of the deaf,
and sets the lame on his feet, and strengthens together the
drooping heart and the feeble knees,—by setting before the one the
radiant frame of society in all its fitness, and waking up for another
the voices of human companionship, and compacting the powers of
the weak with those of the strong, and cheering all by warding off
injury from without, and making restraint easy where perchance it
may gall any of those who are within? Sacred is the power of the
ruler as a trust; but if it be used as a property, where is its sanctity?
If the steward puts out the eyes that follow him too closely, and ties
the tongue that importunes, and breaks the limbs of the strong man
in sport, so as to leave him an impotent beggar in the porch of the
mansion,—do we not know from the Scripture what shall be the fate
of that steward? As it is with a single ruler, so shall it be with a
company of rulers,—with a government which regards the people
only as the something on which itself must stand, which takes bread
from the children to give it to dogs; which sells God’s gifts to them
that are without, at the risk of such utter blindness that they shall
weary themselves to find the door out of their perplexities and
terrors. What governments there be that commit the double sin of
lording it over consciences, (which are God’s heritage,) and of ruling
for their own low pleasures instead of the right living and moving of
the people, judge ye. If there be any which mismanage its defence,
and deny or pervert justice, and refuse public works, and make the
church a scandal, and the court a spectacle for angels to weep over
and devils to resort to, and, instead of speeding the people’s
freedom with the wings of knowledge, shut them into the little cells
49. of ancient men’s wits, it is time that such should know why God hath
made them stewards, and should be alarmed for the coming of their
Master. It is not for the men and maid-servants to wrest his staff
from his hands, or to refuse his reasonable bidding, or to forsake,
the one his plough, and the other his mill, and the maidens to
spread the table: but it is for any one to give loud warning that the
Master of the house will surely demand an account of the welfare of
his servants. Such a warning do I give; and such is the warning
spoken by the many mourners of this day, who, because they
honour the kingly office as the holiest place of the fair temple of
society, and kingly agents as the appointed priesthood, can the less
bear to see the nation outraged as if there were no avenging angel
of Jehovah flying abroad; and comfortless in their miseries, as if
Jehovah himself were not in the midst of them."
It was well that Dr. Reede felt that he could bear the pillory. He
was pilloried.
50. THIRD AGE.
History is silent as to the methods by which men were enabled to
endure the tedium of journeys by the heavy coaches of the olden
time. The absence of all notion of travelling faster might, indeed, be
no inconsiderable aid,—an aid of which travellers are at present, for
the most part, deprived; since the mail-coach passenger, the envy of
the poor tenant of the carrier’s cart, feels envy, in his turn, of the
privileged beings who shoot along the northern rail-road; while they,
perhaps, are sighing for the time when they shall be able to
breakfast at one extremity of the kingdom, and dine at the other.
When once the idea of not going fast enough enters a traveller’s
mind, ennui is pretty sure to follow; and it may be to this
circumstance that the patience of our forefathers, under their long
incarceration on the road, was owing—if patience they had. Now, a
traveller who is too much used to journeying to be amused, as a
child is, by the mere process of travelling, is dismayed alike if there
be a full number of passengers, and if there be none but himself. In
the first case, there is danger of delay from the variety of deposits of
persons and goods; and in the second, there is an equal danger of
delay from the coachman having all his own way, and the certainty,
besides, of the absence of all opportunity of shaking off the dulness
of his own society.
Mr. Reid, a sociable young barrister, who had never found himself
at a loss on a journey, was left desolate one day last summer when
he least expected it. He had taken his wife and child down to the
south, in order to establish them by the sea-side for a few weeks;
and he was now travelling up to town by the stage-coach, in very
amusing company, as he thought, for the first stage, but presently in
solitude. Supposing that his companions were going all the way, he
51. took his time about making the most of them, and lost the
opportunity. There was a sensible farmer, who pointed right and left
to the sheep on the downs—green downs—retiring in long sweeps
from the road; and he had much to relate of the methods of
cultivation which had been pursued here, there, and everywhere,—
with the Barn Field, and Rick Mead, and Pond-side Field, and Brook
Hollow, and many other pretty places that he indicated. He had also
stores of information on the farmer’s favourite subject of complaint—
the state of the poor. He could give the history of all the well-meant
attempts of my lord this, and my lady that, and colonel the other, to
make employment, and institute prizes of almshouses, and induce
their neighbours to lay out more on patches of land than less
helpless folks would think it worth while to bestow. Meantime, a
smart young lady in the opposite corner was telling her widowed
chaperon why she could not abide the country, and would not be
tempted to leave dear London any more,—namely, that the country
was chalky, and whitened the hems of all her petticoats. The widow,
in return, assured the unbelieving girl that the country was not
chalky all over the world, and that she had actually seen, with her
own eyes, the junction of a white, a red, and a black road,—very
convenient, as one might choose one’s walk by the colour of one’s
gown. The widow at the same time let fall her wish to have the
charge—merely for the sake of pleasant occupation—of the
household of a widower, to whose daughters she could teach
everything desirable; especially if they were intended to look after
dairy and poultry-yard, and such things.
“Thank’ee, ma’am,” said the farmer, as she looked full at him; “my
daughters are some of them grown up; and they have got on
without much teaching since their mother died.”
Mr. Reid promised himself to gain more information about the
widow’s estimate of her own capabilities; but she and her charge
were not yet going to “dear London.” They got out at the first
country town, just after the farmer had thrust himself half out of the
window to stop the coach, flung himself on the stout horse that was
waiting for him at the entrance of a green lane, and trotted off, with
a prodigious exertion of knee, elbow, and coat-flap.
52. Mr. Reid had soon done thinking of the widow, and of the damsel
who had displayed so intimate a knowledge of rural life. Pauperism
lasted longer; but this was only another version of a dismal story
with which he was already too well acquainted. He was glad to think
of something else. He found that he got most sun by riding
backward, and most wind by riding forward, and made his election
in favour of the latter. He discovered, after a momentary doubt, that
his umbrella was safe, and that there was no occasion to trouble his
knees any longer with his great-coat. He perceived that the coach
had been new-lined, and he thought the lace suited the lining
uncommonly well. He wondered whether the people would be as
confoundedly long in changing horses at every stage as they had
been at the first. It would be very provoking to arrive in town too
late for dinner at G——’s. Ah! the women by the road-side found it a
fine day for drying the linen they had washed. How it blew about,
flapping, with a noise like mill-sails; big-sleeved pinafores and
dancing stockings! This was a pretty country to live in: the
gentlemen’s houses were sufficiently sheltered, and the cottages had
neat orchards behind them; and one would think pains had been
taken with the green lanes—just in the medium as they were
between rankness and bareness. What an advantage roads among
little hills have in the clear stream under the hedge,—a stream like
this, dimpling and oozing, now over pebbles, and now among
weeds! That hedge would make a delicious foreground for a picture,
—the earth being washed away from the twisted roots, and they
covered with brown moss, with still a cowslip here and there
nodding to itself in the water as the wind passed by. By the way,
that bit of foreground might be kept in mind for his next paper for
the “New Monthly.” It would be easy to give his subject a turn that
would allow that hedge and its cowslip to be brought in. What had
not Victor Hugo made of a yellow flower, in a scene to which nobody
who had read it would need a second reference! But this well, to the
left, was even better than the hedge: it must have been described
already; for it looked as if put there for the purpose. What a damp
nook in the hedge it stood in, with three old yews above it, and tufts
of long grass to fringe the place! What a well-used chain and ladle,
53. and what merry, mischievous children, pushing one another into the
muddy pool where the drippings fell, and splashing each other,
under pretence of drinking! He was afraid of losing the impression of
this place, so much dusty road as he had to pass through, and so
many new objects to meet before he could sit down to write; unless,
indeed, he did it now. Why should not he write his paper now? It
was a good idea—a capital thought!
Three backs of letters and a pencil were presently found, and a
flat parcel in one of the window-pockets, which served as a desk,
when the feet were properly planted on the opposite seat. The lines
were none of the straightest, at first; and the dots and stops
wandered far out of their right places; while the long words looked
somewhat hieroglyphical. But the coach stopped; and Mr. Reid forgot
to observe how much longer it took than before to change horses
while he was the only passenger. He looked up only once, and then
saw so charming an old granny, with her little Tommy, carrying a
toad-in-a-hole to the baker’s, that he was rewarded for his
momentary idleness, and resolved to find a place for them too, near
the well and the mossy hedge.
He was now as sorry to be off again as before to stop. The horses
were spirited, and the road was rough. His pencil slipped and jerked,
this way and that. Presently his eyes ached: his ideas were jostled
away. It was impossible to compose while the manual act was so
troublesome; it was nonsense to attempt it. Nothing but idleness
would do in travelling; so the blunted pencil was put by, and the eye
was refreshed once more with green.
But now a new sort of country was opening. The hedges were
gone, and a prodigious stretch of fallow on either hand looked
breezy and pleasant enough at first; and the lark sprang from the
furrow so blithely, that Reid longed to stop the coach, that he might
hear its trilling. But the lark could not be heard, and was soon out of
sight; and the perspective of furrows became as wearying as making
pothooks had been. Reid betook himself to examining the window-
pockets. There were two or three tidy parcels for solicitors, of
course; and a little one, probably for a maid-servant, as there were
seven lines of direction upon it. The scent of strawberries came from
54. a little basket, coolly lined with leaves, and addressed to Master
Jones, at a school in a town to be presently passed through. Reid
hoped, for the boy’s sake, that there was a letter too; and he found
an interstice, through which he could slip half-a-dozen burnt
almonds, which had remained in his pocket after treating his own
child. What speculations there would be, next holiday time, about
how the almonds got in! Two or three other little parcels were
disregarded; for among them lay one of more importance to Reid
than all the rest,—three newspapers, tied round once with a bit of
red tape, and directed, in pencil, to be left at the Blue Lion till called
for. Reid took the liberty of untying the tape, and amusing himself
with the precious pieces of type that had fallen in his way. There was
little political intelligence in these papers, and that was of old date;
but a little goes a great way with a solitary traveller; and when the
better parts of a newspaper are disposed of, enough remains in the
drier parts to employ the intellect that courts suggestion. That which
is the case with all objects on which the attention is occupied, is
eminently the case with a newspaper—that whatever the mind
happens to be full of there receives addition, and that the mood in
which it is approached there meets with confirmation. Reid had
heard much from the farmer of the hardships which individuals
suffer from a wasteful public expenditure; and his eye seemed to
catch something which related to this matter, to whatever corner of
the papers it wandered.
"Strike at ****** Palace.—All the workmen at present employed
on this extensive structure ceased work on the appearance of the
contractor yesterday morning. Their demand for higher wages being
decidedly refused by him, the men quitted the spot, and the works
have since remained deserted. A considerable crowd gathered
round, and appeared disposed to take part with the workmen, who,
it is said, have for some time past been arranging a combination to
secure a rise of wages. The contractor declares his intention to
concede no part of the demand."
The crowd taking part with the workmen! Then the crowd knows
less than the workmen what it is about. These wages are paid by
that very crowd; and it is because they issue from the public purse
55. that the workmen think they may demand higher wages than they
would from a nobleman or private gentleman. The contractor is but
a medium, as they see, between the tax-payers and themselves; and
the terms of the contract must depend much on the rate of wages of
those employed. I hope the contractor will indeed concede nothing;
for it is the people that must overpay eventually; and it has been too
long taken for granted that the public must pay higher for everything
than individuals. I should not wonder if these men have got it into
their heads, like an acquaintance of mine in the same line, that, as
they are taxed for these public buildings, they have a right to get as
much of their money back as they can, forgetting that if every taxed
person did the same, there would be no palace built;—not but that
we could spare two or three extremely well;—or might, at least,
postpone some of the interminable alterations and embellishments,
with an account of which the nation is treated, year after year, in
return for its complaisance in furnishing the cash. Let their Majesties
be nobly lodged, by all means; and, moreover, gratified in the
exercise of tastes which are a thousand times more dignified than
those of our kings in the days of cloth of gold, and more refined
than those of monarchs who could make themselves exceedingly
merry at the expense of their people. The test, after all, is—What is
necessary for the support of the administrating body, and what
upholds mere pomp? These are no days for public pomp. In one
sense, the time for it is gone by; in another sense, it is not come;—
that is, we ought now to be men enough to put away such childish
things; and, we cannot yet afford them. Two or three noble royal
palaces, let alone when once completed, are, in my mind, a proper
support to the dignity of the sovereign. As for half-a-dozen, if they
do not make up a display of disgraceful pomp, the barbaric princes
of the East are greater philosophers than I take them for. Yes, yes;
let the sovereign be nobly lodged; but let it be remembered that
noble lodgings are quite as much wanted for other parties.
"Mr. ——’s motion was lost without a division."
Aye: just so. The concentrated essence of the people, as the
House of Commons pretends to be, must put up with a sordid
lodging, however many royal palaces England may boast. They are
56. not anything so precious as they pretend to be, or they would not so
meanly exclude themselves from their right. They might just as
faithfully consult the dignity of the empire by making the King and
Queen live in a cottage of three rooms, as by squeezing themselves
into a house where there is neither proper accommodation for their
sittings, nor for the transaction of their business in Committees, nor
for witnessing, nor for reporting their proceedings. I thought my wife
quite right in saying that she would never again undergo the insult
of being referred to the ventilators; and I have determined twenty
times myself that I would despise the gallery so utterly that I would
never set foot in it again: yet to the gallery I still go; and I should
not wonder if my wife puts away, for once or twice, her disgust at
inhaling smoke and steam, and her indignation at being permitted to
watch the course of legislation only through a pigeon-hole and a
grating. The presence of women there, in spite of such insults, is a
proof that they are worthy of being treated less like nuns and more
like rational beings; and the greater the rush and consequent
confusion in the gallery, the more certain is it that there are people
who want, and who eventually will have the means of witnessing the
proceedings of their legislators. But all this is nothing to the
importance of better accommodation to the members. Of all
extraordinary occasions of being economical, that is the most
strange which impairs the exertions of the grand deliberative
assembly of the nation,—the most majestic body, if it understood its
own majesty,—within the bounds of the empire. Why,—every
nobleman should be content with one house, and every private
gentleman be ashamed of his stables and kennels, rather than that
the House of Commons should not have a perfect place of
assemblage. I verily believe that many a poor man would willingly
give his every third potato towards thus aiding the true
representation of his interests. It would be good economy in him so
to do, if there was nothing of less consequence to be sacrificed first.
But King, Lords, and Commons are not the only personages who
have a claim on the public to be well housed, for purposes of social
support, not pomp.
57. 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!
ebookfinal.com