.NET Design Patterns - Praseed Pai - E-Book

.NET Design Patterns E-Book

Praseed Pai

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Knowing about design patterns enables developers to improve their code base, promoting code reuse and making their design more robust.

This book focuses on the practical aspects of programming in .NET. You will learn about some of the relevant design patterns (and their application) that are most widely used. We start with classic object-oriented programming (OOP) techniques, evaluate parallel programming and concurrency models, enhance implementations by mixing OOP and functional programming, and finally to the reactive programming model where functional programming and OOP are used in synergy to write better code.

Throughout this book, we’ll show you how to deal with architecture/design techniques, GoF patterns, relevant patterns from other catalogs, functional programming, and reactive programming techniques.

After reading this book, you will be able to convincingly leverage these design patterns (factory pattern, builder pattern, prototype pattern, adapter pattern, facade pattern, decorator pattern, observer pattern and so on) for your programs. You will also be able to write fluid functional code in .NET that would leverage concurrency and parallelism!

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 353

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

.NET Design Patterns
Credits
Foreword
About the Authors
About the Reviewers
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. An Introduction to Patterns and Pattern Catalogs
OOP - A short history
Patterns and pattern movement
Key pattern catalogs
GoF patterns
POSA catalog
POEAA catalog
EIP catalog
J2EE design patterns catalog
DDD-based patterns
Arlow/Nuestadt patterns
Should we use all of these?
The C# language and the .NET platform
C# language and the singleton pattern
Summary
2. Why We Need Design Patterns?
Some principles of software development
Why are patterns required?
A quick foray into the .NET Reflection API
Personal income tax computation - A case study
Archetypes and business archetype patterns
Entity, value, and data transfer objects
A computation engine
The application to engine communication
The plugin system to make system extensible
Factory method pattern and plugins
Finalizing the solution
Design by contract and template method pattern
Using the Facade pattern to expose the computation API
Summary
3. A Logging Library
Requirements for the library
Solutions approach
Writing content to a media
Template method pattern and content writers
Writing a log entry to a file stream
Writing a log entry to a database
Writing a log entry to a network stream
Logging strategy atop the strategy pattern
The factory method pattern for instantiation
Writing a generic factory method implementation
Factory method, singleton, and prototype pattern for dynamic class loading
Refactoring the code with the generic factory method
A log server for network logging
A simple client program to test the library
Summary
4. Targeting Multiple Databases
Requirements for the library
Solutions approach
A quick primer on ADO.net
The abstract factory pattern and object instantiation
The SQL server implementation
The SQLite implementation
The Oracle and ODBC implementation
The adapter pattern powered API
The adapter class Implementation
The adapter configuration
The client program
Summary
5. Producing Tabular Reports
Requirements for the library
Solutions approach
iTextSharp for the PDF output
Composite and visitor pattern - A quick primer
The composite pattern and document composition
Visitor pattern for document traversal
PDFVisitor for PDF generation
HTMLVisitor for HTML generation
The client program
Summary
6. Plotting Mathematical Expressions
Requirements for the expressions library and app
Solutions approach
The graph plotter application
The observer pattern for UI events
The expression evaluator and interpreter pattern
The abstract syntax tree (AST)
The grammar of expressions
Lexical analysis
The parser module
The builder, facade, and expression APIs
Summary
7. Patterns in the .NET Base Class Library
Adapter pattern in the .NET BCL
Strategy pattern in the .NET BCL
Builder pattern in the .NET BCL
Decorator pattern in the .NET BCL
Chain of responsibility pattern in ASP.net
Bridge pattern in the .NET RCW
Factory pattern in the .NET BCL
Observer pattern in the WPF
Composite pattern in the .NET Framework
Facade pattern in the .NET BCL
Iterator pattern in the .NET BCL
Summary
8. Concurrent and Parallel Programming under .NET
Days of Free Lunch
Days of Sponsored Lunch
Concurrent versus parallel
Some common patterns of parallel programming
Embarrassingly or conveniently parallel
Problem statement
Solutions approach
Step 1
Step 2
Step 3
Fork/join or master/worker
Speculative execution
Producer/consumer
Summary
9. Functional Programming Techniques for Better State Management
Being functional
Referential transparency
First-class and higher-order functions
Function type
Lambda (λ) calculus
Anonymous functions
Closures
Currying and partial application
Currying
Partial application
Applying currying and partial application
Expression trees
Recursion
Sample programs
Spell checker
Subset generation
How does LINQ work?
Summary
10. Pattern Implementation Using Object/Functional Programming
A strategy pattern implementation using FP/OOP
Using FP constructs to make the code better
A fresh look at the iterator pattern using FP/OOP
MapReduce programming idiom
A new spin on the template method pattern using FP/OOP
Using FP for the template method pattern implementation
A quick note on the observer pattern
Does FP replace GoF patterns?
Summary
11. What is Reactive Programming?
Being reactive
Electronic spread sheets - A quintessential example
Reactive programming model
Functional reactive programming
Reactive programming principles
Rx from Microsoft
Key data structures of Rx
IEnumberable/IObservable duality
Converting entities to streams (IObservable<T>)
Converting events into stream
Reduction of streams (sequences)
Inspection of streams (sequences)
Aggregation of streams (sequences)
Transformation of streams (sequences)
Combining streams (sequences)
A philosophy for reactive programming
Summary
12. Reactive Programming Using .NET Rx Extensions
Streams as a way of life
Spell checker using events composition
MVVM on Rx
An asynchronous logger
Near real-time visualizer/dashboard
Summary
13. Reactive Programming Using RxJS
The JS world
Rx foundations
RxJS formalism
Observables and observers
Observables from arrays
Observables from events
Observables from callbacks
Observable pipeline
Subject et al.
Schedulers
RxJS samples
Real-time file watcher
Change galore
Summary
14. A Road Ahead
Polyglot programming and design
Polyglot programming with C/C++
The polyglot web programming
The JavaScript evolution
Dynamic/scripting languages
Emergence of functional programming
Mobile revolution
A quick note on polyglot persistence
How to become a polyglot programmer?
Domain-specific languages
Ontology
AntiPatterns
Summary

