100% found this document useful (2 votes)
60 views

Download Complete Adaptive Code via C Agile coding with design patterns and SOLID principles 1st Edition Gary Mclean Hall PDF for All Chapters

Adaptive

Uploaded by

velsonbojmaa
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
100% found this document useful (2 votes)
60 views

Download Complete Adaptive Code via C Agile coding with design patterns and SOLID principles 1st Edition Gary Mclean Hall PDF for All Chapters

Adaptive

Uploaded by

velsonbojmaa
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/ 45

Download the full version of the ebook at

https://ebookgate.com

Adaptive Code via C Agile coding with design


patterns and SOLID principles 1st Edition
Gary Mclean Hall

https://ebookgate.com/product/adaptive-code-via-c-
agile-coding-with-design-patterns-and-solid-
principles-1st-edition-gary-mclean-hall/

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


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

Agile software development principles patterns and


practices Martin

https://ebookgate.com/product/agile-software-development-principles-
patterns-and-practices-martin/

ebookgate.com

Agile Software Development Principles Patterns and


Practices Robert Martin

https://ebookgate.com/product/agile-software-development-principles-
patterns-and-practices-robert-martin/

ebookgate.com

C Class Design Handbook Coding Effective Classes 1st


Edition Richard Conway

https://ebookgate.com/product/c-class-design-handbook-coding-
effective-classes-1st-edition-richard-conway/

ebookgate.com

The Project Manager s Guide to Mastering Agile Principles


and Practices for an Adaptive Approach 1st Edition Charles
G. Cobb
https://ebookgate.com/product/the-project-manager-s-guide-to-
mastering-agile-principles-and-practices-for-an-adaptive-approach-1st-
edition-charles-g-cobb/
ebookgate.com
C Design Patterns and Derivatives Pricing 2nd Edition M.
S. Joshi

https://ebookgate.com/product/c-design-patterns-and-derivatives-
pricing-2nd-edition-m-s-joshi/

ebookgate.com

Where Code and Content Meet Design Patterns for Web


Content Management and Delivery Personalisation and User
Participation Wiley Software Patterns Series 1st Edition
Andreas Rueping
https://ebookgate.com/product/where-code-and-content-meet-design-
patterns-for-web-content-management-and-delivery-personalisation-and-
user-participation-wiley-software-patterns-series-1st-edition-andreas-
rueping/
ebookgate.com

Pro Objective C Design Patterns for IOS 1st Edition Carlo


Chung

https://ebookgate.com/product/pro-objective-c-design-patterns-for-
ios-1st-edition-carlo-chung/

ebookgate.com

CLR via C Third Edition Jeffrey Richter

https://ebookgate.com/product/clr-via-c-third-edition-jeffrey-richter/

ebookgate.com

Mobile Design Patterns Nudelman

https://ebookgate.com/product/mobile-design-patterns-nudelman/

ebookgate.com
From the Library of Ida Schander
Adaptive Code via C#:
Agile coding with
design patterns and
SOLID principles

Gary McLean Hall

From the Library of Ida Schander


PUBLISHED BY
Microsoft Press
A division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2014 by Gary McLean Hall. All rights reserved.
No part of the contents of this book may be reproduced or transmitted in any form or by any means without
the written permission of the publisher.
Library of Congress Control Number: 2014943458
ISBN: 978-0-7356-8320-4

Printed and bound in the United States of America.

First Printing

Microsoft Press books are available through booksellers and distributors worldwide. If you need support related
to this book, email Microsoft Press Book Support at [email protected]. Please tell us what you think of
this book at http://aka.ms/tellpress.

This book is provided “as-is” and expresses the author’s views and opinions. The views, opinions and information
expressed in this book, including URL and other Internet website references, may change without notice.

Some examples depicted herein are provided for illustration only and are fictitious. No real association or
connection is intended or should be inferred.

Microsoft and the trademarks listed at http://www.microsoft.com on the “Trademarks” webpage are trademarks
of the Microsoft group of companies. All other marks are property of their respective owners.

Acquisitions Editor: Devon Musgrave


Developmental Editor: Devon Musgrave
Project Editor: Devon Musgrave
Editorial Production: Online Training Solutions, Inc. (OTSI)
Technical Reviewer: Jeremy Johnson
Copyeditor: Kathy Krause (OTSI)
Indexer: Krista Wall (OTSI)
Cover: Twist Creative • Seattle and Joel Panchot

From the Library of Ida Schander


For Amelia Rose
—Gary McLean Hall

From the Library of Ida Schander


This page intentionally left blank

From the Library of Ida Schander


Contents at a glance

Introduction xv

PART I AN AGILE FOUNDATION

CHAPTER 1 Introduction to Scrum 3


CHAPTER 2 Dependencies and layering 43
CHAPTER 3 Interfaces and design patterns 93
CHAPTER 4 Unit testing and refactoring 125

PART II WRITING SOLID CODE

CHAPTER 5 The single responsibility principle 169


CHAPTER 6 The open/closed principle 207
CHAPTER 7 The Liskov substitution principle 217
CHAPTER 8 Interface segregation 251
CHAPTER 9 Dependency injection 281

PART III ADAPTIVE SAMPLE

CHAPTER 10 Adaptive sample: Introduction 325


CHAPTER 11 Adaptive sample: Sprint 1 337
CHAPTER 12 Adaptive sample: Sprint 2 365

Appendix A: Adaptive tools 379


Appendix B: GitHub code samples online

Index 387

About the author 403

From the Library of Ida Schander


This page intentionally left blank

From the Library of Ida Schander


Contents

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

PART I AN AGILE FOUNDATION

Chapter 1 Introduction to Scrum 3


Scrum versus waterfall. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Roles and responsibilities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7


Product owner. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Scrum master. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Development team. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Pigs and chickens. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Artifacts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
The Scrum board. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Charts and metrics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Backlogs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

The sprint. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Release planning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Sprint planning. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Daily Scrum. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Sprint demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Sprint retrospective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Scrum calendar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Problems with Scrum and Agile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37


Maladaptive code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

What do you think of this book? We want to hear from you!


Microsoft is interested in hearing your feedback so we can continually improve our
books and learning resources for you. To participate in a brief online survey, please visit:

microsoft.com/learning/booksurvey

vii

From the Library of Ida Schander


Chapter 2 Dependencies and layering 43
The definition of dependency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
A simple example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Modeling dependencies in a directed graph. . . . . . . . . . . . . . . . . . . . . . 51

Managing dependencies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Implementations versus interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
The new code smell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Alternatives to object construction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
The Entourage anti-pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
The Stairway pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Resolving dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Dependency management with NuGet. . . . . . . . . . . . . . . . . . . . . . . . . . 77

