0% found this document useful (0 votes)
16 views67 pages

23538

Uploaded by

cossuayolah8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views67 pages

23538

Uploaded by

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

Download the full version of the ebook at

https://ebookfinal.com

Scala Design Patterns 1st Edition Nikolov

https://ebookfinal.com/download/scala-design-
patterns-1st-edition-nikolov/

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


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

Elemental Design Patterns 1st Edition Jason Mcc. Smith

https://ebookfinal.com/download/elemental-design-patterns-1st-edition-
jason-mcc-smith/

ebookfinal.com

Head First Design Patterns 1st Edition Eric Freeman

https://ebookfinal.com/download/head-first-design-patterns-1st-
edition-eric-freeman/

ebookfinal.com

Pro JavaScript Design Patterns 1st Edition Ross Harmes

https://ebookfinal.com/download/pro-javascript-design-patterns-1st-
edition-ross-harmes/

ebookfinal.com

Java Design Patterns 1st Edition Mr. Devendra Singh

https://ebookfinal.com/download/java-design-patterns-1st-edition-mr-
devendra-singh/

ebookfinal.com
C 3 0 Design Patterns 1st Edition Judith Bishop

https://ebookfinal.com/download/c-3-0-design-patterns-1st-edition-
judith-bishop/

ebookfinal.com

Advanced ActionScript 3 2nd Edition Design Patterns Ben


Smith

https://ebookfinal.com/download/advanced-actionscript-3-2nd-edition-
design-patterns-ben-smith/

ebookfinal.com

Progressive Engineering Practices in Marine Resource


Management 1st Edition Nikolov

https://ebookfinal.com/download/progressive-engineering-practices-in-
marine-resource-management-1st-edition-nikolov/

ebookfinal.com

Programming in Scala 1st Edition Martin Odersky

https://ebookfinal.com/download/programming-in-scala-1st-edition-
martin-odersky/

ebookfinal.com

Scala in Action Nilanjan Raychaudhuri

https://ebookfinal.com/download/scala-in-action-nilanjan-raychaudhuri/

ebookfinal.com
Scala Design Patterns 1st Edition Nikolov Digital Instant
Download
Author(s): Nikolov, Ivan
ISBN(s): 9781785882500, 1785882503
Edition: 1
File Details: PDF, 4.35 MB
Year: 2016
Language: english
Scala Design Patterns

Write efficient, clean, and reusable code with Scala

Ivan Nikolov

BIRMINGHAM - MUMBAI
Scala Design Patterns

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2016

Production reference: 1230216

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78588-250-0
www.packtpub.com

Cover image by Ivan Nikolov ([email protected])


Credits

Author Project Coordinator


Ivan Nikolov Shweta H Birwatkar

Reviewer Proofreader
Bruno Filippone Safis Editing

Commissioning Editor Indexer


Amarabha Banerjee Tejal Daruwale Soni

Acquisition Editor Graphics


Kirk D'costa Jason Monteiro

Content Development Editor Production Coordinator


Preeti Singh Melwyn Dsa

Technical Editor Cover Work


Vivek Arora Melwyn Dsa

Copy Editor
Kausambhi Majumdar
About the Author

Ivan Nikolov is a software engineer living and working in London. After he


graduated with an award of distinction from the University of Edinburgh in 2012,
he moved to London and started working for a company in the ad tech industry.
During his studies, Ivan developed an interest in technologies that help in dealing
with a large amount of data. His professional career has given him the chance to
work with cutting edge big data technologies on a daily basis. Some of the interesting
projects that Ivan has worked on include a large scale real-time predictive analytics
engine and batch processing solutions. He has used Scala in all of these projects
in combination with technologies and libraries such as Spark, Hadoop, Scalding,
Cassandra, Kafka, and so on, as well as other JVM languages such as Java.

Ivan's approach to software engineering is very personal, and he takes pride in


the projects he works on. He is extremely meticulous about writing efficient and
beautiful code.

Apart from programming and learning about new languages and technologies, in his
free time, Ivan likes to participate in sports activities, travel, meet people, and explore
new places and cultures. He also likes photography, especially nature and wildlife.

In his spare time, Ivan tries to keep himself busy with personal projects and learning
about new technologies. He also runs a small programming blog where he writes
articles about important programming concepts. Ivan believes that knowledge
sharing is an essential part of keeping the software and more specifically, the open
source community running. Sharing ideas leads to greater innovation and raises the
quality of products to a higher level.
Acknowledgments
I would like to thank my family and friends for all the support they have given
me with the book, for putting up with my late night sessions and all nighters,
bearing my absence, and for giving me invaluable advice. I would like to thank my
grandfather, Felix, for his advice and constant interest in this book and the projects
I've been working on.

Special thanks to all my tutors from my university years for showing me the way to
a professional career I love and for guiding me in choosing a path that would lead
me to where I am now. From the open source community, I am thankful to everyone
who has inspired me with their extreme intelligence, amazing ideas, and dedication.
Last but not least, I've had the great pleasure to work with many smart people who
taught me many things and have helped me learn so much.

Finally, I would like to thank the technical reviewer for his valuable feedback and
pointers. Thanks to everyone at Packt Publishing for their hard work—without you
this book wouldn't be possible.
About the Reviewer

Bruno Filippone is a polyglot software engineer based in London, with more


than 8 years of experience in building a variety of software solutions using different
technology stacks.

He spent part of his career working on JavaScript, PHP, .NET, Java, and Python
projects while focusing more on the Typesafe stack in the recent years, accumulating
more than 3 years of experience embracing functional programming and working
with Scala and Akka building scalable software architectures.
www.PacktPub.com
Support files, eBooks, discount offers,
and more
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and
as a print book customer, you are entitled to a discount on the eBook copy. Get in touch
with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface xi
Chapter 1: The Design Patterns Out There and Setting Up
Your Environment 1
Design patterns 2
Scala and design patterns 2
The need for design patterns and their benefits 3
Design pattern categories 3
Creational design patterns 4
The abstract factory design pattern 5
The factory method design pattern 5
The lazy initialization design pattern 5
The singleton design pattern 5
The object pool design pattern 6
The builder design pattern 6
The prototype design pattern 6
Structural design patterns 6
The adapter design pattern 7
The decorator design pattern 7
The bridge design pattern 7
The composite design pattern 8
The facade design pattern 8
The flyweight design pattern 8
The proxy design pattern 8
Behavioral design patterns 8
The value object design pattern 9
The null object design pattern 10
The strategy design pattern 10
The command design pattern 10
The chain of responsibility design pattern 10
The interpreter design pattern 11
The iterator design pattern 11
The mediator design pattern 11

[i]
Table of Contents

The memento design pattern 11


The observer design pattern 11
The state design pattern 12
The template method design pattern 12
The visitor design pattern 12
Functional design patterns 12
Monoids 13
Monads 13
Functors 13
Scala-specific design patterns 13
The lens design pattern 14
The cake design pattern 14
Pimp my library 14
Stackable traits 15
The type class design pattern 15
Lazy evaluation 15
Partial functions 15
Implicit injection 15
Duck typing 15
Memoization 16
How to choose a design pattern 16
Setting up the development environment 16
Installing Scala 17
Scala IDEs 17
Dependency management 18
SBT 18
Maven 22
SBT versus Maven 25
Summary 26
Chapter 2: Traits and Mixin Compositions 27
Traits 28
Traits as interfaces 28
Mixing in traits with variables 29
Traits as classes 29
Extending classes 30
Extending traits 31
Mixin compositions 32
Mixing traits in 32
Composing 33
Composing simple traits 33
Composing complex traits 34
Composing with self types 35
Clashing traits 37
Same signatures and return types traits 37
Same signatures and different return types traits 37

[ ii ]
Table of Contents

Same signatures and return types mixins 38


Same signatures and different return types mixins 39
Multiple inheritance 40
The diamond problem 40
The limitations 42
Linearization 42
Rules of inheritance hierarchies 43
Linearization rules 43
How linearization works 44
Initialization 45
Method overriding 45
Testing traits 48
Using a class 48
Mixing the trait in 49
Mixing into the test class 49
Mixing into the test cases 50
Running the tests 51
Traits versus classes 51
Summary 52
Chapter 3: Unification 53
Functions and classes 53
Functions as classes 54
Function literals 54
Functions without syntactic sugar 55
Increased expressivity 56
Algebraic data types and class hierarchies 56
ADTs 56
Sum ADTs 56
Product ADTs 57
Hybrid ADTs 58
The unification 58
Pattern matching 59
Pattern matching with values 59
Pattern matching for product ADTs 60
Modules and objects 61
Using modules 61
Summary 64
Chapter 4: Abstract and Self Types 65
Abstract types 65
Generics 66
Abstract types 67
Generics versus abstract types 68
Usage advice 70

[ iii ]
Table of Contents

Polymorphism 71
Subtype polymorphism 71
Parametric polymorphism 72
Ad hoc polymorphism 72
Adding functions for multiple types 74
Self types 75
Using self types 75
Requiring multiple components 77
Conflicting components 78
Self types and the cake design pattern 80
Self types versus inheritance 81
Inheritance leaks functionality 81
Summary 83
Chapter 5: Aspect-Oriented Programming and Components 85
Aspect-oriented programming 86
Chapter case example 86
Without AOP 88
With AOP 90
Components in Scala 91
Scala is rich 92
Implementing components 92
Self types for components 92
Summary 95
Chapter 6: Creational Design Patterns 97
What are creational design patterns? 98
The factory method design pattern 98
Class diagram 98
Code example 100
Scala alternatives 102
What is it good for? 102
What is it not so good for? 102
The abstract factory 104
Class diagram 105
Code example 105
Scala alternatives 106
What is it good for? 107
What is it not so good for? 107
Other factory design patterns 107
The static factory 107
The simple factory 108
Factory combinations 108