.NET Design Patterns

.NET Design Patterns

Copyright © 2017 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 authors, 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: January 2017

Production reference: 1250117

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-615-0

www.packtpub.com

Credits

Authors

Praseed Pai

Shine Xavier

Copy Editor

Sonia Mathur

Reviewers

Soumya Mukherjee

Vidya Vrat Agarwal

Project Coordinator

Izzat Contractor

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Francy Puthiry

Content Development Editor

Siddhi Chavan

Graphics

Jason Monteiro

Technical Editor

Sunith Shetty

Production Coordinator

Shraddha Falebhai

Foreword

We are living in an era where most of the things that we do are getting automated through software. Even though, there is definite trend towards pre-packaged software modules and platforms, there is always a place for custom software development and integration projects. In the Enterprise world, .NET and Java EE are the natural platforms of choice for custom software development and deployments. With Agile software development methods, continuous delivery and Domain-Driven Design dominating the scene, there is a need for standardization and communication about software artifacts in a “platform-agnostic” manner.  In this context, software design patterns becomes a primary tool for such communications.

You have in your hands a book that encompasses more than four decades of collective wisdom amassed by these two authors, as part of their continuous pursuit of knowledge and excellence, in the software engineering and technology consulting arena. What is more significant is the fact that these knowledge representations are a direct reflection of a practitioner’s mindset; some of those have been undertaken for our organization under our supervision!  This is more than a reference book and should be looked at as a handbook for developers who are aspiring to take their skills to the next level and design state-of-the-art systems independently. This is undoubtedly a book that helps unfold many underlying principles that further educate and help one appreciate the various programming paradigms that are in vogue, as I write this foreword.

We have been continuously disrupting and pushing computing limits way beyond CPUs and GPUs over the past five decades. It is quite amazing to see the ground the authors have covered, in terms of contemplating the evolution of software design, patterns and idioms, to help developers create scalable and consistent code. More than coverage, their focus has been on certain aspects of design that help you create well structured (leveraging GoF patterns), scalable (through concurrent and parallel programming) and reliable (through functional and reactive programming) code with some of the .NET platform tools that transcend conventional imperative programming techniques.

At the core, the book deals with how pattern-based software development helps one to write better code. The authors have deliberately crafted the book to convey how various development patterns that are part of different catalogues can be put to use in a coordinated manner to write good quality code in .NET. The book covers how one can use GoF, POSA, DDD, POEAA, and EIP catalogue in the C# programming language.