Layering. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Common patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Cross-cutting concerns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Asymmetric layering. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Chapter 3 Interfaces and design patterns 93


What is an interface? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Explicit implementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Adaptive design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102


The Null Object pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
The Adapter pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The Strategy pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

Further versatility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113


Duck-typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Mixins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Fluent interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

viii Contents

From the Library of Ida Schander


Chapter 4 Unit testing and refactoring 125
Unit testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Arrange, Act, Assert. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Test-driven development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
More complex tests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Refactoring. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Changing existing code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
A new account type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

PART II WRITING SOLID CODE

Chapter 5 The single responsibility principle 169


Problem statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Refactoring for clarity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Refactoring for abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

SRP and the Decorator pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184


The Composite pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Predicate decorators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Branching decorators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Lazy decorators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Logging decorators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Profiling decorators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Asynchronous decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Decorating properties and events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Using the Strategy pattern instead of switch. . . . . . . . . . . . . . . . . . . . . . . . 204

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206

Contents ix

From the Library of Ida Schander


Chapter 6 The open/closed principle 207
Introduction to the open/closed principle. . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
The Meyer definition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
The Martin definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Bug fixes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Client awareness. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

Extension points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209


Code without extension points. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Virtual methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Abstract methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Interface inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
“Design for inheritance or prohibit it”. . . . . . . . . . . . . . . . . . . . . . . . . . 212

Protected variation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


Predicted variation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
A stable interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Just enough adaptability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Chapter 7 The Liskov substitution principle 217


Introduction to the Liskov substitution principle. . . . . . . . . . . . . . . . . . . . . . 217
Formal definition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
LSP rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218

Contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Preconditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Postconditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Data invariants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Liskov contract rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Code contracts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

Covariance and contravariance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239


Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Liskov type system rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

x Contents

From the Library of Ida Schander


Chapter 8 Interface segregation 251
A segregation example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
A simple CRUD interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Multiple interface decoration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261

Client construction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263


Multiple implementations, multiple instances. . . . . . . . . . . . . . . . . . . 263
Single implementation, single instance. . . . . . . . . . . . . . . . . . . . . . . . . 266
The Interface Soup anti-pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

Splitting interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268


Client need. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Architectural need. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Single-method interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280

Chapter 9 Dependency injection 281


Humble beginnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
The Task List application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Constructing the object graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Inversion of Control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Beyond simple injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
The Service Locator anti-pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Illegitimate Injection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
The composition root. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Convention over configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317

Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

Contents xi

From the Library of Ida Schander


PART III ADAPTIVE SAMPLE

Chapter 10 Adaptive sample: Introduction 325


Trey Research. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
The team. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
The product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328

Initial backlog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328


Finding stories in prose. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Story point estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335

Chapter 11 Adaptive sample: Sprint 1 337


Planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

“I want to create rooms for categorizing conversations.”. . . . . . . . . . . . . . . 340


The controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
The room repository. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

“I want to view a list of rooms that represent conversations.”. . . . . . . . . . . 349

“I want to view the messages that have been sent to a room.“ . . . . . . . . . 353

“I want to send plain text messages to other room members.”. . . . . . . . . 356

Sprint demo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357


First demonstration of Proseware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

Sprint retrospective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358


What went well?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
What went badly?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Things to change?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Things to keep? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Surprises?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

xii Contents

From the Library of Ida Schander


Chapter 12 Adaptive sample: Sprint 2 365
Planning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

“I want to send markdown that will be correctly formatted.”. . . . . . . . . . . 367

“I want to filter message content so that it is appropriate.”. . . . . . . . . . . . . 370

“I want to serve hundreds of users concurrently.”. . . . . . . . . . . . . . . . . . . . . 373

Sprint demo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

Sprint retrospective. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376


What went well?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
What went badly?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Things to change?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Things to keep? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Surprises?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378

Appendix A: Adaptive Tools 379


Appendix B: GitHub code samples online

Index 387

About the author 403

What do you think of this book? We want to hear from you!


Microsoft is interested in hearing your feedback so we can continually improve our
books and learning resources for you. To participate in a brief online survey, please visit:

microsoft.com/learning/booksurvey

Contents xiii

From the Library of Ida Schander


This page intentionally left blank

From the Library of Ida Schander


Introduction

T he first words of the title of this book, Adaptive Code, provide a good description
of the outcome of applying the principles in the book: the ability of code to adapt
to any new requirement or unforeseen scenario while avoiding significant rework. The
aim of this book is to aggregate into one volume many of the current best practices in
the world of C# programming with the Microsoft .NET Framework. Although some of
the content is covered in other books, those books either focus heavily on theory or are
not specific to .NET development.

Programming can be a slow process. If your code is adaptive, you will be able to
make changes to it more quickly, more easily, and with fewer errors than you would
if you were working with a codebase that impedes changes. Requirements, as every
developer knows, are subject to change. How change is managed is a key differen­
tiating factor between successful software projects and those that atrophy due to scope
creep. Developers can react in many ways to requirement changes, with two opposing
viewpoints highlighting the continuum that lies between.

First, developers can choose a rigid viewpoint. In this approach, from the develop-
ment process down to class design, the project is as inflexible as if it were implemented
50 years ago by using punch cards. Waterfall methodologies are conspicuous culprits
in ensuring that software cannot change freely. Their determination that the phases of
analysis, design, implementation, and testing be distinct and one-way make it difficult—
or at least expensive—for customers to change requirements after implementation has
begun. The code, then, does not need to be built for change: the process all but forbids
alterations.

The second approach, Agile methodology, is not just an alternative to such rigid
methodologies, but a reaction to them. The aim of Agile processes is to embrace change
as a necessary part of the contract between client and developer. If customers want to
change something in the product that they are paying for, the temporal and financial
cost should be correlated to the size of the change, not the phase of the process that is
currently in progress. Unlike physical engineering, software engineering works with a
malleable tool: source code. The bricks and mortar that form a house are literally fused
together as construction progresses. The expense involved in changing the design of
a house is necessarily linked to the completion of the building phase. If the project
has not been started—if it is still just in blueprints—change is relatively cheap. If the
windows are in, the electricity wired up, and the plumbing fitted, moving the upstairs
bathroom down next to the kitchen could be prohibitively expensive. With code, mov-
ing features around and reworking the navigation of a user interface should not be as

xv

From the Library of Ida Schander


significant. Unfortunately, this is not always the case. The temporal cost alone often
prohibits such changes. This, I find, is largely a result of a lack of adaptability in code.

This book demonstrates the second approach and explains, with real-world exam-
ples, the practicalities of implementing adaptive code.

Who should read this book