[ iv ]
Table of Contents

Lazy initialization 108


Class diagram 109
Code example 109
What is it good for? 110
What is it not so good for? 111
The singleton design pattern 111
Class diagram 111
Code example 111
What is it good for? 113
What is it not so good for? 114
The builder design pattern 114
Class diagram 114
Code example 116
Java-like implementation 116
Implementation with a case class 117
Using generalized type constraints 119
Using require statements 123
What is it good for? 124
What is it not so good for? 124
The prototype design pattern 125
Class diagram 125
Code example 125
What is it good for? 126
What is it not so good for? 126
Summary 127
Chapter 7: Structural Design Patterns 129
What are structural design patterns? 129
The adapter design pattern 130
Class diagram 130
Code example 131
The adapter design pattern with final classes 132
The adapter design pattern the Scala way 133
What is it good for? 134
What is it not so good for? 134
The decorator design pattern 134
Class diagram 135
Code example 136
The decorator design pattern the Scala way 139
What is it good for? 142
What is it not so good for? 142

[v]
Table of Contents

The bridge design pattern 142


Class diagram 143
Code example 144
The bridge design pattern the Scala way 146
What is it good for? 148
What is it not so good for? 148
The composite design pattern 148
Class diagram 148
Code example 149
What is it good for? 152
What is it not so good for? 152
The facade design pattern 152
Class diagram 152
Code example 153
What is it good for? 155
What is it not so good for? 155
The flyweight design pattern 155
Class diagram 156
Code example 157
What is it good for? 160
What is it not so good for? 160
The proxy design pattern 160
Class diagram 161
Code example 161
What is it good for? 164
What is it not so good for? 164
Summary 164
Chapter 8: Behavioral Design Patterns – Part 1 165
What are behavioral design patterns? 165
The value object design pattern 166
Class diagram 166
Code example 167
What is it good for? 169
What is it not so good for? 169
The null object design pattern 169
Class diagram 170
Code example 170
What is it good for? 173
What is it not so good for? 173

[ vi ]
Table of Contents

The strategy design pattern 174


Class diagram 174
Code example 175
The strategy design pattern the Scala way 178
The command design pattern 179
Class diagram 180
Code example 181
The command design pattern the Scala way 183
What is it good for? 184
What is it not so good for? 184
The chain of responsibility design pattern 185
Class diagram 185
Code example 187
The chain of responsibility design pattern the Scala way 190
What is it good for? 191
What is it not so good for? 191
The interpreter design pattern 192
Class diagram 192
Code example 193
What is it good for? 196
What is it not so good for? 196
Summary 196
Chapter 9: Behavioral Design Patterns – Part 2 199
The iterator design pattern 200
Class diagram 200
Code example 201
What is it good for? 202
What is it not so good for? 203
The mediator design pattern 203
Class diagram 203
Code example 204
What is it good for? 207
What is it not so good for? 208
The memento design pattern 208
Class diagram 208
Code example 209
What is it good for? 212
What is it not so good for? 212

[ vii ]
Table of Contents

The observer design pattern 213


Class diagram 213
Code example 214
What is it good for? 216
What is it not so good for? 217
The state design pattern 217
Class diagram 217
Code example 218
What is it good for? 220
What is it not so good for? 220
The template method design pattern 220
Class diagram 220
Code example 221
What is it good for? 224
What is it not so good for? 224
The visitor design pattern 225
Class diagram 225
Code example 226
The visitor design pattern the Scala way 229
What is it good for? 233
What is it not so good for? 233
Summary 234
Chapter 10: Functional Design Patterns – The Deep Theory 235
Abstraction and vocabulary 236
Monoids 236
What are monoids? 236
Monoids in real life 237
Using monoids 239
Monoids and foldable collections 239
Monoids and parallel computations 241
Monoids and composition 243
When to use monoids? 246
Functors 246
Functors in real life 247
Using our functors 248
Monads 249
What is a monad? 249
The flatMap method 250
The unit method 250
The connection between map, flatMap, and unit 251
The names of the methods 251
The monad laws 253

[ viii ]
Table of Contents

Monads in real life 254


Using monads 255
The option monad 255
More advanced monad example 258
Monad intuition 265
Summary 265
Chapter 11: Functional Design Patterns – Applying What
We Learned 267
The lens design pattern 268
Lens example 268
Without the lens design pattern 269
Immutable and verbose 269
Using mutable properties 271
With the lens design pattern 272
Minimizing the boilerplate 273
The cake design pattern 274
Dependency injection 274
Dependency injection libraries and Scala 274
Dependency injection in Scala 275
Writing our code 275
Wiring it all up 282
Unit testing our application 284
Other alternatives 285
Implicits 285
Reader monad 285
The pimp my library design pattern 286
Using the pimp my library 286
Pimp my library in real life 289
The stackable traits design pattern 289
Using stackable traits 289
The type class design pattern 293
Type class example 293
Alternatives 297
Lazy evaluation 297
Evaluating by name parameters only once 298
Alternative lazy evaluation 299
Partial functions 300
Partial functions are not partially applied functions 300
Partially defined functions 302

[ ix ]
Table of Contents

Implicit injection 304


Implicit conversions 305
Dependency injection using implicits 306
Testing with implicit dependency injection 308
Duck typing 308
Duck typing example 309
Alternatives 311
When to use duck typing 311
Memoization 311
Memoization example 311
Alternatives 314
Summary 314
Chapter 12: Real-Life Applications 315
Why should we use libraries? 316
The Scalaz library 316
Monoids in Scalaz 317
Using monoids 317
Testing monoids 318
Monads in Scalaz 319
Using monads 319
Testing monads 324
The possibilities of Scalaz 324
Writing a complete application 324
Application specifications 325
Implementation 326
The libraries to use 327
Writing some code 329
Wiring it all up 339
The end result 341
Testing 342
Unit testing 342
Application testing 343
The future of our application 345
Summary 345
Index 347

[x]
Preface
Software engineering and design has existed for many years now. We use software
almost everywhere in our lives, and this makes programs extremely distinct in terms
of the problems they solve.

Regardless of the number of things that can be done with programming, there are
still some specific features that repeat over and over again. Over time, people have
come up with some best practices that help to tackle specific patterns that emerge in
programs. These are called design patterns.

Design patterns solve not only commonly occurring problems, but also deal with
language limitations. No matter what the specific design patterns are and what
single issue they solve, all of them in the end aim at producing better software.
This includes improved readability, simplicity, easier maintainability, testability,
extendibility, and efficiency. Today, design patterns are an important part of every
good software engineer's arsenal.

Together with the large number of problems that we tackle with programming,
there are also many languages that we can use. Every language is different and has
its strengths and weaknesses, so we also need to take this into consideration when
doing something. In this book, we will look at design patterns from the point of view
of Scala.

Scala has become extremely popular in the last couple of years. Many companies use
it in production for various purposes—big data processing, writing APIs, machine
learning, and so on. Switching to Scala from popular languages, such as Java, turns
out to be quite simple because it is a hybrid of an object-oriented language and
a functional programming language. Using Scala to its full potential, however,
requires us to be familiar with not only the object-oriented features, but also with the
functional ones. The use of Scala could improve performance and the time it takes to
implement the features. One of the reasons is the really high expressivity of Scala.

[ xi ]
Preface

The fact that Scala is close to object-oriented languages means that many of the design
patterns for object-oriented programming are still applicable here. The fact that it is
also functional means that some other design patterns also applicable, and some of
the original ones could be modified to better fit the paradigm of Scala. In this book, we
will be focusing on all of them—we will go through some specific features of Scala and
then we will look at the popular Gang of Four design patterns viewed from the Scala
perspective. We will also become familiar with design patterns that are exclusive to
Scala, and we will understand different functional programming concepts, including
monoids and monads. Having meaningful examples always makes learning and
understanding easier. We will try to provide examples that you can easily map to real
problems that you would potentially be solving. We will also introduce some libraries,
which will be useful for anyone who writes real-world applications.

What this book covers


Chapter 1, The Design Patterns Out There and Setting Up Your Environment, is a brief
introduction to design patterns, why they exist, and their different types. This chapter
also provides you with tips on how you can set up your environment in order to easily
run the examples in the book.

Chapter 2, Traits and Mixin Compositions, talks about traits and mixin compositions in
Scala, multiple inheritance, and the rules of linearization that the Scala programming
language uses when extending multiple traits.

Chapter 3, Unification, covers the various unifications that exist in Scala, which make
it as expressive as it is.

Chapter 4, Abstract and Self Types, covers the different types of polymorphism that
exist in Scala that help to make generic and extendible software.

Chapter 5, Aspect-Oriented Programming and Components, shows the concept of


aspect-oriented programming and how it can be applied to Scala. This chapter also
explains what components are and how to build applications using multiple small
and simple components.

Chapter 6, Creational Design Patterns, covers the most popular creational design
patterns from the Gang of Four. All patterns are viewed from the point of view of
Scala and alternatives are shown where applicable.

Chapter 7, Structural Design Patterns, goes through the most popular structural design
patterns from the Gang of Four from the Scala point of view. This chapter also shows
Scala alternatives where this is applicable and gives usage advice.

[ xii ]
Preface

Chapter 8, Behavioral Design Patterns – Part 1, covers Part 1 of behavioral design


patterns from the Gang of Four viewed from the Scala perspective. This chapter
also provides examples and usage advice.

Chapter 9, Behavioral Design Patterns – Part 2, covers Part 2 of behavioral design


patterns from the Gang of Four viewed from the Scala perspective. This chapter
also provides examples and usage advice.

Chapter 10, Functional Design Patterns – The Deep Theory, delves into pure functional
programming concepts such as monoids, functors, and monads. This chapter also
explains these concepts in an understandable way, along with some examples.