Praseed and Shine are part of UST Global’s Technology Consulting group and have been collaborating professionally for the last ten years. They truly complement each other when it comes to software design and development. Their command over computer science first principles, ability to learn new technologies, appetite for challenges, and passion for software design is truly commendable. This makes their technology leadership invaluable to any professional organization.

Leveraging the core platform features (in this case, .NET) in tandem with industry-standard best practices (in this case, proven design pattern catalogues and idioms) is the need of the hour and becomes a clear differentiator when it comes to delivering high quality, scalable, and consistent code. This clearly is any developer’s best hedge in the present day's highly volatile technology landscape. I believe the authors have tried their best in articulating this with anecdotes and detailed code samples, and I hope that, after reading this book, you will feel the same way.

Arun Narayanan

COO, UST Global

About the Authors

Praseed Pai is a software engineering/re-engineering professional with good business acumen, technical competency, and software engineering skills. He has presented on various topics in more than two hundred technical events in the last decade and half. His areas of interest include software architecture, design patterns, domain-specific languages, engineering software development, computer graphics, and machine learning. Currently, he is associated with the UST global as a senior solutions architect in their consulting division. He is also the primary force behind the SLANGFORDOTNET compiler infrastructure, which has been ported to VB.NET (CLR), Java (JVM), C++ (LLVM), Python, JavaScript, and Ruby. He lives in the city of Kochi with his wife and two kids.

I would like to start off thanking my co-author Shine Xavier for undertaking this journey along with me. An important acknowledgment goes to my longtime collaborator and friend Shalvin PD, who introduced us to Denim Pinto of Packt. I would like to acknowledge the contributions of Aneesh P Revi, Nikhil Nair, Sarath Soman, Vaisakh Babu, Haridas Nair, John Thomas, Biju Alapat, Joseph Abraham, Shaji P Dayanandan, and members of the Kerala Microsoft Users Group (KMUG) while working on the content of the book. I would like to thank my parents, Mrs. Mohana T Pai and the late K.J. Thrivikrama Pai, who taught me the value of continuous learning. I whole heartedly thank my wife, Sandhya L Kammath, for giving encouragement and taking care of our domestic issues herself, while I was writing this book. Being a developer herself, I could get different perspectives on the content I was writing. Last, but not least, Sidharth Pai and Karthik Pai, my sons, for allowing me to concentrate on the book, by not bothering much with their usual demands! Finally, I thank the wonderful folks at Packt and the two reviewers who helped us to make the book better.

Shine Xavier is a core software engineering practitioner with an extreme passion for designing/building software solutions, application frameworks, and accelerators that help maintain productivity, code quality, performance, and security. His areas of interest include functional programming, interpreters, JavaScript library development, visual programming, algorithms, performance engineering, automation, enterprise mobility, IoT and machine learning. He is currently associated with UST Global as a senior architect, where he continues to provide technical leadership in customer engagements, pre-sales, practice development, product development, innovation, and technology adoption. He lives with his wife and three kids in Thiruvananthapuram, Kerala, India.

I would like to start off thanking my colleague and mentor Praseed Pai for choosing me to co-author this book. It has been a joy and privilege penning this book along with you, my friend! There are others without whom I wouldn’t have been able to complete this book. In particular, I would like to thank: the folks at Packt (Denim Pinto, Pooja Mhapsekar, Siddhi Chavan, and Sunith Shetty) who were really patient and inspiring us throughout this journey and the technical reviewers Soumya Mukherjee and Vidya Vrat Agarwal, who really pushed us all along to get this book one knot better. This book has become a lot better and taken its present shape because of you all! My teachers and friends in school and college, mentors (Arun Narayanan and Sunil Balakrishnan), colleagues (Jeenu Mathew, Viby Abraham, Renju Ramadevan, Nikhil Nair, John Thomas, Renjith Ramachandran, Jenson Joseph, Ashok Nair, and Abhilash Ponnachan) and members of the computer science fraternity (many whom I paid my respects to in the book). You all continue to teach, motivate, and inspire me! My parents (Xavier and Grace) without whom I would cease to exist. My wife (Kavitha Jose) and kids (Joel, Sera and Johaan) for their whole-hearted love, support, and understanding in helping me realize this dream.