This book is intended to bridge a gap between theory and practice. The reader for
whom this book is written is an experienced programmer who seeks more practical
examples of design patterns, SOLID principles, unit testing and refactoring, and more.

Capable intermediate programmers who want to plug the gaps in their knowledge
or have doubts and questions about how some of the industry’s best practices fit
together will benefit most from this book, especially because the day-to-day reality
of programming rarely matches simple examples or theory. Much of SOLID is now
understood, but the intricacies of the open/closed principle (covered in Chapter 6)
and Liskov substitution (covered in Chapter 7) are not fully comprehended. Even
experienced programmers sometimes do not fully realize the benefits provided by
dependency injection (covered in Chapter 9). Similarly, the flexibility—adaptability—
that interfaces (covered in Chapter 3) lend to code is often overlooked.

This book can also help the more junior developer learn, from the ground up, which
aspects of common patterns and practices are benevolent and which are, in the long
term, malevolent. The code samples that I see from prospective employees have a lot
in common. The general theme is that the candidate is almost there with respect to
many skills but just needs a slight push in the right direction to become a significantly
better programmer. Specifically, the Entourage anti-pattern (covered in Chapter 2) and
the Service Locator anti-pattern (covered in Chapter 9) are very prevalent in sample
code. Practical alternatives, and their rationales, are provided in this book.

Assumptions
Ideally, you should have some practical experience of programming in a language that
is syntactically similar to C#, such as Java or C++. You should also have a strong founda-
tion in core procedural programming concepts such as conditional branching, loops,
and expressions. You should also have some experience of object-oriented program-
ming using classes, and at least a passing familiarity with interfaces.

xvi Introduction

From the Library of Ida Schander


This book might not be for you if…
This book might not be for you if you are just starting out on a journey to learn how to
program. This book covers advanced topics that assume a thorough understanding of
fundamental programming concepts.

Organization of this book


This book is made up of three parts, each of which builds on the last. That said, the
book can also be read out of order. Each chapter covers a self-contained subject in
detail, with cross references included where appropriate.

Part I: An Agile foundation


This part lays the foundation for building software in an adaptive way. It covers the
high-level Agile process known as Scrum, which requires code to be adaptive to change.
The chapters in this part focus on details around interfaces, design patterns, refactoring,
and unit testing.

■■ Chapter 1: Introduction to Scrum This chapter sets the scene for the book
by introducing Scrum, which is an Agile project management methodology. The
chapter gives an in-depth overview of the artifacts, roles, metrics, and phases
of a Scrum project. Finally, it shows how developers should organize themselves
and their code when operating in an Agile environment.

■■ Chapter 2: Dependencies and layering This chapter explores dependencies


and architectural layering. Code can only be adaptive if the solution’s structure
allows it to be. The different types of dependencies are described: first-party,
third-party, and framework. The chapter describes how to manage and organize
dependencies, from anti-patterns (which should be avoided) to patterns (which
should be embraced). It also introduces advanced topics such as aspect-oriented
programming and asymmetric layering, providing further depth.

■■ Chapter 3: Interfaces and design patterns Interfaces are, by now, ubiquitous


in modern .NET development. However, they are often misapplied, misunder-
stood, and misappropriated. This chapter shows some of the more common and
practically useful design patterns, exploring how versatile an interface can be.
Leading the reader beyond the simple extraction of an interface, the chapter

Introduction xvii

From the Library of Ida Schander


shows how interfaces can be elaborated in many different ways to solve a
problem. Mixins, duck-typing, and interface fluency further underscore the
versatility of this key weapon in the programmer’s arsenal.

■■ Chapter 4: Unit testing and refactoring Two practices that are becoming
prerequisite skills are unit testing and refactoring. The two are closely related
and work in unison to produce adaptive code. Without the safety net of unit
tests, refactoring is prone to error; without refactoring, code becomes unwieldy,
rigid, and hard to comprehend. This chapter takes an example of unit testing
from humble beginnings and expands it to use more advanced—but practical
—patterns and practices such as fluent assertions, test-driven development,
and mocking. For refactoring, the chapter provides examples of real-world
refactors that improve the readability and maintainability of the source code.

Part II: Writing SOLID code


This part builds on the foundation laid in Part I. Each chapter is devoted to examining
one principle of SOLID. The emphasis in these chapters is on practical examples for
implementing the principles, rather than solely on the theory of why. By placing each
example in a real-world context, the chapters in this part of the book clearly demon-
strate the utility of SOLID.

■■ Chapter 5: The single responsibility principle This chapter shows how to


implement the single responsibility principle in practice by using the Decorator
and Adapter patterns. The outcome of applying the principle is an increase in
the number of classes and a decrease in the size of those classes. The chapter
shows that, in contrast with monolithic classes that provide extensive features,
these smaller classes are more directed and focused on solving only a small part
of a larger problem. It is in their aggregation that these classes then become
more than the sum of their parts.

■■ Chapter 6: The open/closed principle The open/closed principle (OCP) is


simply stated, but it can have a significant impact on code. It is responsible for
ensuring that code that follows SOLID principles is only appended to and never
edited. This chapter also discusses the concept of predicted variation in relation
to OCP and explores how it can help developers identify extension points for
further adaptability.

■■ Chapter 7: The Liskov substitution principle This chapter shows the posi-
tive effects that result from applying the Liskov substitution principle on code,
particularly the fact that the guidelines help enforce the open/closed principle
and prevent the unintended consequences of change. Contracts—through

xviii Introduction

From the Library of Ida Schander


preconditions, postconditions, and data invariants—are covered by using the
Code Contracts tooling. The chapter also describes subtyping guidelines such
as covariance, contravariance, and invariance, along with the negative impact
of breaking these rules.

■■ Chapter 8: Interface segregation Not only should classes be smaller than


they commonly are, this chapter shows that interfaces are, similarly, often too
big. Interface segregation is a simple practice that is often overlooked; this
chapter shows the benefits of limiting interfaces to the smallest size possible,
along with the benefits of working with smaller interfaces. It also explores the
different reasons that might motivate the segregation of interfaces, such as
­client need and architectural need.

■■ Chapter 9: Dependency injection This chapter contains the cohesive glue


that holds together the rest of the features in the book. Without dependency
injection (DI), there is a lot that would not be possible—it is really that impor-
tant. This chapter contains an introduction to DI and a comparison of the differ-
ent methods of implementing it. The chapter includes discussions on managing
object lifetimes, working with Inversion of Control containers, avoiding common
anti-patterns relating to service location, and identifying composition roots and
resolution roots.

Part III: Adaptive sample


This part uses a sample application as a way of tying together the rest of the book.
Although there is a lot of code in these chapters, there is ample accompanying explana-
tion. Because this book is about working in an Agile environment, the chapters map to
Scrum sprints, and all work is the result of backlog items and client change requests.