Chapter 11, Functional Design Patterns – Applying What We Learned, presents design
patterns that are specific to Scala. It is loaded with examples along with theory and
usage advice.

Chapter 12, Real-Life Applications, introduces you to the Scalaz library. You will write
a complete application that applies many of the concepts learned in the book, and
you will finish off with a summary.

What you need for this book


You will need to install an IDE that supports the Scala programming language
(IntelliJ IDEA or Eclipse), even though a text editor also works well to read the code.
You will need to have Maven and Scala (not 100% required as Maven will take care
of downloading Scala for the purposes of compilation).

The examples in the book were written and tested on a Unix-based operating system;
however, they should also successfully compile and run on Windows.

Who this book is for


You are a software engineer who already has some knowledge of Scala, but wants
to get more practical understanding of how to apply it in real-world application
development, or you might simply want to have a useful reference to consult while
designing applications. Having an understanding of the importance of using best
practices and writing nice code is good; however, even if you don't, hopefully you
will be convinced by the time you finish reading this book. Prior knowledge of
design patterns is not required, but if you are familiar with some, this book will be
useful, as we will be looking at them from the point of view of Scala.

[ xiii ]
Preface

Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of
their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We can include other contexts through the use of the include directive."

A block of code is set as follows:


object IOAction {

def apply[T](result: => T): IOAction[T] =


new SimpleAction[T](result)

private class SimpleAction[T](result: => T) extends IOAction[T]


{
override def apply(state: State): (State, T) =
(state.next, result)
}
}

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
abstract class FileIO {
// this makes sure nobody can create a state
private class FileIOState(id: Int) extends State {
override def next: State = new FileIOState(id + 1)
}

def run(args: Array[String]): Unit = {


val action = runIO(args(0), args(1))
action(new FileIOState(0))
}

def runIO(readPath: String, writePath: String): IOAction[_]


}

[ xiv ]
Preface

New terms and important words are shown in bold.

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention


the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

Downloading the example code


You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you.

[ xv ]
Preface

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at [email protected] with a link to the suspected


pirated material.

We appreciate your help in protecting our authors and our ability to bring you
valuable content.

Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.

[ xvi ]
The Design Patterns Out
There and Setting Up Your
Environment
In the world of computer programming, there are multiple different ways to create
a solution that does something. However, some might contemplate whether there is
a correct way of achieving a specific task. The answer is yes; there is always a right
way, but in software development, there are usually multiple ways to achieve a task.
Some factors exist, which guide the programmer to the right solution, and depending
on them, people tend to get the expected result. These factors could define many
things—the actual language being used, algorithm, type of executable produced,
output format, and the code structure. In this book, the language is already chosen
for us—Scala. There are, however, a number of ways to use Scala, and we will be
focusing on them—the design patterns.

In this chapter, we will explain what design patterns are and why they exist. We will
go through the different types of design patterns that are out there. This book aims
to provide useful examples to aid you in the learning process, and being able to run
them easily is key. Hence, some points on how to set up a development environment
properly will be given here. The top-level topics we will go through are as follows:

• What is a design pattern and why do they exist?


• The main types of design patterns and their features
• Choosing the right design pattern
• Setting up a development environment in real life

The last point doesn't have to do much with design patterns. However, it is always a
good idea to build projects properly, as this makes it much easier to work in future.

[1]
The Design Patterns Out There and Setting Up Your Environment

Design patterns
Before delving into the Scala design patterns, we have to explain what they actually
are, why they exist, and why it is worth being familiar with them.

Software is a broad subject, and there are innumerable examples of things people
can do with it. At first glance, most of these things are completely different—games,
websites, mobile phone applications, and specialized systems for different industries.
There are, however, many similarities in how software is built. Many times, people
have to deal with similar issues, no matter the type of software they create. For
example, computer games as well as websites might need to access a database.
And throughout time, by experience, developers learn how structuring their code
differs for the various tasks that they perform.

A formal definition for design patterns will allow you to understand the value of
using good practice in building elegant and efficient software.

The formal definition for design patterns


A design pattern is a reusable solution to a recurring problem
in software design. It is not a finished piece of code, but a
template, which helps solving the particular problem or
family of problems.

Design patterns are best practices, to which the software community has arrived
over a period of time. They are supposed to help write efficient, readable, testable,
and easily extendable code. In some cases, they can be a result of a programming
language not being expressive enough to elegantly achieve a goal. This means that
more feature-rich languages might not even need a design pattern, while others still
do. Scala is one of those rich languages, and in some cases, it makes the use of some
design patterns obsolete or simpler. We will see how exactly it does that in this book.

The lack or existence of a certain functionality within a programming language


also makes it able to implement additional design patterns that others cannot.
The opposite is also valid—it might not be able to implement things that others can.

Scala and design patterns


Scala is a hybrid language, which combines features from object-oriented and
functional languages. This not only allows it to keep some of the well-known object-
oriented design patterns relevant but also provides various other ways of exploiting its
features to write code, which is clean, efficient, testable, and extendable all at the same
time. The hybrid nature of the language also makes some of the traditional object-
oriented design patterns obsolete, or possible, using other cleaner techniques.
[2]
Chapter 1

The need for design patterns and their


benefits
Everybody needs design patterns and should look into some before writing code. As
we mentioned earlier, they help writing efficient, readable, extendable, and testable
code. All these features are really important to companies in the industry.

Even though in some cases it is preferred to quickly write a prototype and get it out,
it is more usually the case that a piece of software is supposed to evolve. Maybe you
will have experience of extending some badly written code, but regardless, it is a
challenging task and takes a really long time, and sometimes it feels that rewriting
it would be easier. Moreover, this makes introducing bugs into the system much
more likely.

Code readability is also something that should be appreciated. Of course, one could
use a design pattern and still have their code hard to read, but generally, design
patterns help. Big systems are usually worked on by many people, and everyone
should be able to understand what exactly is going on. Also, people who join a
team are able to integrate much more easily and quickly if they are working on
a well-written piece of software.

Testability is something that prevents developers from introducing bugs when


writing or extending code. In some cases, code could be created so badly that it is
not even testable. Design patterns are supposed to eliminate these problems as well.

While efficiency is often connected to algorithms, design patterns could also affect
it. A simple example could be an object, which takes a long time to instantiate, and
instances are used in many places in an application, but could be made singleton
instead. You will see more concrete examples in the later chapters of this book.

Design pattern categories


The fact that software development is an extremely broad topic leads to a number
of things that can be done with programming. Everything is different and this leads
to various requirements about the qualities of programs. All these facts have caused
many different design patterns to be invented. This is further contributed to by the
existence of various programming languages with different features and levels
of expressiveness.

[3]
The Design Patterns Out There and Setting Up Your Environment

This book focuses on the design patterns from the point of view of Scala. As we
mentioned previously, Scala is a hybrid language. This leads us to a few famous
design patterns that are not needed anymore—one example is the null object design
pattern, which can simply be replaced by Scala's Option. Other design patterns
become possible using different approaches—the decorator design pattern can be
implemented using stackable traits. Finally, some new design patterns become
available, which are applicable specifically to the Scala programming language—the
cake design pattern, pimp my library, and so on. We will focus on all of these and
make it clear where the richness of Scala helps us to make our code even cleaner
and simpler.

Even if there are many different design patterns, they can all be collated into a few
main groups:

• Creational
• Structural
• Behavioral
• Functional
• Scala-specific design patterns

Some of the design patterns that are specific to Scala can be assigned to the previous
groups. They can either be additional or replacements of the already existing ones.
They are typical to Scala and take advantage of some advanced language features
or simply features not available in other languages.

The first three groups contain the famous Gang of Four design patterns. Every design
pattern book covers them and so will we. The rest, even if they can be assigned to
one of the first three groups, will be specific to Scala and functional programming
languages. In the next few subsections, we will explain the main characteristics of
these groups and briefly present the actual design patterns that fall under them.

Creational design patterns


The creational design patterns deal with object creation mechanisms. Their purpose
is to create objects in a way that is suitable to the current situation, which could lead
to unnecessary complexity and the need of extra knowledge if they were not there.
The main ideas behind the creational design patterns are as follows:

• Knowledge encapsulation about the concrete classes


• Hiding details about the actual creation and how objects are combined

[4]
Chapter 1

We will be focusing on the following creational design patterns in this book:

• The abstract factory design pattern


• The factory method design pattern
• The lazy initialization design pattern
• The singleton design pattern
• The object pool design pattern
• The builder design pattern
• The prototype design pattern

The following few sections give a brief definition of what these patterns are. They will
be looked at in depth individually later in this book.

The abstract factory design pattern


This is used to encapsulate a group of individual factories that have a common theme.
When used, the developer creates a specific implementation of the abstract factory
and uses its methods in the same way as in the factory design pattern to create objects.
It can be thought of as another layer of abstraction that helps instantiating classes.

The factory method design pattern


This design pattern deals with creation of objects without explicitly specifying the
actual class that the instance will have—it could be something that is decided at
runtime based on many factors. Some of these factors can include operating systems,
different data types, or input parameters. It gives developers the peace of mind of
just calling a method rather than invoking a concrete constructor.

The lazy initialization design pattern


This design pattern is an approach to delay the creation of an object or the evaluation
of a value until the first time it is needed. It is much more simplified in Scala than it is
in an object-oriented language such as Java.

The singleton design pattern


This design pattern restricts the creation of a specific class to just one object. If more
than one class in the application tries to use such an instance, then this same instance
is returned for everyone. This is another design pattern that with the use of basic
Scala features can be easily achieved.

[5]
The Design Patterns Out There and Setting Up Your Environment

The object pool design pattern