About the Reviewers

Soumya Mukherjee is very passionate about working on open source projects and has extensive experience in architecting enterprise applications in .NET, JAVA, Ruby, and Python.

He has expertise in implementation of Test Driven and Behavioural Driven development and test automation for large teams. He has developed various tools, one of them is the Quantinuous Agile Framework (QAF) for continuous mobile and web automation.

He is a certified MCAD.NET, Certified Scrum Master (CSM), Certified Professional Selenium Agile Tester, a Trainer, and a seasoned author of couple of books on amazon. He is also a speaker across multiple world renowned conferences, an Agile Practitioner, and loves mentoring team's in Open Source Technologies.

He has extensive experience in Software Test Automation using professional tools, such as QTP, QC, LoadRunner, Jmeter, and Neoload GreenHat, and with Open Source Tools, such as Selenium RC & Web driver with Java, .Net, Python, Ruby, FitNess, JMeter, SoapUI, TestNG, ReportNG, JUnit, Cucumber & Capybara, and Tosca & Perfecto.

An ex-employee of JP Morgan, Merill Lynch, he is currently the co-founder of QAAgility Technologies and AppTestPro. He resides in Mumbai, India, with his wife, Garima.

Vidya Vrat Agarwal is passionate about .NET, a Microsoft MVP, a C# Corner MVP, a TOGAF certified architect, a Certified Scrum Master (CSM), an author, a speaker, a certified MCT, MCPD, MCTS, MCSD.NET, MCAD.NET, and MCSD. He is currently working as a .NET Enterprise Architect and Consultant in USA. He is passionate about .NET technology and loves to contribute to the .NET community. He blogs at http://www.MyPassionFor.NET and can be followed on Twitter, @DotNetAuthor. He lives with his wife, Rupali, and two daughters, Pearly and Arshika, in Redmond, WA.

www.PacktPub.com

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://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously--that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].

Preface

Writing modern Enterprise software requires large teams that need close co-ordination to deliver quality products and services. The teams require a common language for communication when dealing with technical solutions and artifacts, in order to work as a cohesive unit for meeting the set objective. The GOF design pattern catalog was a major step in this direction. This was followed by other similar catalogs to empower software engineering teams with a common pool of shared idioms and practices. For all practical purpose, GOF patterns became sine qua non for patterns. But there are other equally important catalogs that you would want to leverage.

There have been attempts to map the pattern catalogs to platforms such as JEE and .NET. The J2EE --design patterns and Microsoft--patterns and practices catalogs were attempts in this direction. The emergence and adoption of functional programming and reactive programming models mandates a fresh look at the patterns, applied to modern .NET software development. That is where this book comes into the picture. This book provides detailed examples written using C#/.NET, which will help developers map different constructs from various pattern catalogs to executable code.

The book you have got in your hand outlines author's perspectives about how design, architecture, and domain patterns can be applied in practice by leveraging the .NET platform. The topics covered deals with various patterns and pattern catalogs, including GOF patterns, concurrent programming, object/functional programming, and functional reactive programming. The final chapter talks about materials which we could not cover in this book, but, which a modern programmer should master to become an effective developer.

Learning, as we all know, is a continuous process. We have made to the best of our ability to impart our learnings on the job so that it benefits any one who is interested. We have leveraged code extensively for illustrating this with very detailed examples. Design illustration in the form of UML and context diagrams accompany the concepts and code. The views and perspectives we have outlined mostly align with the industry references and standards.

What this book covers

Chapter 1, An Introduction to Patterns and Pattern Catalogs, deals with the summary of key pattern catalogs and also deals with the evolution of the C# programming language. The chapter deals with the gist of GOF, POSA, DDD, EIP, J2EE, POEAA, and the Arlow and Neustadt pattern catalog.

Chapter 2, Why We Need Design Patterns?, provides the rationale for applying patterns in the context of software engineering. The chapter deals with some foundational principles such as SOLID, KISS, YAGNI, DRY/WET and so on, that lay the foundation for pattern oriented software development. A tax computation engine that uses the factory method pattern, the template method pattern, and design by contract is given as a running example.