■■ Chapter 10: Adaptive sample: Introduction This first chapter describes


the application that is to be developed: an online chat application developed
in ASP.NET MVC 5. A brief design is provided as a guideline for the planned
architecture, in addition to an explanation of the features on the backlog.

■■ Chapter 11: Adaptive sample: Sprint 1 Using a test-driven development


(TDD) approach, the first features of the application are developed, including
viewing and creating chat rooms and messages.

■■ Chapter 12: Adaptive sample: Sprint 2 The client, inevitably, makes some
changes to the requirements of the application, and the team accommodates
those changes through adaptive code.

Introduction xix

From the Library of Ida Schander


Another random document with
no related content on Scribd:
Thanks to Odin’s protection, Sigi soon won the glorious empire
of the Huns and became a powerful monarch. But when he had
attained extreme old age his fortune changed, Odin suddenly
forsook him, his wife’s kindred fell upon him, and after a short
encounter he was treacherously slain.
His death was soon avenged, however, for his son Rerir,
Rerir. returning from a journey, put all the murderers to
death and claimed the throne. But, in spite of all
outward prosperity, Rerir’s dearest wish, a son to succeed him,
remained unfulfilled for many a year. Finally, however, Frigga
decided to grant his constant prayer, and to vouchsafe the heir he
longed for. Her swift messenger Gna, or Liod, was dispatched to
carry him a miraculous apple, which she dropped into his lap as he
was sitting alone on the hillside. Glancing upward, Rerir recognized
the emissary of the goddess, and joyfully hastened home to partake
of the apple with his wife. The child thus born in answer to their
prayers was a handsome little lad called Volsung, who, losing both
parents in early infancy, became ruler of all the land.
Every year Volsung’s wealth and power increased, and, as he
Volsung. was the boldest leader, many brave warriors rallied
around him, and drank his mead sitting beneath the
Branstock, a mighty oak, which, rising in the middle of his dwelling,
pierced the roof and overshadowed the whole house.

“And as in all other matters ’twas all earthly houses’ crown,


And the least of its wall-hung shields was a battle-world’s renown,
So therein withal was a marvel and a glorious thing to see,
For amidst of its midmost hall-floor sprang up a mighty tree,
That reared its blessings roofward and wreathed the roof-tree dear
With the glory of the summer and the garland of the year.”

Volsung did not long remain childless, for ten stalwart sons and
one lovely daughter, Signy, came to brighten his home. As soon as
this maiden reached marriageable years, many suitors asked for her
hand, which was finally pledged to Siggeir, King of the Goths, whom,
however, she had never seen.
The wedding day came, and when the bride first beheld her
destined groom she shrank back in dismay, for his
The wedding
of Signy. puny form and lowering glances contrasted oddly with
her brothers’ strong frames and frank faces. But it was
too late to withdraw,—the family honor was at stake,—and Signy so
successfully concealed her dislike that none except her twin brother
Sigmund suspected how reluctantly she became Siggeir’s wife.
The wedding feast was held as usual, and when the
The sword in merrymakings had reached their height the guests
the Branstock. were startled by the sudden entrance of a tall, one-
eyed man, closely enveloped in a mantle of cloudy
blue. Without vouchsafing word or glance to any in the assembly, the
stranger strode up to the Branstock and thrust a glittering sword up
to the hilt in its great bole. Then, turning slowly around, he faced the
awe-struck assembly, and in the midst of the general silence
declared that the weapon would belong to the warrior who could pull
it out, and that it would assure him victory in every battle. These
words ended, he passed out and disappeared, leaving an intimate
conviction in the minds of all the guests that Odin, king of the gods,
had been in their midst.

“So sweet his speaking sounded, so wise his words did seem,
That moveless all men sat there, as in a happy dream
We stir not lest we waken; but there his speech had end,
And slowly down the hall-floor and outward did he wend;
And none would cast him a question or follow on his ways,
For they knew that the gift was Odin’s, a sword for the world to
praise.”

Volsung was the first to recover the power of speech, and,


waiving his own right to try to secure the divine weapon, he invited
Siggeir to make the first attempt to draw it out of the tree-trunk. The
bridegroom anxiously tugged and strained, but the sword remained
firmly embedded in the oak. He resumed his seat, with an air of
chagrin, and then Volsung also tried and failed. But the weapon was
evidently not intended for either of them, and the young Volsung
princes were next invited to try their strength.

“Sons I have gotten and cherished, now stand ye forth and try;
Lest Odin tell in God-home how from the way he strayed,
And how to the man he would not he gave away his blade.”

The nine eldest sons were equally unsuccessful; but when


Sigmund, the tenth and youngest, laid his firm young
Sigmund.
hand upon the hilt, it easily yielded to his touch, and
he triumphantly drew the sword out without making the least
exertion.

“At last by the side of the Branstock Sigmund the Volsung stood,
And with right hand wise in battle the precious sword-hilt caught,
Yet in a careless fashion, as he deemed it all for naught;
When, lo, from floor to rafter went up a shattering shout,
For aloft in the hand of Sigmund the naked blade showed out
As high o’er his head he shook it: for the sword had come away
From the grip of the heart of the Branstock, as though all loose it
lay.”

All present seemed overjoyed at his success; but Siggeir’s heart


was filled with envy, for he coveted the possession of the weapon,
which he now tried to purchase from his young brother-in-law.
Sigmund, however, refused to part with it at any price, declaring that
the weapon had evidently been intended for him only. This refusal so
offended Siggeir that he secretly resolved to bide his time, to
exterminate the proud race of the Volsungs, and thus secure the
divine sword.
Concealing his chagrin therefore, he turned to Volsung and
cordially invited him to visit his court a month later, bringing all his
sons and kinsmen with him. The invitation so spontaneously given
was immediately accepted, and although Signy, suspecting evil,
secretly sought her father while her husband slept, and implored him
to retract his promise and stay at home, he would not consent to
appear afraid.
A few weeks after the return of the bridal couple Volsung’s well-
Siggeir’s manned vessels came within sight of Siggeir’s shores,
treachery. and Signy perceiving them hastened down to the
beach to implore her kinsmen not to land, warning
them that her husband had treacherously planned an ambush,
whence they could never escape alive. But Volsung and his sons,
whom no peril could daunt, calmly bade her return to her husband’s
palace, and donning their arms they boldly set foot ashore.