This design pattern uses a pool of objects that are already instantiated and ready
for use. Whenever someone requires an object from the pool, it is returned, and after
the user is finished with it, it puts it back into the pool manually or automatically.
A common use for pools are database connections, which generally are expensive to
create; hence, they are created once and then served to the application on request.

The builder design pattern


The builder design pattern is extremely useful for objects with many possible
constructor parameters, which would otherwise require developers to create many
overrides for the different scenarios an object could be created in. This is different to
the factory design pattern, which aims to enable polymorphism. Many of the modern
libraries today employ this design pattern. As we will see later, Scala can achieve this
pattern really easily.

The prototype design pattern


This design pattern allows object creation using a clone() method from an already
created instance. It can be used in cases when a specific resource is expensive to
create or when the abstract factory pattern is not desired.

Structural design patterns


Structural design patterns exist in order to help establish the relationships between
different entities in order to form larger structures. They define how each component
should be structured so that it has very flexible interconnecting modules that can
work together in a larger system. The main features of structural design patterns
include the following:

• The use of composition to combine the implementations of multiple objects


• Help build a large system made of various components by maintaining
a high level of flexibility

In this book, we will focus on the following structural design patterns:

• The adapter design pattern


• The decorator design pattern
• The bridge design pattern
• The composite design pattern
• The facade design pattern

[6]
Chapter 1

• The flyweight design pattern


• The proxy design pattern

The next subsections will put some light on what these patterns are about before we
delve in them later in this book.

The adapter design pattern


The adapter design pattern allows the interface of an existing class to be used from
another interface. Imagine that there is a client who expects your class to expose a
doWork() method. You might have the implementation ready in another class but the
method is called differently and is incompatible. It might require extra parameters too.
This could also be a library that the developer doesn't have access to for modifications.
This is where the adapter can help by wrapping the functionality and exposing the
required methods. The adapter is useful for integrating the existing components. In
Scala, the adapter design pattern can be easily achieved using implicit classes.

The decorator design pattern


Decorators are a flexible alternative to subclassing. They allow developers to extend
the functionality of an object without affecting other instances of the same class.
This is achieved by wrapping an object of the extended class into one that extends
the same class and overrides the methods whose functionality is supposed to be
changed. Decorators in Scala can be built much more easily using another design
pattern called stackable traits.

The bridge design pattern


The purpose of the bridge design pattern is to decouple an abstraction from its
implementation so that the two can vary independently. It is useful when the class
and its functionality vary a lot. The bridge reminds us of the adapter pattern, but
the difference is that the adapter pattern is used when something is already there
and you cannot change it, while the bridge design pattern is used when things are
being built. It helps us to avoid ending up with multiple concrete classes that will be
exposed to the client. You will get a clearer understanding when we delve deeper
in the topic, but for now, let's imagine that we want to have a FileReader class
that supports multiple different platforms. The bridge will help us end up with
FileReader, which will use a different implementation, depending on the platform.
In Scala, we can use self-types in order to implement a bridge design pattern.

[7]
The Design Patterns Out There and Setting Up Your Environment

The composite design pattern


The composite is a partitioning design pattern that represents a group of objects that
are to be treated as only one object. It allows developers to treat individual objects
and compositions uniformly and to build complex hierarchies without complicating
the source code. An example of composite could be a tree structure where a node can
contain other nodes, and so on.

The facade design pattern


The purpose of the facade design pattern is to hide the complexity of a system and
its implementation details by providing a simpler interface to use to the client. This
also helps to make the code more readable and to reduce the dependencies of the
outside code. It works as a wrapper around the system that is being simplified, and
of course, it can be used in conjunction with some of the other design patterns we
mentioned previously.

The flyweight design pattern


The flyweight design pattern provides an object that is used to minimize memory
usage by sharing it throughout the application. This object should contain as
much data as possible. A common example given is a word processor, where each
character's graphical representation is shared with the other same characters. The local
information then is only the position of the character, which is stored internally.

The proxy design pattern


The proxy design pattern allows developers to provide an interface to other objects
by wrapping them. They can also provide additional functionality, for example,
security or thread-safety. Proxies can be used together with the flyweight pattern,
where the references to shared objects are wrapped inside proxy objects.

Behavioral design patterns


Behavioral design patterns increase communication flexibility between objects based
on the specific ways they interact with each other. Here, creational patterns mostly
describe a moment in time during creation, structural patterns describe a more
or less static structure, and behavioral patterns describe a process or flow. They
simplify this flow and make it more understandable.

[8]
Chapter 1

The main features of behavioral design patterns are as follows:

• What is being described is a process or flow


• The flows are simplified and made understandable
• They accomplish tasks that would be difficult or impossible to achieve
with objects

In this book, we will focus our attention on the following behavioral design patterns:

• The value object design pattern


• The null object design pattern
• The strategy design pattern
• The command design pattern
• The chain of responsibility design pattern
• The interpreter design pattern
• The iterator design pattern
• The mediator design pattern
• The memento design pattern
• The observer design pattern
• The state design pattern
• The template method design pattern
• The visitor design pattern

The following subsections will give brief definitions of the aforementioned


behavioral design patterns.

The value object design pattern


Value objects are immutable and their equality is based not on their identity, but
on their fields being equal. They can be used as data transfer objects, and they can
represent dates, colors, money amounts, numbers, and so on. Their immutability
makes them really useful in multithreaded programming. The Scala programming
language promotes immutability, and value objects are something that naturally
something occurs there.

[9]
The Design Patterns Out There and Setting Up Your Environment

The null object design pattern


Null objects represent the absence of a value and they define a neutral behavior.
This approach removes the need to check for null references and makes the code
much more concise. Scala adds the concept of optional values, which can replace this
pattern completely.

The strategy design pattern


The strategy design pattern allows algorithms to be selected at runtime. It defines a
family of interchangeable encapsulated algorithms and exposes a common interface
to the client. Which algorithm is chosen could depend on various factors that are
determined while the application runs. In Scala, we can simply pass a function as
a parameter to a method, and depending on the function, a different action will be
performed.

The command design pattern


This design pattern represents an object that is used to store information about
an action that needs to be triggered at a later time. The information includes the
following:

• The method name


• The owner of the method
• Parameter values

The client then decides which commands to be executed and when by the invoker.
This design pattern can easily be implemented in Scala using the by-name
parameters feature of the language.

The chain of responsibility design pattern


The chain of responsibility is a design pattern where the sender of a request is
decoupled from its receiver. This way, it makes it possible for multiple objects to
handle the request and to keep logic nicely separate. The receivers form a chain
where they pass the request, and if possible, they process it, and if not, they pass it
to the next receiver. There are variations where a handler might dispatch the request
to multiple other handlers at the same time. This somehow reminds of function
composition, which in Scala can be achieved using the stackable traits design pattern.

[ 10 ]
Chapter 1

The interpreter design pattern


The interpreter design pattern is based on the possibility to characterize a well-known
domain with a language with strict grammar. It defines classes for each grammar
rule in order to interpret sentences in the given language. These classes are likely to
represent hierarchies as grammar is usually hierarchical as well. Interpreters can be
used in different parsers, for example, SQL or other languages.

The iterator design pattern


The iterator design pattern is when an iterator is used to traverse a container and
access its elements. It helps to decouple containers from the algorithms performed
on them. What an iterator should provide is sequential access to the elements of an
aggregate object without exposing the internal representation of the iterated collection.

The mediator design pattern


This pattern encapsulates the communication between different classes in an
application. Instead of interacting directly with each other, objects communicate
through the mediator, which reduces the dependencies between them, lowers the
coupling, and makes the overall application easier to read and maintain.

The memento design pattern


This pattern provides the ability to rollback an object to its previous state. It is
implemented with three objects: originator, caretaker, and memento. The originator
is the object with the internal state; the caretaker will modify the originator, and
a memento is an object that contains the state that the originator returns. The
originator knows how to handle a memento in order to restore its previous state.

The observer design pattern


This design pattern allows the creation of publish/subscribe systems. There is a
special object called subject that automatically notifies all the observers when there
are any changes in the state. This design pattern is popular in various GUI toolkits
and generally where event handling is needed. It is also related to reactive
programming, which is enabled by libraries such as Akka, and we will see an
example of this toward the end of this book.

[ 11 ]
The Design Patterns Out There and Setting Up Your Environment

The state design pattern


This design pattern is similar to the strategy design pattern, and it uses a state
object to encapsulate different behavior for the same object. It improves the code's
readability and maintainability by avoiding the use of large conditional statements.

The template method design pattern


This design pattern defines the skeleton of an algorithm in a method and then passes
some of the actual steps to the subclasses. It allows developers to alter some of the
steps of an algorithm without having to modify its structure. An example of this
could be a method in an abstract class that calls other abstract methods, which will
be defined in the children.

The visitor design pattern


The visitor design pattern represents an operation to be performed on the elements
of an object structure. It allows developers to define a new operation without
changing the original classes. Scala can minimize the verbosity of this pattern
compared to the pure object-oriented way of implementing it by passing
functions to methods.

Functional design patterns


We will be looking into all of the preceding design patterns from the point of view
of Scala. This means that they will look different than in other languages, but
they've still been designed not specifically for functional programming. Functional
programming is much more expressive than object-oriented programming. It has
its own design patterns that help making the life of a programmer easier. We will
focus on:

• Monoids
• Monads
• Functors

After we've looked at some Scala functional programming concepts, and we've
been through these, we will mention some interesting design patterns from the
Scala world.

A brief explanation of the preceding listed patterns will follow in the next few
subsections.

[ 12 ]
Chapter 1

Monoids
Monoid is a concept that comes from mathematics. We will take a look at it in more
detail with all the theory needed to understand it later in this book. For now, it will
be enough to remember that a monoid is an algebraic structure with a single associative
binary operation and an identity element. Here are the keywords you should remember:

• The associative binary operation. This means (a+b)+c = a+(b+c).


• The identity element. This means a+i = i+a = a. Here, the identity is i.

What is important about monoids is that they give us the possibility to work with
many different types of values in a common way. They allow us to convert pairwise
operations to work with sequences; the associativity gives us the possibility for
parallelization, and the identity element allows us to know what to do with empty
lists. Monoids are great to easily describe and implement aggregations.

Monads
In functional programming, monads are structures that represent computations as
sequences of steps. Monads are useful for building pipelines, adding operations with
side effects cleanly to a language where everything is immutable, and implementing
compositions. This definition might sound vague and unclear, but explaining
monads in a few sentences seems to be something hard to achieve. Later in this book,
we will focus on them and try and clear things up without the use of a complex
mathematical theory. We will try to show why monads are useful and what they
can help with, as long as developers understand them well.

Functors
Functors come from a category theory, and as for monads, it takes time to explain
them properly. We will look at functors later in this book. For now, you could
remember that functors are things that can allow us to lift a function of the type
A => B to a function of the type F[A] => F[B].

Scala-specific design patterns


The design patterns in this group could be assigned to some of the previous groups.
However, they are specific to Scala and exploit some of the language features that we
will focus on in this book, and we've decided to place them in their own group.

[ 13 ]
The Design Patterns Out There and Setting Up Your Environment

We will focus our attention on the following ones:

• The lens design pattern


• The cake design pattern
• Pimp my library
• Stackable traits
• The type class design pattern
• Lazy evaluation
• Partial functions
• Implicit injection
• Duck typing
• Memoization

The next subsections will give you some brief information about these patterns
before we properly study them later in this book.

The lens design pattern


The Scala programming language promotes immutability. Having objects immutable
makes it harder to make mistakes. However, sometimes mutability is required and
the lens design pattern helps us achieve this nicely.

The cake design pattern


The cake design pattern is the Scala way to implement dependency injection. It is
something that is used quite a lot in real-life applications, and there are numerous
libraries that help developers achieve it. Scala has a way of doing this using language
features, and this is what the cake design pattern is all about.

Pimp my library
Many times, engineers need to work with libraries, which are made to be as generic
as possible. Sometimes, we need to do something more specific to our use case,
though. The pimp my library design pattern provides a way to write extension
methods for libraries, which we cannot modify. We can also use it for our own
libraries as well. This design pattern also helps to achieve a better code readability.

[ 14 ]
Chapter 1

Stackable traits
The stackable traits is the Scala way to implement the decorator design pattern. It can
also be used to compose functions, and it's based on a few advanced Scala features.

The type class design pattern


This design pattern allows us to write generic code by defining a behavior that must
be supported by all members of a specific type class. For example, all numbers must
support the addition and subtraction operations.

Lazy evaluation
Many times, engineers have to deal with operations that are slow and/or expensive.
Sometimes, the result of these operations might not even be needed. Lazy evaluation
is a technique that postpones the operation execution until it is actually needed. It
could be used for application optimization.

Partial functions
Mathematics and functional programming are really close together. As a consequence,
there are functions that exist that are only defined for a subset of all the possible input
values they can get. A popular example is the square root function, which only works
for non-negative numbers. In Scala, such functions can be used to efficiently perform
multiple operations at the same time or to compose functions.

Implicit injection
Implicit injection is based on the implicit functionality of the Scala programming
language. It automatically injects objects whenever they are needed, as long as
they exist in a specific scope. It can be used for many things, including dependency
injection.

Duck typing
This is a feature that is available in Scala and is similar to what some dynamic
languages provide. It allows developers to write code, which requires the callers to
have some specific methods (but not implement an interface). When someone uses
a method with a duck type, it is actually checked during compile time whether the
parameters are valid.