Chapter 3, A Logging Library, implements a logging library which can be used in a multithreaded environment. The implementation leverages the template method pattern, the strategy pattern, and the factory method pattern. A custom Dependency Injection framework loads the classes on the fly.

Chapter 4, Targeting Multiple Databases, shows how one can use different persistent technologies (Oracle, SQL Server, SQLite, and so on) without changing a single line of application code. The library leverages ADO.net and uses the abstract factory pattern, the factory pattern, and the adapter pattern.

Chapter 5, Producing Tabular Reports, shows how one can create a canonical object model based on the composite pattern and traverse the object model through visitor pattern to generate HTML and PDF documents.

Chapter 6, Plotting Mathematical Expressions, deals with a library that uses composite, interpreter, observer, builder, and facade patterns to plot arbitrary mathematical expression on the fly using Windows Presentation Foundation. 

Chapter 7, Patterns in the .NET Base Class Library, demonstrates how the designers of .NET base class library has leveraged various GOF patterns to give developers a good programing model.

Chapter 8, Concurrent and Parallel Programming under .NET, steps into the very important topic of concurrent and parallel programming by leveraging constructs provided by the .NET platform. Topics such as concurrency versus parallelism, fork/join parallelism, producer-consumer model, and so on are dealt at depth.

Chapter 9, Functional Programming Techniques for Better State Management, deals with the very important topic of managing state by leveraging closures, lambda, immutability, LINQ and other functional programming techniques.

Chapter 10, Pattern Implementation Using Object/Functional Programming, illustrates Map/Reduce, the template method pattern, the iterator pattern, and the strategy pattern by a judicious mix of functional and object-oriented programming constructs.

Chapter 11, What is Reactive Programming?, gives you the gist of Functional Reactive programming model and its realization on the .NET platform.

Chapter 12, Reactive Programming Using .NET Rx Extensions, carries forward from the previous chapter and shows some concrete examples where Functional Reactive Programming techniques can be put for real world use.

Chapter 13, Reactive Programming Using RxJS, gives a very good introduction to the techniques and internals of RxJS for writing web-based responsive UI.

Chapter 14, A Road Ahead, sheds light on a learning progression path highlighting the importance of polyglot programming, domain-specific languages, ontology, and antipatterns.

What you need for this book

The reader is supposed to have worked with at least a project with the .NET platform using C# as the primary programming language. A good understanding of basic object oriented programming will help you navigate the territory faster. From a software perspective, a laptop, desktop or a virtual machine with Visual Studio 2012 (or above) to test and play around with the source code.

Who this book is for

The book is useful for any C#/.NET developer to understand how enterprise class applications are designed, developed, and deployed. Rather than studying various patterns in isolation, the book deals with scenarios where patterns are often combined to engineer state of the art applications. Developers who work with Java can also follow the book without much difficulty, as both platforms have lot of things in common.

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: "An instance of this class needs to be passed to the Sort routine of the List<T> instance."

A block of code is set as follows:

class Employee { public String name {get;set;} public int age {get;set;} public double salary { get; set; } }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