THE BRANSTOCK.—Hoffmann.
“Then sweetly Volsung kissed her: ‘Woe am I for thy sake,
But Earth the word hath hearkened, that yet unborn I spake;
How I ne’er would turn me backward from the sword or fire of bale;—
—I have held that word till to-day, and to-day shall I change the tale?
And look on these thy brethren, how goodly and great are they,
Wouldst thou have the maidens mock them, when this pain hath
passed away
And they sit at the feast hereafter, that they feared the deadly
stroke?
Let us do our day’s work deftly for the praise and the glory of folk;
And if the Norns will have it that the Volsung kin shall fail,
Yet I know of the deed that dies not, and the name that shall ever
avail.’”

Marching towards the palace, the brave little troop soon fell into
Siggeir’s ambuscade, and, although they fought with heroic courage,
they were so overpowered by the superior number of their foes that
Volsung was soon slain and all his sons made captive. Led bound
into the presence of Siggeir, who had taken no part in the fight (for
he was an arrant coward), Sigmund was forced to relinquish his
precious sword, and he and his brothers were all condemned to die.
Signy, hearing this cruel sentence, vainly interceded for them,
but all she could obtain by her prayers and entreaties was that her
kinsmen should be chained to a fallen oak in the forest, there to
perish of hunger and thirst if the wild beasts spared them. Then,
fearing lest his wife should visit and succor her brothers, Siggeir
confined her in the palace, where she was closely guarded night and
day.
Early every morning Siggeir himself sent a messenger into the
forest to see whether the Volsungs were still living, and every
morning the man returned saying a monster had come during the
night and had devoured one of the princes, leaving nothing but his
bones. When none but Sigmund remained alive, Signy finally
prevailed upon one of her servants to carry some honey into the
forest and smear it over her brother’s face and mouth.
That very night the wild beast, attracted by the smell of the
honey, licked Sigmund’s face, and even thrust its tongue into his
mouth. Clinching his teeth upon it, Sigmund, weak and wounded as
he was, struggled until his bonds broke and he could slay the nightly
visitor who had caused the death of all his brothers. Then he
vanished into the forest, where he remained concealed until the daily
messenger had come and gone, and until Signy, released from
captivity, came speeding to the forest to weep over her kinsmen’s
remains.
Seeing her evident grief, and knowing she had no part in
Siggeir’s cruelty, Sigmund stole out of his place of concealment,
comforted her as best he could, helped her to bury the whitening
bones, and registered a solemn oath in her presence to avenge his
family’s wrongs. This vow was fully approved by Signy, who,
however, bade her brother abide a favorable time, promising to send
him a helper. Then the brother and sister sadly parted, she to return
to her distasteful palace home, and he to seek the most remote part
of the forest, where he built a tiny hut and plied the trade of a smith.

“And men say that Signy wept


When she left that last of her kindred; yet wept she never more
Amid the earls of Siggeir, and as lovely as before
Was her face to all men’s deeming: nor aught it changed for ruth,
Nor for fear nor any longing; and no man said for sooth
That she ever laughed thereafter till the day of her death was come.”

Years passed by. Siggeir, having taken possession of the


Volsung kingdom, proudly watched the growth of his
Signy’s sons.
eldest son, whom Signy secretly sent to her brother as
soon as he was ten years of age, bidding Sigmund train the child up
to help him, if he were worthy of such a task. Sigmund reluctantly
accepted the charge; but as soon as he had tested the boy and
found him deficient in physical courage, he either sent him back to
his mother, or, as some versions relate, slew him.
Some time after this Sigmund tested Signy’s second son, who
had been sent to him for the same purpose, and found him wanting
also. Evidently none but a pure-blooded Volsung could help him in
his work of revenge, and Signy, realizing this, resolved to commit a
crime.

“And once in the dark she murmured: ‘Where then was the ancient
song
That the Gods were but twin-born once, and deemed it nothing
wrong
To mingle for the world’s sake, whence had the Æsir birth,
And the Vanir, and the Dwarf-kind, and all the folk of earth?’”

This resolution taken, she summoned a beautiful young witch,


exchanged forms with her, and, running into the forest, sought
shelter in Sigmund’s hut. Deeming her nothing but the gypsy she
seemed, and won by her coquetry, he soon made her his wife. Three
days later she vanished from his hut, returned to the palace,
resumed her own form, and when she gave birth to a little son, she
rejoiced to see his bold glance and strong frame.
When this child, Sinfiotli, was ten years of age, she herself made
Sinfiotli. a preliminary test of his courage by sewing his
garment to his skin. Then she suddenly snatched it off
with shreds of flesh hanging to it, and as the child did not even
wince, but laughed aloud, she confidently sent him to Sigmund. He,
too, found the boy quite fearless, and upon leaving the hut one day
he bade him take meal from a certain sack, and knead and bake the
bread. On returning home Sigmund asked Sinfiotli whether his
orders had been carried out. The lad replied by showing the bread,
and when closely questioned he artlessly confessed that he had
been obliged to knead into the loaf a great adder which was hidden
in the meal. Pleased to see that the child, for whom he felt a strange
affection, had successfully stood the test which had daunted his
predecessors, Sigmund bade him refrain from eating of that loaf, as
he alone could taste poison unharmed, and patiently began to teach
him all a Northern warrior need know.

“For here the tale of the elders doth men a marvel to wit,
That such was the shaping of Sigmund among all earthly kings,
That unhurt he handled adders and other deadly things,
And might drink unscathed of venom: but Sinfiotli was so wrought
That no sting of creeping creatures would harm his body aught.”

Sigmund and Sinfiotli soon became inseparable companions,