[ 15 ]
Random documents with unrelated
content Scribd suggests to you:
wayfarer in an inn; and yet what more is any of us in this brief world?
No, Mrs. Bredon, you are exempt.”
“Oh, do stop him,” said Angela. “How did you come down, Mr.
Eames?”
“By the midday train, a funeral pageant in itself. Was Mr. Mottram
much known in the neighbourhood?”
“He is now,” replied Mr. Pulteney, with irrepressible ghoulishness.
“The victim of sudden death is like a diver; no instinct of decency
withholds us from watching his taking-off.”
“I don’t think he had any near relations living,” said Brinkman,
“except young Simmonds. He’ll be there, I suppose; but there wasn’t
much love lost between them. He will hardly be interested, anyhow,
in the reading of the will.”
“By the way, Mr. Brinkman, His Lordship asked me to say that
you will be very welcome at the Cathedral house, if you are detained
in Pullford at all.”
“It is extremely kind of him. But I had wound up all Mr. Mottram’s
outstanding affairs before he came away for his holiday, and I don’t
suppose I shall be needed. I was thinking of going up to London in a
day or two. I have to shift for myself, you see.”
“Have some coffee, Eames,” suggested Bredon; “you must need
it after a tiring journey like that.”
“Thanks, I think I will. Not that I’m tired, really. It makes so much
difference on the railway if you are occupied.”
“You don’t mean to say you are one of those fortunate creatures
who can work in railway trains?”
“No, not work. I played patience all the way.”
“Patience? Did I hear you say patience? Ah, but you only brought
one pack, of course.”
“No, I always travel with two.”
“Two? And Mr. Pulteney has two! Angela, that settles it! This
afternoon I shall have a game.”
“Miles, dear, not the game? You know you can’t play that and
think of anything else at the same time. Mr. Eames, would you mind
dropping your packs in the river? You see, it’s so bad for my
husband; he sits down to an interminable game of patience, and
forgets all about his work and everything.”
“You don’t understand, Angela; it clears the brain. When you’ve
been puzzled over a thing, as I have been over this question of
suicide, your brains get all stale and used up, and you must give
them a fresh start. A game of patience will just do the trick. No, no
milk, thanks. Would you tell Mrs. Davis”—this was to the barmaid
—“that I shall be very busy all the latter part of this afternoon, and
mustn’t be disturbed on any account? It’s all right, Angela; I’ll give
you half an hour now to remonstrate with me, but it won’t be any
use.”
It was not, as a matter of fact, till after the funeral party had left,
and the coffin been removed, that Miles and Angela foregathered.
They went to the old mill-house, feeling that it would be a safe place
for confidences now that Brinkman was otherwise engaged. “Well,”
said Angela, “I suppose you’re wanting some Watson work?”
“Badly. Look here, one of us, either Leyland or I, is beginning to
feel the strain a bit. Everything that crops up makes him more and
more determined to have Simmonds’s blood, and me more and more
inclined to stick to my old solution.”
“You haven’t been doubling that bet again, have you?”
“That’s a detail. Look here, I must tell you all about his find this
morning.” And he proceeded to explain the whole business of the
piece of paper, and Leyland’s inferences from it. “Now,” he finished
up, “what d’you make of all that?”
“Well, he has got a case, hasn’t he? I mean, his explanation
would explain things.”
“Yes, but look at the difficulties.”
“Let’s have them. No, wait a minute, I believe I can do the
difficulties. Let’s try a little womanly intuish. First, you’d have noticed
the piece of paper if it had been there when you went in.”
“Not necessarily. It’s wonderful what one can overlook if one isn’t
thinking about it.”
“Well, then, Simmonds wouldn’t have been such a chump as to
burn the thing on the spot. Especially with a foul smell of gas in the
room, not to mention the corpse. He’d have shoved it into his pocket
and taken it home.”
“There’s a good deal in that. But Leyland would say that
Simmonds was afraid to do that for fear he should be stopped and
searched.”
“Pretty thin. And, then, of course, if it was really important for him
to get the document out of the way, he wouldn’t have left a bit lying
about. He’d have seen that it was all burnt.”
“Leyland says that was because he was in a hurry.”
“Well, let’s have some others. I’m used up.”
“Well, don’t you see that a man who is burning an important
document, holding it in his hand all the time, takes it up by the least
important corner, probably a blank space at the top? This is the work
of a man who wasn’t particularly keen on destroying all traces of the
document, and he held it by the bottom right-hand corner, as one
naturally would.”
“Why not the left hand, and the match in one’s right? Ha! The left-
handed criminal. We are in luck.”
“Don’t you believe it. You start holding it at the left-hand corner,
and then transfer it to your right hand when you’ve thrown the match
away. You try, next time you’re burning your dressmaker’s bill. And
here’s another point: Simmonds would have been bound to stand
with his head right in the window, to keep clear of the gas fumes.
Almost certainly he would have put the paper down on the window-
sill and let it burn, leaving one of those curious damp marks. He
didn’t, because I should have been bound to notice that; I was
looking for marks on the window-sill. If he held it in his hand, he
would be holding it outside the window, and he wouldn’t be such a
chump as to throw away the odd corner in the room when he could
pitch it out of the window. Another thing: he wouldn’t have dared to
burn a light at the window like that for fear of attracting attention.”
“Well, I still think my objections were more important. But go on.”
“Well, since that piece of paper wasn’t dropped in the room
before Leyland and I went into it—probably not, anyhow—it looks as
if it had been dropped in the room since Leyland and I went into it.
Or, at any rate, since the first police search. Because the room has
been kept locked, one way and another, since then.”
“There was no deceiving this man.”
“Which makes it very improbable that the piece of paper was
dropped there by accident at all. Anybody who went in there had no
business to go in there, and would be jolly careful not to leave any
traces. We are therefore irresistibly compelled, my dear Angela, to
the conclusion that somebody dropped it there on purpose.”
“That firm grasp of the obvious. Yes?”
“He put it there deliberately to create an impression. Now, it might
be to create the impression that Simmonds was the murderer. To
whose advantage would that be?”
“Mr. Leyland’s.”
“Angela, don’t be flippant. Is there anybody?”
“Well, Mr. Simmonds hasn’t any enemies that we know of. Unless
it was somebody who was disappointed in the quality of his
handkerchiefs. What you want me to say is, that it must be
somebody who has murdered Mottram himself, and wants to save
his skin by pretending it was Simmonds that did it.”
“I’m dashed if I want you to say that. In fact, it’s just what I didn’t
want you to say. Of course if you assume that Mottram was
murdered by Brinkman, it does all work out, most unpleasantly well.
You see, when Leyland and I were sitting here, talking at Brinkman,
who was hiding behind the wall, Leyland did say that the only thing
which prevented him from arresting Simmonds was the fact that he’d
no evidence to connect him with the actual room. I could see what
he was up to—he wanted Brinkman to take the hint (assuming, of
course, that he was the real murderer) and start manufacturing clues
to incriminate Simmonds. Well, it looks very much as if Brinkman
had taken the hint, and were doing identically what Leyland
suggested. Curse it all.”
“Still, it was clever of Brinky to get in when the door was locked.”
“Oh, that’s nothing. I wouldn’t put it beyond Brinkman to have a
duplicate key of that door. . . . No, I’ve nothing to fall back on really
except the absence of motive. What earthly reason had Brinkman for
wanting to do Mottram in? Or rather, I have one other thing to fall
back on. But it’s not evidence; it’s instinct.”
“As how?”
“Why, don’t you see that the whole thing works out too beastly
well? Isn’t it rather too obviously a ruse? I mean, that idea of
dropping a piece of paper with only half a dozen words on it, and yet
those half-dozen words shewing exactly what the document was?
Isn’t it rather too obviously a plant?”
“But it was a plant, if Brinky put it there.”
“Yes, but isn’t it too obviously a plant? So obviously, I mean, that
you couldn’t expect anybody, even Leyland, to think for a moment
that it was genuine? Can Brinkman really have thought that Leyland
wouldn’t see through it?”
“But if he didn’t think so”——
“Double bluff, my good woman, double bluff. I can tell you, crime
is becoming quite a specialized profession nowadays. Don’t you see
that Brinkman argued to himself like this: ‘If I leave an obviously
faked clue lying about like this, Leyland will immediately think that it
is a faked clue, used by one criminal to shove off the blame on
another. Who the criminals are, or which is which, doesn’t matter. It
will convince him that there has, after all, been a murder. And it will
disguise from him the fact that it was suicide.’ Of course all that’s
making Brinkman out to be a pretty smart lad. But I fancy he is a
pretty smart lad. And I read that piece of paper as a bit of double
bluff, meant to harden the ingenious Leyland in his belief that the
suicide was a murder.”
“Ye-es. It’ll look pretty thin before a jury, won’t it?”
“Don’t I know that it’ll look thin before a jury? Especially as, on my
shewing, Brinkman was prepared to let suspicion of murder rest on
himself rather than admit it was suicide. But it does give us a motive.
There’s no doubt that Brinkman is a fanatical anti-clerical, and would
do anything to prevent Mottram’s money going to a Catholic
diocese. . . . I say, what’s that?”
A sudden sneeze, an unmistakable sneeze, had come from
somewhere immediately behind them. In a twinkling Bredon had
rushed round to the other side of the wall. But there was nobody
there.
Chapter XVII.
Mysterious Behaviour of the Old
Gentleman
Bredon and his wife looked at one another in astonishment. It
was impossible that the funeral should yet be over; impossible,
surely, that Brinkman, whose place in the pageant was such a
prominent one, should have absented himself from the ceremony
unnoticed. There was no doubt as to the path which the self-
betrayed listener must have taken. From behind the wall, there was
a gap in a privet-hedge, and through this there was a direct and
speedy retreat to the back door of the inn. The inn itself, when they
went back to it, was as silent as the grave—indeed, the comparison
forced itself upon their minds. It was as if the coffin from upstairs had
taken all human life away with it when it went on its last journey,
leaving nothing but the ticking of clocks and the steaming of a kettle
in the kitchen to rob solitude of its silence. Outside the sun still shone
brightly, though there was a menacing bank of cloud coming up from
the south. The air felt breathless and oppressive; not a door could
bang, not a window rattle. The very flies on the window-panes
seemed drowsy. The Bredons passed from room to room, in the vain
hope of discovering an intruder; everywhere the same loneliness, the
same stillness met them. Bredon had an odd feeling as if they ought,
after all, to be at the funeral; it was so like the emptiness of his old
school when everybody was out of doors except himself on a
summer day.
“I can’t stand much of this,” he said. “Let’s go down toward the
churchyard, and see if we can meet them coming back. Then at least
we shall be in a position to know who wasn’t here.”
The expedition, however, proved abortive; they met Eames
almost on the doorstep, and down the street figures melting away by
twos and threes from the churchyard shewed that the funeral was at
an end. “I say, come in here,” said Bredon. “I want to talk things over
a bit, Mr. Eames.” And the three retired into that “best room” where
tea had been laid on the afternoon of the Bredons’ arrival. “You’ve
just come back from the funeral?”
“This moment. Why?”
“Can you tell us for certain who was there? Was Brinkman there,
for example?”
“Certainly. He was standing just next me.”
“And Mr. Simmonds from the shop—do you know him by sight?”
“He was pointed out to me as the chief mourner. I had a word
with him afterward. But why all this excitement about the local
celebrities?”
“Tell him, Miles,” said Angela. “He may be able to throw some
light on all this.” And Bredon told Eames of the strange
eavesdropping that went on behind the mill-house wall; something,
too, of the suspicions which he and Leyland entertained, and the
difficulty they both found in giving any explanation of the whole
tragedy.
“Well, it’s very extraordinary. Pulteney, of course didn’t go after
all”——
“Pulteney didn’t go?”
“No; didn’t you hear him say, soon after luncheon, that his good
resolutions had broken down, and that he wasn’t going to the funeral
after all? I thought it rather extraordinary at the time.”
“You mean his sudden change of plan?”
“No, the reason he gave for it. He said the afternoon was too
tempting, and he really must go out fishing.”
“Is that a very odd reason for Pulteney? He’s an incalculable sort
of creature.”
“Yes, but it doesn’t happen to be true. Can’t you feel the thunder
in the air? If you can’t, the fishes can, And when there’s thunder in
the air they won’t rise. Pulteney knows that as well as I do.”
“Would you know his rod if you saw it?”
“Yes, I was looking at it with him just before luncheon.”
“Come on.” They went out into the front hall, and Eames gave a
quick glance round. “Yes, that’s it, in the corner. He’s no more out
fishing than you or I.”
“Edward!” said Angela as they returned to the best room. “To
think it was my Edward all the time.”
“Oh, don’t rag, Angela; this is serious. Now, can’t it have been
Pulteney listening all along?”
“He was there, you know, when you and Leyland arranged to go
out to the mill-house after breakfast. And he was there at luncheon,
though I don’t think either of us mentioned that we meant to go there.
Still, he might have guessed that. But what on earth is the poor old
dear up to?”
“Well, one or two things are clear. About Brinkman, I mean.
Whatever his idea may have been when he took me out for a walk to
the gorge and talked about geology he wasn’t ‘reacting’ on Leyland’s
suggestion, because it wasn’t he who was listening behind the wall
when the suggestion was made. And there’s another thing—this bit
of paper Leyland found lying about in the room upstairs. If Brinkman
put it there, then Brinkman did it on his own; he wasn’t playing up to
the suggestion which Leyland made about wanting clues to
incriminate Simmonds with.”
“Still,” objected Angela, “we never proved that it was Brinky who
left that old clue lying about. We only assumed it, because we
thought it was Brinky who was listening behind the wall.”
“You mean that if Pulteney was listening, and Pulteney was—
well, was somehow interested in confusing the tracks of the murder,
it may have been he who left the bit of paper under the table.”
“I didn’t say so. But it seems quite as much on the cards as
anything else in this frightful business.”
“Let’s see, now, what do we know about Pulteney? We know, in
the first place, that he was sleeping in the house on the night when
Mottram died. Actually, he had the room next door to Mottram’s—
between his and the one we’ve got now. According to his own
evidence, he slept soundly all night, and heard nothing. On the other
hand, his own evidence shewed that he went to bed after Mottram
and Brinkman, and we’ve nothing, therefore, to confirm his own
account of his movements. He was woken up the next morning after
the tragedy had occurred, and when he was told about it all he said
was—what was it, Angela?”
“ ‘In that case, Mrs. Davis, I shall fish the Long Pool this
morning.’ ”
“That might almost be represented as suggesting that he wasn’t
exactly surprised when he heard of Mottram’s death, mightn’t it? All
his references to Mottram’s death since then have been rather—
shall we say?—lacking in feeling. He, no less than Brinkman,
seemed to be anxious that we should interpret the death as suicide,
because it was he who suggested to me that idea about Mottram
having brought down the wrong flies, as if he never really had any
intention of fishing at all. He has been rather inquisitive about when
Brinkman was leaving, and when we were leaving too, for that
matter. That’s all you can scrape together, I think, against his general
behaviour. And against that, of course, you’ve got to put the absence
of all known motive.”
“And the general character of the man,” suggested Eames.
“I suppose so. . . . What impression exactly does he make on
you?”
“Why, that he is out of touch with real life. All that macabre
humour of his about corpses and so on is an academic thing—he
has never really felt death close to. I don’t say that a superb actor
mightn’t adopt that ironical pose. I only say it’s far more natural to
regard him as a harmless old gentleman who reflects and doesn’t
act. It’s very seldom that you find the capacity for acute reflection
and the capacity for successful action combined in the same
character. At least, that’s always been my impression.”
“Well, granted that we acquit him of the main charge, as Leyland
would acquit Brinkman of the main charge. He still comes under the
minor suspicion of eavesdropping. He’s as good a candidate for that
position as Brinkman himself, only that it was Brinkman’s brand of
cigarette we found behind the wall yesterday.”
“Edward had run out, you remember,” suggested Angela. “He
might have borrowed one from Brinky, or pinched it when he wasn’t
looking. And to be accurate, we must remember that the first time we
were overheard, when we were talking in my room, the listener had
disappeared before you got into the passage, and the next room to
ours is Edward’s.”
“And besides, we know now that it wasn’t Brinkman, this time at
any rate. Because he was away at the funeral. Whereas Pulteney
shirked the funeral on an obviously false ground; didn’t go to the
funeral and didn’t go fishing either. Assuming that the listener is the
same all through, it looks bad for Pulteney.”
A knock at the door suddenly interrupted their interview. “May I
come in?” said a gentle voice, and following it, flushed as with hot
walking yet still beaming with its habitual benevolence, came the
face of Mr. Pulteney.
“Ah, Mr. Bredon, they told me I would find you in here. I wanted a
word with you. Could we go outside, or”——
“Nonsense, Mr. Pulteney,” said Angela firmly. “What Mr. Eames
and I don’t know isn’t worth knowing. Come in and tell us all about
it.”
“Well, you know, I’m afraid I’ve got to make a kind of confession.
It’s a very humiliating confession for me to make, because I’m afraid,
once again, I’ve been guilty of curiosity. I simply cannot mind my own
business.”
“And what have you been up to now?” asked Angela.
“Why, when I said I was going out fishing this afternoon, I’m
afraid I was guilty of a prevarication. Indeed, when I announced my
intention of going to the funeral, I was beginning to weave the
tangled web of those who first practise to deceive. You see, I didn’t
want Brinkman to know.”
“To know what?”
“Well, that I was rather suspicious about his movements. You
see, I’ve asked him several times when he means to leave
Chilthorpe, and he always talks as if he was quite uncertain of his
plans. He did so at breakfast, you remember. But this morning, when
I went up to get a sponge I had left in the bathroom, I saw Brinkman
packing.”
“Packing?”
“Well, he was wandering about the room clearing up his papers,
and there was a despatch-box open on the table, and a suitcase on
the floor. And, as I knew he was due to be at the funeral, I thought
this was rather a funny time for him to want to leave. Especially as
he’d given no notice to Mrs. Davis. So I wondered whether, perhaps,
there was anything behind it.”
“You did well to wonder,” said Bredon. “So what did you do?”
“Well it stuck in my head that Mottram, when he came down here,
came in a motor-car. Mrs. Davis, though her trade announcement
advertises good accommodation for man and beast, does not run to
a garage. There is only one in Chilthorpe; you can just see it down
the road there. Now, thought I, if by any chance Mr. Brinkman is
meditating a precipitate disappearance, it would be like his caution to
have made all arrangements beforehand. And if I went down to the
garage and had a look at the car, it might be that I, though heaven
knows I am no motorist, should be able to see whether he had got
the car in proper trim for a journey.”
“You must have talked very nicely to the garage people,”
suggested Angela. “It would never do if you were suspected of being
a motor-thief.”
“Well, I had to do my best. I changed my mind about going to the
funeral, and made the excuse that I wanted to go fishing. I heard you
gasp, Mr. Eames; but Brinkman knows nothing about fishing. Then,
when you had started, I went off to the garage by myself.
Fortunately, very fortunately for my purpose, it proved that there was
nobody in. There are only two men, in any case, and they neglect
their business a good deal. I had an excuse if one was needed, but
when I found myself alone in the garage I flung caution to the winds.
There was a cardcase inside which shewed me which was Mottram’s
car. My investigations led me to the conclusion that the car was in
readiness for an immediate and secret departure for some
considerable journey.”
“Do tell us what they were,” said Angela demurely. “Just for the
interest of the thing.”
“Well, I removed with some difficulty a kind of cap from that thing
behind, which put me in a position to examine the interior of what is,
I suspect, called the petrol-tank. The careful insertion of a pencil
shewed that the tank was quite full; which suggested that a refill had
been obtained since they arrived.”
“They might have run short on the journey down, a mile or two
out,” suggested Angela. “But this was not all?”
“No, there was a map lying on the driver’s seat, somewhat
carelessly folded up. I thought it a point of interest that this map did
not include Pullford, and seemed to contemplate an expedition to the
west or southwest.”
“There’s not a great deal in that,” said Bredon. “Still, it’s
suggestive. Anything else?”
“Well, you know, I lifted up one of the seats, and found there a
collection of sandwiches and a large flask of whisky.”
“The devil you did! But they might have been for the journey
down here. Did you taste the sandwiches to see if they were fresh?”
“I took that liberty. They seemed to me, I must say, a trifle on the
stale side. But who was I to complain? I was, as it were, a guest.
Meanwhile, let me point out to you the improbability of Mottram’s
loading up his car with sandwiches for a twenty-mile drive.”
“That’s true. Were they properly cut? Professional work, I mean?”
“I suspected the hand of the artist. Mrs. Davis, no doubt. The
whisky I did not feel at liberty to broach. But the idea suggested itself
to me that these were the preparations of a man who is
contemplating a considerable journey, and probably one which will
not allow him time to take his meals at a public-house.”
“And why a secret departure?”
“Why, somebody had induced a coat of black paint over what I
take to be the number-plate of the car. I am a mere novice in such
matters, but is that usual?”
“It is not frequently done. And was the paint still wet?”
“That is a curious point. The paint was dry. I supposed then, that
Brinkman’s preparations for departure were not made yesterday or
the day before.”
“It’s awfully kind of you to take all this trouble, and to come and
tell us.”
“Not at all. I thought perhaps it might be worth mentioning, in
case you thought it best, well, to lay hands somehow on Brinkman.”
“Why, Mr. Pulteney,” said Angela, bubbling over, “we were just
preparing to lay hands on you!”
Chapter XVIII.
The Barmaid Is Brought to Book
The bewilderment registered by Mr. Pulteney’s face at this
extraordinary announcement rapidly gave way to a look of intense
gratification. “At last,” he said, “I have lived! To be mistaken for a
criminal, perhaps a murderer—it is my nunc dimittis. All these years I
have lived the blameless life of one who is continually called upon to
edify his juniors; I have risen early in order to convict my pupils of the
sin of being late; I have eaten sparingly in order to pretend that the
food provided by our establishment is satisfying when it is not; I have
pretended to sentiments of patriotism, of rugged sportsmanship, of
moral approval or indignation, which I did not feel. There is little to
choose, believe me, between the fakir and the schoolmaster; either
must spend days of wearisome mortification, because that is the way
in which he gets his living. And now, for one crowded hour of
glorious old age, I have been mistaken for a guilty intriguer. The
blood flows richer in my veins; I am overcome with gratitude. If only I
could have kept it up!”
“Mr. Eames,” said Angela, “there’s one thing you said which
you’ve got to take back. You said Mr. Pulteney was too much a man
of reflection to be a man of action as well. And now you’ve heard
how he broke into a garage, stole a piece of sandwich, and took the
cap off a petrol-tank without being in the least certain that the car
wouldn’t explode. Is this the pale scholar you pictured to us?”
“I apologize,” said Eames. “I apologize to Mr. Pulteney
unreservedly. I will form no more judgments of character. You may
tell me that Mrs. Davis is a murderess, if you will, and I will discuss
the proposition on its merits.”
“Talking of which,” said Angela, “the cream of the situation is that
we still don’t know who it was that was rubbering behind that beastly
mill-house.”
“Oh, as to that,” said Eames diffidently, “I’ve felt fairly certain
about that all along. I suppose it’s the result of living with priests that
one becomes thus worldly wise. But didn’t you know, Mr. Bredon,
that maids always steal their masters’ cigarettes? It is, I believe, a
more or less recognized form of perquisite. Every liberty taken by the
rich is aped by their domestics. And, although she is not in
household service, I have no doubt that the barmaid here claims a
like privilege.”
“Do you mean”—— began Bredon:
“You noticed, surely, that her fingers are a little stained with
brown? I noticed it when she brought in my fried eggs. Ladies
generally have expensive tastes in cigarettes, and I have no doubt
that this maid would go for the Callipoli if she got a chance.”
“Miles, dear,” said Angela softly, “who was it said that it must be a
servant who was listening at our bedroom door?”
“The uneducated do not take Mr. Pulteney’s view about curiosity.
I daresay this young lady often listens at keyholes. With a corpse in
the house, and detectives about, she listens with all the more avidity.
And if the detectives insist on exchanging confidences close to that
precise point in the shrubbery at which she is in the habit of smoking
purloined cigarettes, they put themselves in her hands. But a
stronger motive supervenes; what she overhears out of pure
curiosity turns out to be of vital importance to herself. She learns that
the young man she is walking out with is suspected of murder.”
“Good Lord, and of course it was she who reacted on our
suggestions, not Brinkman! I don’t know if I mentioned it to you,
Angela, but when Leyland and I were talking together at the mill-
house, he said the only thing that would make him hesitate to arrest
Simmonds would be evidence shewing that Simmonds knew he
wasn’t Mottram’s heir. And it was exactly that evidence which
‘Raight-ho’ proceeded to produce.”
“Oh,” cried Angela, “How perfectly odious! You mean that when I
thought I was pumping Emmeline so cleverly, and getting out of her
exactly what I wanted, she was really doing it all on purpose, and
telling me exactly what she wanted?”
“I’m afraid so, my dear. A lot of reputations seem to be going
west to-day. And, of course, I should say it’s odds that her whole
story was absolutely trumped up, invented to suit the occasion. And
we’re back exactly where we were, not knowing whether Simmonds
knew he was cut out of the will or not.”
“On the other hand,” said Angela, “we do know, now, what put the
wind up young Simmonds so badly. When you and Leyland passed
him and Emmeline in the lane last night, she was telling him that he
was suspected of murder, and had better be dashed careful what he
said and who he said it to. Naturally it gave him a bit of a fright when
he thought you were going to pump him about his uncle.”
“And meanwhile, what has Brinkman been up to? We’ve really no
evidence against him until all this about the car cropped up. Dash it
all, and just when I was going to get a game of patience!”
“I don’t want to put my oar in unduly,” said the old gentleman in
an apologetic tone, “but might it not be a good thing to acquaint Mr.
Leyland with the somewhat unusual state of affairs down at the
garage? If Brinkman really intends to do what is popularly known as
a ‘bunk,’ he may be off at any moment. Had I been more expert, I
could no doubt have immobilized some important part of the
mechanism. As it was, I was helpless.”
“Where is Leyland, by the way?” asked Bredon.
“He is just coming up the street now,” said Eames, looking out of
the window. “I’ll call to him to come in here.”
“Hullo, what have you been up to?” asked Bredon, as Leyland
entered.
“Why, to tell the truth, I have been shadowing Mr. Pulteney. I must
apologize, Mr. Pulteney, but I felt bound to be careful. I’ve had you
kept under close observation all this week; and it was only as I stood
behind the door, watching your investigations into that car, that I
became perfectly convinced of your innocence.”
“What! more suspicion! This is indeed a day! Why, if I had had
the least conception that you were watching me, Mr. Leyland, I would
have led you a rare dance! My movements, I promise you, should
have been full of mystery. I should have gone out every night with a
scowl and a dark lantern. I am overwhelmed.”
“Well, I must apologize at least for spying upon your detective
work. You do very well for an amateur, Mr. Pulteney, but you are not
suspicious enough.”
“Indeed! I overlooked something? How mortifying!”
“Yes, when you took the cushion off that front seat, you failed to
observe that there was a neat tear in it, which had been quite
recently sewn up. Otherwise I am sure that you would have done
what I did just now—cut it open.”
“And is it fair to ask what you found inside?”
“Well, we seem to have gone too far now to have any secrets
between us. I feel sure that both you, Mr. Pulteney, and you, Mr.
Eames, are anxious to see justice done, and are prepared to help at
least by your silence.”
“To be sure,” said Pulteney.
“I am at your service,” said Eames.
“Well, this is actually what I found.” With a dramatic gesture he
produced a small waterproof wallet, and turned out its contents. “You
will find a thousand pounds there, all in Bank of England notes.”
“Well,” said Bredon, when the exclamations of surprise had died
away, “are you still suspecting young Simmonds?”
“I’m not easy about him yet in my own mind. But of course I see
Brinkman’s deeper in this business than I had suspected so far. A
man who’s innocent doesn’t prepare to do a bolt with a thousand
pounds and a motor-car that doesn’t belong to him.”
“Well,” said Bredon, “I suppose we ought to be keeping an eye on
Mr. Brinkman.”
“My dear old thing,” said Leyland, “don’t you realize that I’ve had
two of my men at the Swan all this week, and that Brinkman hasn’t
been unaccounted for for one moment? The trouble is, he knows
he’s being watched, so he won’t give himself away. At least I’m pretty
sure of it. But the motor, of course, puts us in a very good position.
We know how he means to escape, and we can afford to take the
watch off him and put it on the motor instead. Then he’ll shew his
hand, because he’s mad keen to be off. At present he’s in his room,
smoking a cigarette and reading an old novel. He won’t move, I
think, until he makes certain that we’re all out of the way. Probably
not till after supper, because a night ride will suit his purpose best.
And he’s got a night for it too; there’s a big storm coming on, unless
I’m mistaken.”
“And what about Simmonds?” asked Bredon.
“And the barmaid?” added Angela.
“Well, of course I could question both or either of them. But I’d
sooner not, if I can help it; it’s cruel work, I was wondering if you,
Mrs. Bredon, could go and have a talk to that maid after we’ve had
our tea, and see what satisfaction you can get out of her?”
“I don’t mind at all. In fact, I rather want to have it out with dear
Emmeline. I owe her one, you see. Meanwhile, let’s have tea by all
means. I wonder if Brinky will come down to it?”
Brinkman did come down, and tea was not a very enlivening
meal. Everybody in the room looked upon him as a man who was
probably a murderer and certainly a thief. Consequently everybody
tried to be nice to him, and everybody’s style was cramped by the
effort. Even Mr. Pulteney’s verbosity seemed to have been dried up
by the embarrassment of the situation. On the whole, Eames carried
it off best. His dry, melancholy manner was quite unaltered; he talked
about patience to Bredon, he talked Pullford gossip to Brinkman; he
tried to draw out Pulteney on educational questions. But most of the
party were glad when it was over, when Brinkman had shut himself
up again, and Angela had betaken herself to the back premises to
have it out with the barmaid.
The “best room” had been turned by common consent into a sort
of committee room; during all this whirligig of sensations, the
background of their mind was filled with those protuberant portraits
of the late Mr. Davis which so defiantly occupied the walls. It was
here that Angela found them assembled when she came up, some
half an hour later, a little red about the eyes.
“Well, I didn’t try any subterfuges this time; I let her have it
straight from the shoulder. And then she cried, and I cried, and we
both cried together a good bit.”
“The mysterious sex again,” said Mr. Pulteney.
“Oh, you wouldn’t understand, of course. Anyhow, she’s had a
rotten time. That first evening, when she listened outside the door, it
was only for a moment or two, out of sheer curiosity, and she didn’t
hear anything that interested her. It was yesterday evening, when
you two were talking, that she got interested. She overheard at first
merely by accident, which just shews how careful you ought to be.
She caught the name ‘Simmonds’; she heard, for the first time, about
the Euthanasia policy, and what it might have meant to him and to
her. She went on listening, naturally, and so she came in for all Mr.
Leyland’s exposition of the case against Simmonds. You didn’t
convince my husband, Mr. Leyland, but you had a much greater
success on the other side of the wall. The poor girl, who’s been
brought up on novelettes and penny-shockers all her life, drank in
the whole story. She really believed that the man who had been
making love to her, the man she was in love with, was a cold-
blooded murderer. She acted I think, very well. He came round that
evening to take her out for an evening walk, and on the way she
taxed him with his supposed crime. If you come to think of it, that
was sporting of her.”
“It was,” said Leyland. “People are found dead in ditches for less
than that.”
“Well, anyhow, it worked all right. Simmonds listened to her
charges, and then denied them all. He didn’t give her any evidence
for his denial, but she believed him. There was no quarrel. Next day,
that is to say this morning, Emmeline heard you two arranging for a
talk at the mill-house. She didn’t suspect the trap; she walked
straight into it. What she heard made her believe that there was only
one way to save Simmonds—to pretend that he knew about the
Euthanasia, and knew the money wasn’t coming to him. The poor
girl reflected that Simmonds had been hanging round the house on
the night of Mottram’s death; he had been there waiting to see her
when she left the bar at closing time. So, bravely again, I think, she
came to me with her story about the anonymous friend and her
young man with his lost legacy. Of course, by sheer accident, I made
it much easier for her to pitch me this yarn, and I swallowed it whole.
She thought that, with some blackening of her own conscience, she
had saved an innocent man’s life.”
“And that’s all she knows, so far?”
“No, at the end of lunch she heard you, Miles, saying that you’d
give me half an hour to talk things over. So when she saw us
stealing down to the now familiar trysting-place by the mill—she
hadn’t gone to the funeral—she followed us and listened again. And,
to her horror, she realized from what you said that all her lying had
failed to do its work. Leyland still believed, believed more than ever,
that her young man was the criminal. Her anxiety put her off her
guard, and a sudden sneeze gave her away. She didn’t dare go back
to the house; she hid in the privet-hedge.”
“And the long and short of it is,” suggested Leyland, “that her
story is no evidence at all. Simmonds may be as guilty or as
innocent as you like; she knew nothing about it. Can she give any
account of Simmonds’s movements on the night of the murder?”
“Well, she says she had to be in the bar up to closing time, and
then she slipped round to the back door, where he was waiting for
her, and stood there talking to him.”
“For how long?”
“She says it might have been a quarter of an hour, or it might
have been three quarters of an hour; she really couldn’t say.”
“That sounds pretty thin.”
“How impossible you bachelors are! Miles, can’t you explain to
him? Oh, well, I suppose it’s no use; you couldn’t possibly
understand.”
“It’s certainly rather an unfortunate circumstance for Simmonds
that, just at the moment the gas was turned on in Mottram’s room, he
was indulging in a kind of ecstasy which may have lasted a quarter
of an hour, or may have lasted three quarters.”
“Meanwhile,” said Bredon, “I hope you realize that your own case
against Simmonds is considerably weakened? You were trying to
make out, if you remember, that Simmonds murdered Mottram and
burned the will, knowing that the will cut him out of his inheritance.
But since we have learned to discredit the testimony of ‘Raight-ho,’
we have no evidence that Simmonds ever knew anything about the
will, or had ever so much as heard of the Euthanasia policy.”
“That’s true. And it’s also true that these last discoveries have
made me more inclined to suspect Brinkman. I shall have to keep my
eye on Simmonds, but for the time being Brinkman is the quarry we
must hunt. It’s Brinkman’s confession I look forward to for the
prospect of those forty pounds.”
“Well, if you can catch Brinkman and make him confess, you’re
welcome to them. Or even if Brinkman does himself in somehow,
commits suicide rather than face the question, I’ll give you the
benefit of the doubt, and we’ll treat it as murder. Meanwhile, if you
will excuse me, I think I’ve just time to lay out that patience before
supper.”
“Oh, he’s hopeless,” said Angela.
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

You might also like