return function () { try { return fn.apply(null, args.slice(1)); }

Any command-line input or output is written as follows:

npm install rx

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "You could simply do this in JSbin by using the Add library option shown in the web editor."

Note

Warnings or important notes appear in a box like this.

Tip

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 for this book from your account at http://www.packtpub.com. 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.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/.NET-Design-Patterns. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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.

Chapter 1. An Introduction to Patterns and Pattern Catalogs

Design patterns have always fascinated software developers, yet true knowledge of their applicability and consequences has eluded many. The various solutions that have been created and applied to solve similar problems have been studied over time by experienced developers and architects. A movement slowly began to catalog such time-tested and successful solutions, which served as a blueprint for software design. The applicability of design patterns exhibited maturity (even though over-engineering was a perceived risk) in solution architecture (in terms of stability, consistency, maintainability, and extensibility), and became a core skill for serious developers and architects. In this introduction to patterns and pattern catalogs, the authors wish to provide a detailed illustration of the movement in the software development industry that led to the discovery and consolidation of the various patterns and pattern catalogs. It is equally important to understand the evolution of patterns, idioms, programming languages, and standards that led to standardization of these technology-agnostic blueprints, which form the basis of enterprise application development today. We will cover the following topics in this regard:

History of object-oriented programming (OOP) techniques, idioms, and patternsPatterns and pattern movementKey patterns and pattern catalogsKey C# language features that facilitate implementation of OOP techniques, idioms, and patterns

OOP - A short history

OOP is a programming model that is supposed to combine structure (data) and behavior (methods) to deliver software functionality. This was a marked contrast from the procedural programming model, which was mostly in vogue when the OOP model gained prominence. The primary unit of composition in a procedural programming model is a procedure (mostly a function with side-effects). Data is fed into a series of procedures that constitutes the process or algorithm in a solution context. In the case of OOP, the data and related functions are represented together as a class, which acts as a fundamental unit in the programming model. Schematically it is as follows:

Class Test { <------ Static (Class Level) Variables ---------------> <------ Instance (Object Level) Variables ------------> <------ Private Methods ------------------------------> <------ Public Methods -------------------------------> }

As a programmer, one can create many instances of a class during the execution of a program. Since class encapsulates data and its associated operations to provide a coherent entity, the problems (or rather side-effects) associated with global variables/data (being used as payload for the procedures) went away all of a sudden. This helped to manage the complexity of developing large software.

OOP revolutionized the way programmers modeled the problem domain, with class compositions leveraging encapsulation, association, inheritance, and polymorphism. Additionally, with the flexibility to model hierarchies (that closely represent the problem domain) with ease, it became natural for developers to think in terms of objects.

Note

The origin of OOP can be traced back to the Simula programming language created by Kristen Nygaard and Ole-Johan Dahl, released in the year 1965. The advent of the Smalltalk system helped the ideas of OOP to percolate to the academia and some consulting circles. Smalltalk was a dynamically typed language, and primarily designed as a message passing system. Later, they added Simula's class-based Object model. Alan Kay, Dan Inaglis, and Adele Goldberg at Xerox PARC designed the language.

The OOP model reached a critical mass in the early 1990s, with the popularity of the C++ programming language. Even though Smalltalk and C++ were OOP languages, Smalltalk was a dynamically typed programming language, and C++ was a statically typed (though weakly enforced) programming language. The C++ programming language was created by Bjarne Stroustrup at the AT&T Bell Laboratories, as an extension of C (for wider adoption). In this regard, C++, as a programming language, has issues in terms of usage because of the compulsion to make it C-compatible. The story of evolution of the language is well chronicled in, The Design and Evolution of C++, a book written by Bjarne himself. The book deals with the rationale of designing the language and the design choices available for him to incorporate features such as single inheritance, multiple inheritance, virtual methods, exception handling, templates (Generics), I/O streams, and so on. Any serious C++ developer should not miss this particular book, as it helps to understand the reason why the C++ programming language is the way it is!

There were attempts to make protocol-based development using middleware technologies like Microsoft's Component Object Model (COM) and OMG's Common Object Request Broker Architecture (CORBA). Both CORBA and COM were very similar, and both facilitated object interoperability at the binary level. Each protocol had its own binary encoding format, and interoperability between these two standards became a problem. Some enterprising companies made a living by writing COM/CORBA bridge to rectify this problem. Also, COM was mostly available only on Microsoft Windows, making it a platform-specific solution.

Then, in 1996, Sun Microsystems came up with a language which was marketed as a programming language to write applications that are hosted in a browser (Applets). They named it Java. However, due to performance and political reasons, applet development did not took off. The language, along with its associated platform, was soon projected as a server-side programming system. This was a tremendous success, and the Java language made a strong comeback, further popularizing the OOP programming model. The primary architect of the Java language was James Gosling.

In the year 2001, Microsoft released C#, a brand new OOP language for their new virtual machine development platform, known as .NET. Later, Microsoft did add support for generics, lambda, dynamic typing, and LINQ, among others, to make C# one of the most powerful programming languages in the world. The primary architect of the language was Anders Hejlsberg.

Meanwhile, languages such as Ruby and Python made an appearance, and are still relevant in certain areas. Then, there were object-functional languages such as F#, Scala, Groovy, Clojure, and so on. However, the OOP model is symbolized by C++, C#, and Java.

Patterns and pattern movement

Programmers of the early 1990s struggled a lot to understand OOP, and how to effectively use them in large projects. Without a viral medium such as the Internet, it was quite a struggle for them. Early adopters published technical reports, wrote in periodicals/journals, and conducted seminars to popularize OOP techniques. Magazines such as Dr. Dobbs Journal and C++ Report carried columns featuring OOP.

A need was felt to transfer the wisdom of the experts to the ever-increasing programming community, but this knowledge propagation was not happening. The legendary German mathematician Carl Friedrich Gauss once remarked, "Always learn from the masters". Even though Gauss had mathematics in mind, it is true for any non-trivial human endeavor. However, there were very few masters of the OOP techniques, and the apprenticeship model was not scaling well.

Note

James Coplien published an influential book titled Advanced C++ Programming Styles and Idioms, which dealt with low-level patterns (idioms) associated with the usage of the C++ programming language. Despite being not widely cited, authors consider this a notable book towards cataloguing the best practices and techniques of OOP.

It was during this time that Erich Gamma began his work on a pattern catalog as part of his PhD thesis, inspired by an architect named Christopher Alexander. Christopher Alexander's A Pattern Language - Towns, Buildings, Construction was a source of inspiration for Erich Gamma. Then, people with similar ideas, namely Ralph Johnson, John Vlissides, and Richard Helm, joined hands with Erich Gamma to create a catalog of 23 patterns, now popularly known as the Gang of Four (GoF) design patterns. Addison Wesley published the book Design Patterns: Elements of Reusable Object-Oriented Software in the year 1994. This soon became a great reference for the programmer, and fueled software development based on patterns. The GoF catalog was mostly focused on software design.In the year 1996, a group of engineers from Siemens published a book titled Pattern-Oriented Software Architecture, which focused mostly on the architectural aspects of building a system. The entire Pattern-Oriented Software Architecture (POSA) pattern catalog was documented in five books published by John Wiley and Sons. The group was joined by Douglas Schmidt, the creator of the Adaptive Communication Environment (ACE) network programming library and TAO (The ACE ORB). He later became the chair of Object Management Group (OMG), which develops, adopts, and maintains standards such as CORBA and UML.Another influential catalog was published by Martin Fowler in a book titled Patterns of Enterprise Application Architecture in the year 2001. The book mostly focused on patterns that come up while developing enterprise applications using the JEE and .NET frameworks. Incidentally, most of the code snippets were in Java and C#.Gregor Hohpe and Bobby Woolf published a pattern catalog to document the patterns that arise in the enterprise integration scenario. Their catalog titled Enterprise Integration Patterns, published as part of the Martin Fowler signature book series, is widely recognized as a source of ideas regarding enterprise integration techniques. The Apache Camel integration library is inspired by this book.Core J2EE Patterns: Best Practices and Design Strategies (by Deepak Alur et al.), although a platform-specific catalog, is a rich source of ideas regarding the structuring of an enterprise application. The book includes patterns for presentation, data, and service tiers in web application development.Domain-Driven Design, published by Eric Evans in the year 2003, deals with a technique called domain-driven design (DDD). The book uses GoF and Patterns of Enterprise Application Architecture (POEAA) patterns to put forward a design methodology that focuses on building a persistent ignorant domain model. The book also introduces some patterns and idioms for structuring domain logic.Jim Arlow and Ila Nuestadt published a book entitled Enterprise Patterns and MDA, which catalogued a set of patterns based on the Jungian Archetypes. This catalog contains nine top-level archetypes and 168 business archetypes for developing applications.

The following figure illustrates the evolution of design methodologies, programming languages, and pattern catalogs:

Key pattern catalogs

Patterns are most often catalogued in some kind of pattern repository. Some of them are published as books. The most popular and widely used pattern catalog is GoF, named after the four collaborators that produced them. They are Eric Gama, Ralph Johnson, John Vlissides, and Richard Helm.

GoF patterns

The GoF catalog, named after the four creators of the catalog, started the pattern movement. The creators mostly focused on designing and architecting object-oriented software. The ideas of Christopher Alexander were borrowed to the software engineering discipline, and applied to application architecture, concurrency, security, and so on. The GoF divided the catalog into structural, creational, and behavioral patterns. The original book used C++ and Smalltalk to explain the concepts. These patterns have been ported and leveraged in most of the programming languages that exist today.

Sr. no

Pattern type

Patterns

1

Creational patterns

Abstract factory, builder, factory method, prototype, singleton.

2

Structural patterns

Adapter, bridge, composite, decorator, facade, flyweight, proxy.

3

Behavioral patterns

Chain of responsibility, command, interpreter, iterator, mediator, memento, observer, state, strategy, template method, visitor.

We believe that a good understanding of the GoF patterns is necessary for any programmer. These patterns occur everywhere, regardless of the application domain. GoF patterns help us to communicate and reason about systems in a language-agnostic manner. They are widely implemented in the .NET and Java world.

POSA catalog

POSA Volume 5 is an influential book series, which covers most of the applicable patterns while developing mission-critical systems. An element of bias is seen towards native code programming; perhaps C++ was the prevalent OOP language during the time of research. The catalog, which spanned five published volumes, is listed as follows:

Sr. no

Pattern type

Patterns

1

Architectural

Layers, pipes and filters, blackboard, broker, MVC, presentation-abstraction-control, microkernel, reflection.

2

Design

Whole-part, mater-slave, proxy, command processor, view handler, forwarder-receiver, client-dispatcher-server, publisher-subscriber.

3

Service access and configuration patterns

Wrapper façade, component configurator, interceptor, extension interface.

4

Event handling patterns

Reactor, proactor, asynchronous completion token, acceptor-connector.

5

Synchronization patterns

Scoped locking, strategized locking, thread-safe interface, double-checked locking optimization.

6

Concurrency patterns

Active object, monitor object, half-sync/half-async, leader/followers, thread-specific storage.

7

Resource acquisition patterns

Lookup, lazy acquisition, eager acquisition, partial acquisition.

8

Resource lifecycle

Caching, pooling, coordinator, resource lifecycle manager.

9

Resource release patterns

Leasing, evictor.

10

A pattern language for distributive computing

Consolidation of patterns from different catalogs in the context of distributed programming.

11

On patterns and pattern languages

This last volume gives some meta information about patterns, pattern languages, and their usage.

We believe the POSA catalog is very important (to the extent, one of the author feels, that if someone has not heard about the POSA catalog, he or she does not understand patterns) if one is writing middleware servers and scalable web infrastructure. For some reason, it has not got the kind of traction that it deserves. They are very useful for writing server-class software infrastructure such as web containers, application containers, and other middleware components.

POEAA catalog

Martin Fowler, along with some co-authors, published a book entitled Patterns of Enterprise Application Architecture. The book is a treasure trove of patterns, that helps one to structure and organize the design of enterprise applications using .NET and Java. Some of Fowler's pattern has been leveraged in the context of distributed computing by POSA-Volume 4 authors.

Sr. no

Pattern type

Patterns

1

Domain logic

Transaction script, domain model, table module, service layer.

2

Data source architectural patterns

Table data gateway, row data gateway, active record, data mapper.

3

Object-relational behavioral patterns

Unit of work, identity map, lazy load.

4

Object-relational structural patterns

Identity field, foreign key mapping, association table mapping, dependent mapping, embedded value, serialized LOB, single table inheritance, class table inheritance, concrete table inheritance, inheritance mappers.

5

Object-relational metadata mapping patterns

Metadata mapping, query object, repository.

6

Web presentation patterns

Model view controller, page controller, front controller, template view, transform view, two-step view, application controller.

7

Distribution patterns

Remote facade, data transfer object.

8

Offline concurrency patterns

Optimistic offline lock, pessimistic offline lock, coarse grained lock, implicit lock.

9

Session state patterns

Client session state, server session state, database session state.

10

Base patterns

Gateway, mapper, layer supertype, separated interface, registry, value object, money, special case, plugin, service stub, record set.

The POEAA catalog is a rich source of ideas when it comes to enterprise application software development. Some of these patterns are implemented by frameworks such as Spring (including Spring.NET), Nhibernate/Entity Framework, Windows Communication Foundation (WCF), and Windows Presentation Foundation (WPF). Awareness about the POEAA catalog helps one to reason about the architecture of pretty much everything happening in the .NET platform.

EIP catalog

A modern day enterprise requires information to flow from one application to another, in real time or while offline. Since applications use different implementation technologies, we require message passing systems to transfer the data. Most often, these communications happen in an asynchronous manner. The