and while ranging the forest together they once came
The
werewolves. to a hut, where they found two men sound asleep.
Wolf skins hanging near them immediately made them
conclude that the strangers were werewolves (men whom a cruel
spell forced to assume the habits and guise of ravenous wolves, and
who could only resume their natural form for a short space at a time).
Prompted by curiosity, Sigmund donned one of the wolf skins,
Sinfiotli the other, and they were soon metamorphosed into wolves
and rushed through the forest, slaying and devouring all they saw.
Such were their wolfish passions that they soon attacked each
other, and after a fierce struggle Sinfiotli, the younger and weaker,
fell down dead. This sudden catastrophe brought Sigmund to his
senses. While he hung over his murdered companion in sudden
despair, he saw two weasels come out of the forest and fight until
one lay dead. The live weasel then sprang back into the thicket, and
soon returned with a leaf, which it laid upon its companion’s breast.
At the contact of the magic herb the dead beast came back to life. A
moment later a raven flying overhead dropped a similar leaf at
Sigmund’s feet, and he, understanding that the gods wished to help
him, laid it upon Sinfiotli, who was restored to life.
Afraid lest they might work each other further mischief while in
this altered guise, Sigmund and Sinfiotli now crept home and
patiently waited until the time of release had come. On the ninth
night the skins dropped off and they hastily flung them into the fire,
where they were entirely consumed, and the spell was broken
forever.
It was now that Sigmund confided the story of his wrongs to
Sinfiotli, who swore that, although Siggeir was his father (for neither
he nor Sigmund knew the secret of his birth), he would help him to
take his revenge. At nightfall, therefore, he accompanied Sigmund to
the palace; they entered unseen, and concealed themselves in the
cellar, behind the huge beer vats. Here they were discovered by
Signy’s two youngest children, who were playing with golden rings,
which rolled into the cellar, and who thus suddenly came upon the
men in ambush.
They loudly proclaimed the discovery they had just made to their
father and his guests, but, before Siggeir and his men could don
their arms, Signy caught both children by the hand, and dragging
them into the cellar bade her brother slay the little traitors. This
Sigmund utterly refused to do, but Sinfiotli struck off their heads ere
he turned to fight against the assailants, who were rapidly closing
around him.
In spite of all efforts Sigmund and his brave young companion
soon fell into the hands of the Goths, whose king, Siggeir, sentenced
them to be buried alive in the same mound, a stone partition being
erected between them so they could neither see nor touch each
other. The prisoners were already confined in their living graves, and
the men were about to place the last stones on the roof, when Signy
drew near, bearing a bundle of straw, which they allowed her to
throw at Sinfiotli’s feet, for they fancied that it contained only a few
provisions which would prolong his agony a little without helping him
to escape.
When the workmen had departed and all was still, Sinfiotli undid
the sheaf and shouted for joy when he found instead of bread the
sword which Odin had given to Sigmund. Knowing that nothing could
dull or break the keen edge of this fine weapon, Sinfiotli thrust it
through the stone partition, and, aided by Sigmund, sawed an
opening, and both soon effected an escape through the roof.
“Then in the grave-mound’s darkness did Sigmund the king upstand,
And unto that saw of battle he set his naked hand;
And hard the gift of Odin home to their breasts they drew;
Sawed Sigmund, sawed Sinfiotli, till the stone was cleft atwo,
And they met and kissed together: then they hewed and heaved full
hard
Till, lo, through the bursten rafters the winter heavens bestarred!
And they leap out merry-hearted; nor is there need to say
A many words between them of whither was the way.”

Sigmund and Sinfiotli, free once more, noiselessly sought the


palace, piled combustible materials around it, and
Sigmund’s
vengeance. setting fire to it placed themselves on either side the
door, declaring that none but the women should be
allowed to pass through. Then they loudly called to Signy to escape
ere it was too late, but she had no desire to live, and after kissing
them both and revealing the secret of Sinfiotli’s birth she sprang
back into the flames, where she perished.

“And then King Siggeir’s roof-tree upheaved for its utmost fall,
And its huge walls clashed together, and its mean and lowly things
The fire of death confounded with the tokens of the kings.”

The long-planned vengeance had finally been carried out,


Volsung’s death had been avenged, and Sigmund,
Helgi.
feeling that nothing now detained him in Gothland, set
sail with Sinfiotli and returned to Hunaland, where he was warmly
welcomed and again sat under the shade of his ancestral tree, the
mighty Branstock. His authority fully established, Sigmund married
Borghild, a beautiful princess, who bore him two sons, Hamond and
Helgi, the latter of whom was visited by the Norns when he lay in his
cradle, and promised sumptuous entertainment in Valhalla when his
earthly career should be ended.
“And the woman was fair and lovely, and bore him sons of fame;
Men called them Hamond and Helgi, and when Helgi first saw light
There came the Norns to his cradle and gave him life full bright,
And called him Sunlit Hill, Sharp Sword, and Land of Rings,
And bade him be lovely and great, and a joy in the tale of kings.”

This young Volsung prince was fostered by Hagal, for Northern


kings generally entrusted their sons’ education to a stranger, thinking
they would be treated with less indulgence than at home. Under this
tuition Helgi became so fearless that at the age of fifteen he ventured
alone into the palace of Hunding, with whose whole race his family
was at feud. Passing all through the palace unmolested and
unrecognized, he left an insolent message, which so angered
Hunding that he immediately set out in pursuit of the bold young
prince. Hunding entered Hagal’s house, and would have made Helgi
a prisoner had the youth not disguised himself as a servant maid,
and begun to grind corn as if it were his wonted occupation. The
invaders marveled somewhat at the maid’s tall stature and brawny
arms, but departed without suspecting that they had been so near
the hero whom they sought.
Having thus cleverly escaped, Helgi joined Sinfiotli; they
collected an army, and marched openly against the Hundings, with
whom they fought a great battle, during which the Valkyrs hovered
overhead, waiting to convey the slain to Valhalla. Gudrun, one of the
battle maidens, was so charmed by the courage which Helgi
displayed, that she openly sought him and promised to be his wife.
Only one of the Hunding race, Dag, remained alive, and he was
allowed to go free after promising never to try to avenge his
kinsmen’s death. This promise was not kept, however, for Dag,
having borrowed Odin’s spear Gungnir, treacherously made use of it
to slay Helgi. Gudrun, now his wife, wept many tears at his death,
and solemnly cursed his murderer; then, hearing from one of her
maids that her slain husband kept calling for her in the depths of his
tomb, she fearlessly entered the mound at night and tenderly
inquired why he called and why his wounds kept on bleeding even
after death. Helgi answered that he could not rest happy because of
her grief, and declared that for every tear she shed a drop of his
blood must flow.

“Thou weepest, gold-adorned!


Cruel tears,
Sun-bright daughter of the south!
Ere to sleep thou goest;
Each one falls bloody
On the prince’s breast,
Wet, cold, and piercing,
With sorrow big.”
Sæmund’s Edda (Thorpe’s tr.).

To still her beloved husband’s sufferings, Gudrun then ceased to


weep, but her spirit soon joined his, which had ridden over Bifröst
and entered Valhalla, where Odin made him leader of the Einheriar.
Here Gudrun, a Valkyr once more, continued to wait upon him,
darting down to earth at Odin’s command to seek new recruits for
the army which her lord was to lead into battle when Ragnarok, the
twilight of the gods, should come.
Sinfiotli, Sigmund’s eldest son, also came to an early death; for,
Death of having quarreled with and slain Borghild’s brother, she
Sinfiotli. determined to poison him. Twice Sinfiotli detected the
attempt and told his father there was poison in his
cup. Twice Sigmund, whom no venom could injure, drained the bowl;
but when Borghild made a third and last attempt, he bade Sinfiotli let
the wine flow through his beard. Mistaking the meaning of his
father’s words, Sinfiotli immediately drained the cup and fell to the
ground lifeless, for the poison was of the most deadly kind.

“He drank as he spake the words, and forthwith the venom ran
In a chill flood over his heart, and down fell the mighty man
With never an uttered death-word and never a death-changed look,
And the floor of the hall of the Volsungs beneath his falling shook.
Then up rose the elder of days with a great and bitter cry,
And lifted the head of the fallen; and none durst come anigh
To hearken the words of his sorrow, if any words he said
But such as the Father of all men might speak over Balder dead.
And again, as before the death-stroke, waxed the hall of the
Volsungs dim,
And once more he seemed in the forest, where he spake with naught
but him.”

Speechless with grief, Sigmund tenderly raised his son’s body in


his arms, and strode out of the hall and down to the shore, where he
deposited his precious burden in the skiff of an old one-eyed
boatman who came at his call. But when he would fain have stepped
aboard also, the boatman pushed off and was soon lost to sight. The
bereaved father then slowly wended his way home again, knowing
that Odin himself had come to claim the young hero and had rowed
away with him “out into the west.”
Sigmund repudiated Borghild in punishment for this crime, and
Hiordis. when he was very old indeed he sued for the hand of
Hiordis, a fair young princess, daughter of Eglimi, King
of the Islands. Although this young maiden had many suitors, among
others King Lygni of Hunding’s race, she gladly accepted Sigmund
and became his wife. Lygni, the discarded suitor, was so angry at
this decision, that he immediately collected an army and marched
against his successful rival, who, overpowered by superior numbers,
fought with the courage of despair.
Hidden in a neighboring thicket, Hiordis and her maid anxiously
watched the battle, saw Sigmund pile the dead around him and
triumph over every foe, until at last a tall, one-eyed warrior suddenly
appeared, broke his matchless sword, and vanished, leaving him
defenseless amid the foe, who soon cut him down.

“But, lo! through the hedge of the war-shafts, a mighty man there
came,
One-eyed and seeming ancient, but his visage shone like flame:
Gleaming gray was his kirtle, and his hood was cloudy blue;
And he bore a mighty twi-bill, as he waded the fight-sheaves
through,
And stood face to face with Sigmund, and upheaved the bill to smite.
Once more round the head of the Volsung fierce glittered the
Branstock’s light,
The sword that came from Odin: and Sigmund’s cry once more
Rang out to the very heavens above the din of war.
Then clashed the meeting edges with Sigmund’s latest stroke,
And in shivering shards fell earthward that fear of worldly folk.
But changed were the eyes of Sigmund, the war-wrath left his face;
For that gray-clad, mighty Helper was gone, and in his place
Drave on the unbroken spear-wood ’gainst the Volsung’s empty
hands:
And there they smote down Sigmund, the wonder of all lands,
On the foemen, on the death-heap his deeds had piled that day.”

All the Volsung race and army had already succumbed, so Lygni
immediately left the battlefield to hasten on and take possession of
the kingdom and palace, where he fully expected to find the fair
Hiordis and force her to become his wife. As soon as he had gone,
however, the beautiful young queen crept out of her hiding place in
the thicket, ran to the dying Sigmund, caught him to her breast in a
last passionate embrace, and tearfully listened to his dying words.
He then bade her gather up the fragments of his sword, carefully
treasure them, and give them to the son whom he foretold would
soon be born, and who was destined to avenge his death and be far
greater than he.

“‘I have wrought for the Volsungs truly, and yet have I known full well
That a better one than I am shall bear the tale to tell:
And for him shall these shards be smithied; and he shall be my son,
To remember what I have forgotten and to do what I left undone.’”

While Hiordis was mourning over Sigmund’s lifeless body, her


watching handmaiden warned her of the approach of a party of
vikings. Retreating into the thicket once more, Hiordis
Elf, the viking.
exchanged garments with her; then, bidding her walk
first and personate the queen, they went to meet the viking Elf
(Helfrat or Helferich), and so excited his admiration for Sigmund that
he buried him with all pomp, and promised them a safe asylum in his
house.
As he had doubted their relative positions from the very first
moment, he soon resorted to a seemingly idle question to ascertain
their real rank. The pretended queen, when asked how she knew the
hour had come for rising when the winter days were short and there
was no light to announce the coming of morn, replied that, as she
was in the habit of drinking milk ere she fed the cows, she always
awoke thirsty. But when the same question was put to the real
Hiordis, she answered that she knew it was morning because the
golden ring her father had given her grew cold on her hand.
Elf, having thus discovered the true state of affairs, offered
Sigurd. marriage to the pretended handmaiden, Hiordis,
promising to foster her child by Sigmund—a promise
which he nobly kept. The child was sprinkled with water by his hand
—a ceremony which our pagan ancestors scrupulously performed—
received from him the name of Sigurd, and grew up in the palace.
There he was treated as the king’s own son, receiving his education
from Regin, the wisest of men, who knew all things and was even
aware of his own fate, which was to fall by a youth’s hand.

“Again in the house of the Helper there dwelt a certain man,


Beardless and low of stature, of visage pinched and wan:
So exceeding old was Regin, that no son of man could tell
In what year of the days passed over he came to that land to dwell:
But the youth of king Elf had he fostered, and the Helper’s youth
thereto,
Yea, and his father’s father’s: the lore of all men he knew,
And was deft in every cunning, save the dealings of the sword:
So sweet was his tongue-speech fashioned, that men trowed his
every word;
His hand with the harp-strings blended was the mingler of delight
With the latter days of sorrow; all tales he told aright;
The Master of the Masters in the smithying craft was he;
And he dealt with the wind and the weather and the stilling of the
sea;
Nor might any learn him leech-craft, for before that race was made,
And that man-folk’s generation, all their life-days had he weighed.”

Under this tutor young Sigurd grew up to great wisdom. He


mastered the smith craft, and the art of carving all manner of runes,
learned languages, music, and eloquence, and, last but not least,
became a doughty warrior whom none could subdue. By Regin’s
advice, Sigurd, having reached manhood, asked the king for a war
horse—a request which was immediately granted, for he was bidden
hasten to Gripir, the stud-keeper, and choose from his flock the steed
he liked best.
On his way to the meadow where the horses were at pasture,
Sigurd encountered a one-eyed stranger, clad in gray and blue, who
bade him drive the horses into the river and select the one which
could breast the foaming tide most successfully.
Sigurd, acting according to this advice, noticed that one horse,
after crossing, raced around the meadow on the opposite side; then,
plunging back into the river, he returned to his former pasture without
showing any signs of fatigue. The young hero selected this horse,
therefore, calling him Grane or Greyfell. This steed was a
descendant of Odin’s eight-footed horse Sleipnir, and, besides being
unusually strong and indefatigable, was as fearless as his master. A
short time after this, while Regin and his pupil were sitting over the
fire, the former struck his harp, and, after the manner of the Northern
scalds, sang or recited the following tale, which was the story of his
life:
Hreidmar, king of the dwarf folk, was the father of three sons.
The treasure Fafnir, the eldest, was gifted with a fearless soul and a
of the dwarf powerful hand; Otter, the second, with snare and net,
king. and the power of changing form at will; and Regin, the
third, could, as we have already seen, command all knowledge and
skillfully ply the trade of a smith. To please the avaricious old
Hreidmar, this youngest son fashioned for him a house which was all
lined with glittering gold and flashing gems, and guarded by Fafnir,
whose fierce glances and Ægis helmet none dared encounter.
Now it came to pass that Odin, Hoenir, and Loki once came
down upon earth in human guise for one of their wonted expeditions
to test the hearts of men, and soon reached the land where
Hreidmar dwelt.

“And the three were the heart-wise Odin, the Father of the Slain,
And Loki, the World’s Begrudger, who maketh all labor vain,
And Hönir, the Utter-Blameless, who wrought the hope of man,
And his heart and inmost yearnings, when first the work began;—
The God that was aforetime, and hereafter yet shall be
When the new light yet undreamed of shall shine o’er earth and sea.”

These gods had not wandered very far before Loki perceived an
otter basking in the sun. Animated by his usual spirit of destruction,
he slew the unoffending beast—which, as it happened, was the
dwarf king’s second son, Otter—and flung its lifeless body over his
shoulders, thinking it would furnish a good dish when meal time
came.
Following his companions, Loki came at last to Hreidmar’s
house, entered with them, and flung his burden down upon the floor.
The moment the dwarf king’s glance fell upon it he flew into a
towering rage, and before the gods could help themselves they were
bound by his order, and heard him declare that they should never
recover their liberty unless they could satisfy his thirst for gold by
giving him enough of that precious substance to cover the otterskin
inside and out.

“‘Now hearken the doom I shall speak! Ye stranger-folk shall be free


When ye give me the Flame of the Waters, the gathered Gold of the
Sea,
That Andvari hideth rejoicing in the wan realm pale as the grave;
And the Master of Sleight shall fetch it, and the hand that never
gave,
And the heart that begrudgeth forever, shall gather and give and rue.
Lo, this is the doom of the wise, and no doom shall be spoken
anew.’”

As this otterskin had the property of stretching itself out to a


fabulous size, no ordinary treasure could suffice to cover it. The gods
therefore bade Loki, who was liberated to procure the ransom,
hasten off to the waterfall where the dwarf Andvari dwelt, and secure
the treasure he had amassed by magical means.

“There is a desert of dread in the uttermost part of the world,


Where over a wall of mountains is a mighty water hurled,
Whose hidden head none knoweth, nor where it meeteth the sea;
And that force is the Force of Andvari, and an Elf of the dark is he.
In the cloud and the desert he dwelleth amid that land alone;
And his work is the storing of treasure within his house of stone.”

In spite of diligent search, however, Loki could not find the dwarf;
but perceiving a salmon sporting in the foaming waters, he shrewdly
concluded the dwarf must have assumed this shape, and borrowing
Ran’s net he soon had the fish in his power. As he had suspected, it
was Andvari, who, in exchange for liberty, reluctantly brought forth
his mighty treasure and surrendered it all, including the Helmet of
Dread and a hauberk of gold, reserving only the ring he wore, which
was gifted with miraculous powers, and, like a magnet, helped him to
collect the precious ore. But the greedy Loki, catching sight of it,
wrenched it away from him and departed laughing, while the dwarf
hurled angry curses after him, declaring that the ring would ever
prove its possessor’s bane and would cause the death of many.
“That gold
Which the dwarf possessed
Shall to two brothers
Be cause of death,
And to eight princes,
Of dissension.
From my wealth no one
Shall good derive.”
Sæmund’s Edda (Thorpe’s tr.).

On arriving at Hreidmar’s hut, Loki found the mighty treasure


none too great, for the skin widened and spread, and he was even
forced to give the ring Andvaranaut (Andvari’s loom) to purchase his
and his companions’ release. The gold thus obtained soon became a
curse, as Andvari had predicted, for Fafnir and Regin both coveted a
share. As for Hreidmar, he gloated over his treasure night and day,
and Fafnir the invincible, seeing that he could not obtain it otherwise,
slew his own father, donned the Helmet of Dread and the hauberk of
gold, grasped the sword Hrotti, and when Regin came to claim a part
drove him scornfully out into the world, where he bade him earn his
own living.
Thus exiled, Regin took refuge among men, to whom he taught
the arts of sowing and reaping. He showed them how to work
metals, sail the seas, tame horses, yoke beasts of burden, build
houses, spin, weave, and sew—in short, all the industries of civilized
life, which had hitherto been unknown. Years elapsed, and Regin
patiently bided his time, hoping that some day he would find a hero
strong enough to avenge his wrongs upon Fafnir, whom years of
gloating over his treasure had changed into a horrible dragon, the
terror of Gnîtaheid (Glittering Heath), where he had taken up his
abode.
His story finished, Regin suddenly turned to the attentive Sigurd,
told him he knew that he could slay the dragon if he wished, and
inquired whether he were ready to help his old tutor avenge his
wrongs.
“And he spake: ‘Hast thou hearkened, Sigurd? Wilt thou help a man
that is old
To avenge him for his father? Wilt thou win that treasure of gold
And be more than the kings of the earth? Wilt thou rid the earth of a
wrong
And heal the woe and the sorrow my heart hath endured o’er long?’”

Sigurd immediately assented, declaring, however, that the curse


must be assumed by Regin, for he would have none
Sigurd’s
sword. of it; and, in order to be well prepared for the coming
fight, he asked his master to forge him a sword which
no blow could break. Twice Regin fashioned a marvelous weapon,
but twice Sigurd broke it to pieces on the anvil. Then, declaring that
he must have a sword which would not fail him in time of need, he
begged the broken fragments of Sigmund’s weapon from his mother
Hiordis, and either forged himself or made Regin forge a matchless
blade, whose temper was such that it neatly severed some wool
floating gently down the stream, and divided the great anvil in two
without being even dinted.
After paying a farewell visit to Gripir, who, knowing the future,
foretold every event in his coming career, Sigurd took leave of his
mother, and accompanied by Regin set sail from his native land,
promising to slay the dragon as soon as he had fulfilled his first duty,
which was to avenge his father Sigmund’s death.

“‘First wilt thou, prince,


Avenge thy father,
And for the wrongs of Eglymi
Wilt retaliate.
Thou wilt the cruel,
The sons of Hunding,
Boldly lay low:
Thou wilt have victory.’”
Lay of Sigurd Fafnicide (Thorpe’s tr.).

You might also like