32,36 €
Apply design patterns to solve problems in software architecture and programming using C# 7.x and .NET Core 2
Key Features
Book Description
Design patterns are essentially reusable solutions to common programming problems. When used correctly, they meet crucial software requirements with ease and reduce costs. This book will uncover effective ways to use design patterns and demonstrate their implementation with executable code specific to both C# and .NET Core.
Hands-On Design Patterns with C# and .NET Core begins with an overview of object-oriented programming (OOP) and SOLID principles. It provides an in-depth explanation of the Gang of Four (GoF) design patterns such as creational, structural, and behavioral. The book then takes you through functional, reactive, and concurrent patterns, helping you write better code with streams, threads, and coroutines. Toward the end of the book, you'll learn about the latest trends in architecture, exploring design patterns for microservices, serverless, and cloud native applications. You'll even understand the considerations that need to be taken into account when choosing between different architectures such as microservices and MVC.
By the end of the book, you will be able to write efficient and clear code and be comfortable working on scalable and maintainable projects of any size.
What you will learn
Who this book is for
If you have a basic understanding of C# and the .NET Core framework, this book will help you write code that is easy to reuse and maintain with the help of proven design patterns that you can implement in your code.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 389
Veröffentlichungsjahr: 2019
Copyright © 2019 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor:Richa TripathiAcquisition Editor:Chaitanya NairContent Development Editor:Akshita BillavaSenior Editor: Afshaan KhanTechnical Editor: Neha PandeCopy Editor: Safis EditingLanguage Support Editor: Storm MannProject Coordinator:Carol LewisProofreader: Safis EditingIndexer:Tejal Daruwale SoniProduction Designer:Alishon Mendonsa
First published: July 2019
Production reference: 1040719
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-364-6
www.packtpub.com
To my mother, Late Smt. Santosh, and to the memory of my father, the late Sh. Ramkrishan, fortheir sacrifices and for exemplifying the power of determination. To my youngest sister, the lateBaby Kanchan, for her love and always being my lucky charm.
My parents, Francis and Joyce, who tirelessly put their children first, with love, support, and kindness. To my brothers: Jack, for inspiring me to persevere through challenges, and Mike, for reminding me to stop and take the time to enjoy life.
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
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.packt.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.packt.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.
When designing good software, engineers naturally gravitate toward solutions that avoid duplication. We are naturally DRY—Don't Repeat Yourself—often without thinking about it! Developers naturally compartmentalize functionality, create reusable methods, and make helpful classes.
However, many software design patterns have been created over the years. These are useful, general, and reusable solutions to problems you'll see every day. There are more and more developers who are self-taught or who didn't go through a classical software engineer or computer science course at university, and everyone should enjoy the benefits of decades of development of these great design patterns.
Gaurav and Jeffrey have assembled the best and most common patterns and applied them to the open source world of .NET Core and C#. You'll start with OOP, classes, and objects and move your way on to inheritance, encapsulation, and polymorphism. They've covered design principles such as DRY, KISS, and SOLID (these will all make sense very soon!) and applied them to classic patterns that will help you make clear, crisp, and rock-solid (pun intended!) software.
This book is filled with real code that clearly illustrates how to apply all this knowledge to your .NET Core and C# software today. You'll learn how to adopt the Builder pattern, Decorator pattern, Factory pattern, Visitor pattern, and Strategy pattern, and so much more.
These techniques will then be applied to a simple app, then to a web application, and then to more complex problems involving concurrency and parallelism! You'll then apply patterns at a more macro level using solution patterns that will help you move your projects to the cloud in a scalable and maintainable way.
I hope you appreciate this book as much as I did. And I hope you enjoy working with .NET Core and have as much fun as we did making it!
Scott Hanselman
Partner Program Manager—Microsoft
.NET and Open Source Community
This book is a blessing for every developer looking to raise their development skills to the next level, but more importantly, to build scalable, maintainable, and robust solutions. Most industry standards and best practices are covered, using straight-to-the-point examples.
Beyond development design patterns, the book also tackles underlying architecture principles and some key cloud aspects, such as security and scaling.
As a solution architect, I am involved day in day out in, designing end-to-end solutions, from the development aspects to the underlying infrastructure and security bits, and yet I am impressed by the quality contents and the broad scope of this book. It contains a very comprehensive list of patterns that everyone should take a look at when considering the development and deployment of new workloads.
This in-depth immersion into the Object-oriented programming (OOP) and .NET Core worlds is profitable to anyone interested in writing best-in-class applications.
Stephane Eyskens
Azure MVP
GauravAroraa has an M.Phil in computer science. He is a former Microsoft MVP, Alibaba Cloud MVP, certified as a Scrum trainer/coach, a lifetime member of Computer Society of India (CSI), an advisory member of IndiaMentor, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. Gaurav is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In a career spanning more than 21 years, he has mentored thousands of students and industry professionals. You can tweet Gaurav using his Twitter handle, @g_arora.
Jeffrey Chilberto is a software consultant specializing in the Microsoft technology stack, including Azure, BizTalk, ASP.NET, MVC, WCF, and SQL Server, with experience in a wide range of industries, including banking, telecommunications, and healthcare in New Zealand, Europe, Australia, and the United States. He has a bachelor's degree in information and computer science, and a master's degree in computer science and engineering.
Sjoukje Zaal is a managing consultant, Microsoft cloud architect, and Microsoft Azure MVP with over 15 years of experience providing architecture, development, consultancy, and design expertise. She works at Capgemini, a global leader in consulting, technology services, and digital transformation. She loves to share her knowledge and is active in the Microsoft community as a cofounder of the Dutch user groups SP&C NL and MixUG. She is also a board member of Azure Thursdays. Sjoukje is a public speaker and is involved in organizing events. She has written several books, writes blogs, and is active in the Microsoft Tech Community. Sjoukje is also part of the Diversity and Inclusion Advisory Board.
Ephraim Kyriakidis has almost 20 years of experience in software development. He got his diploma as an electrical and software engineer from Aristotle University of Thessaloniki in Greece. He has been using .NET since its beginning, from version 1.0. In his career, he has mainly focused on Microsoft technologies. He is currently employed by Siemens AG in Germany as a senior software engineer.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Design Patterns with C# and .NET Core
Dedication
About Packt
Why subscribe?
Foreword
Contributors
About the authors
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Code in Action
Download the color images
Conventions used
Get in touch
Reviews
Section 1: Essentials of Design Patterns in C# and .NET Core
Overview of OOP in .NET Core and C#
Technical requirements
Installing Visual Studio
Setting up .NET Core
The models used in this book
OOP and how classes and objects work
Explaining OOP
A class
An object
Associations
An interface
Inheritance
Types of inheritance
Encapsulation
Polymorphism
Static polymorphism
Dynamic polymorphism
Interface polymorphism
Inheritance polymorphism
Generics
Summary
Questions
Modern Software Design Patterns and Principles
Technical requirements
Installing Visual Studio
Setting up .NET Core
Design principles
DRY – Don't Repeat Yourself
KISS – Keep It Simple Stupid
YAGNI – You Aren't Gonna Need It
MVP – Minimum Viable Product
SOLID
Single responsibility principle
Open/closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle
Software patterns
GoF patterns
Creational patterns
Structural patterns
Decorator patterns
Behavioral patterns
Chain of responsibility
Observer pattern
Enterprise integration patterns
Topology
Patterns
Messaging
Transformation
Routing
Software development life cycle patterns
Waterfall SDLC
Agile SDLC
Summary
Questions
Section 2: Deep Dive into Utilities and Patterns in .NET Core
Implementing Design Patterns - Basics Part 1
Technical requirements
Installing Visual Studio
Setting up .NET Core
Minimum Viable Product
Requirements
How does MVP fit with future development?
Test-driven development
Why did the team choose TDD?
Setting up the projects
Initial unit test definitions
Abstract Factory design pattern
InventoryCommand abstract class
SOLID principles
Single responsibility principle (SRP)
Open/closed principle (OCP)
Liskov substitution principle (LSP)
Interface segregation principle (ISP)
Dependency inversion principle
InventoryCommand unit tests
Access modifiers
Helper TestUserInterface
Example unit test – QuitCommand
Summary
Questions
Implementing Design Patterns - Basics Part 2
Technical requirements
Installing Visual Studio
Setting up .NET Core
The singleton pattern
Processes and threads
The repository pattern
Unit tests
A race condition illustration
AddInventoryCommand
TestInventoryContext
AddInventoryCommandTest
UpdateQuantityCommand
UpdateQuantityCommandTest
GetInventoryCommand
GetInventoryCommandTest
The factory pattern
Unit tests
Issue one – UnknownCommand
InventoryCommandFactoryTests
Issue two – case-insensitive text commands
Features in .NET Core
IServiceCollection
CatalogService
IServiceProvider
Console application
Summary
Questions
Implementing Design Patterns - .NET Core
Technical requirements
Installing Visual Studio
Setting up .NET Core
.Net Core service lifetimes
Transient
Scoped
Singleton
Back to FlixOne 
Unit tests
Scope
Implementation factory
IInventoryContext
IInventoryReadContext
IInventoryWriteContext
InventoryCommandFactory
InventoryCommand
Implementation factory using a function
Using services
Using third-party containers
Summary
Questions
Implementing Design Patterns for Web Applications - Part 1
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
Creating a .Net Core web application
Kicking off the project
Developing requirements
Crafting a web application
Web applications and how they work
Coding the web application
Implementing CRUD pages
Summary
Questions
Further reading
Implementing Design Patterns for Web Applications - Part 2
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
Extending the .NET Core web application
Project kickoff
Requirements
Business requirements
Technical requirements
Challenges
Challenges for developers
Challenges for businesses
Finding a solution to the problems/challenges
Authentication and authorization
Authentication in action
Why does it make a difference?
Authorization in action
Creating a web test project
Summary
Questions
Further reading
Section 3: Functional Programming, Reactive Programming, and Coding for the Cloud
Concurrent Programming in .NET Core
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
Concurrency in the real world
Multithreading and asynchronous programming
Async/Await – why is blocking bad?
Concurrent collections
Patterns and practices – TDD and Parallel LINQ
Summary
Questions
Further reading
Functional Programming Practices
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
Understanding functional programming 
Enhancing our inventory application
Requirements
Back to FlixOne 
Strategy pattern and functional programming
Summary
Questions
Reactive Programming Patterns and Techniques
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
The principles of reactive programming
Be reactive with reactive programming
Reactive streams in action
Reactive and IObservable
Observer pattern – implementation using IObservable<T>
Reactive extensions – .NET Rx extensions
Inventory application use case
Starting the project
Requirements
Business requirements
Getting inventory with a filter, paging, and sorting
Patterns and Practices – MVVM
Implementation of MVVM
Summary
Questions
Further reading
Advanced Database Design and Application Techniques
Technical requirements
Installing Visual Studio
Setting up .NET Core
Installing SQL Server
Use case discussion
Project kickoff
Requirements
Business requirements
Technical requirements
Challenges
Challenges for developers
Challenges for businesses
Providing a solution to the problems/challenges
Database discussion
Database processing
OLTP
OLAP
Ledger-style databases
Implementing the CQRS pattern
Summary
Questions
Coding for the Cloud
Technical requirements
Key considerations when building solutions in the cloud
Scalability
Workload
Solution patterns
Vertical scaling
Horizontal scaling
Auto-scaling
Microservices
Small
Business capability
Loosely coupled
Independently maintainable
Isolated state
Advantages
Resiliency/availability
Solution pattern
EDA
Queue-Based Load Leveling
Publisher Subscriber
Priority Queue
Compensating transaction
Security
Solution patterns
Federated security
Application design
Solution patterns
Cache
Cache-aside
Write-through cache
Static Content Hosting
Command and Query Responsibility Segregation
Challenges of CQRS
Why CQRS?
DevOps
Solution patterns
Telemetry
Continuous integration/continuous deployment
Summary
Questions
Further reading
Miscellaneous Best Practices
Technical requirements
Installation of Visual Studio
Use case discussion
UML diagram
Types of UML diagram
Best practices
Other design patterns
Summary
Questions
Further reading
Assessments
Chapter 1 – Overview of OOP in .NET Core and C#
Chapter 2 – Modern Software Design Patterns and Principles
Chapter 3 – Implementing Design Patterns – Basics Part 1
Chapter 4 – Implementing Design Patterns – Basics Part 2
Chapter 5 – Implementing Design Patterns – .NET Core
Chapter 6 – Implementing Design Patterns for Web Applications – Part 1
Chapter 7 – Implementing Design Patterns for Web Applications – Part 2
Chapter 8 – Concurrent Programming in .NET Core
Chapter 9 – Functional Programming Practices – an Approach
Chapter 10 – Reactive Programming Patterns and Techniques
Chapter 11 – Advanced Database Design and Application Techniques
Chapter 12 – Coding for the Cloud
Appendix A – Miscellaneous Best Practices
Other Books You May Enjoy
Leave a review - let other readers know what you think
The purpose of this book is to give readers a broad understanding of patterns in modern software development while diving into more detail with specific examples. The number of patterns used when developing solutions is vast, and often, developers use patterns without knowing they are doing so. This book covers patterns from low-level code, to high-level concepts used in solutions that run in the cloud.
Though many of the patterns presented do not require a specific language, C# and .NET Core will be used to illustrate examples for many of them. C# and .NET Core were chosen due to their popularity and design, which supports building solutions from simple console applications to large-enterprise distributed systems.
Covering a large number of patterns, the book serves as a great introduction to many of them, while allowing a deeper, hands-on approach to a selected collection. The specific patterns covered have been selected as they illustrate a specific point or aspect of patterns. References to additional resources are provided to allow the reader to dive deeper into patterns of particular interest.
From simple websites to large-enterprise distributed systems, the right pattern can make the difference between a successful, long-lived solution and a solution viewed as a failure due to its poor performance and high cost. This book covers many patterns that can be applied to build solutions that handle the inevitable change required to stay competitive in business, as well as achieve the robustness and reliability expected of modern applications.
The target audience is modern application developers working in a collaborative environment. Intentionally, this represents a great number of backgrounds and industries as the patterns can be applied to a wide range of solutions. As this book dives into the code to explain the patterns covered, readers should have a background in software development—this book should not be viewed as a how to program book but more of a how to program better book. Because of this, the target audience will range from junior developers to senior developers, to software architects and designers. For some readers, the content will be new; for others, it will be a refresher.
Chapter 1, Overview of OOP in .NET Core and C#, contains an overview of Object-oriented-programming (OOP) and how it applies to C#. This chapter serves as a refresher of the important constructs and features of OOP and C#, including inheritance, encapsulation, and polymorphism.
Chapter 2, Modern Software Design Patterns and Principles, catalogs and introduces different patterns used in modern software development. This chapter investigates a number of patterns and catalogs, such as SOLID, Gang of Four, and enterprise integration patterns, as well as a discussion of the software development lifecycle and other practices for software development.
Chapter 3, Implementing Design Patterns - Basics Part 1, deep dives into design patterns used to build applications in C#. Using the development of an example application, test-driven development, minimum viable product, and other patterns from the Gang of Four will be illustrated.
Chapter 4, Implementing Design Patterns - Basics Part 2, continues the deep dive into design patterns used to build applications in C#. The concepts of Dependency Injection and Inversion of Control will be introduced as well, continuing to explore design patterns including the Singleton and Factory patterns.
Chapter 5, Implementing Design Patterns - .NET Core, builds upon chapters 3 and 4 by exploring patterns provided by the .NET Core. Several patterns, including Dependency Injection and the Factory pattern, will be revisited using the .NET Core framework.
Chapter 6, Implementing Design Patterns for Web Applications - Part 1, continues to explore .NET Core by looking at the features supported in web application development by continuing to build the sample application. This chapter offers guidance on creating an initial web application, discusses the important characteristics of a web application, and introduces how to create CRUD website pages.
Chapter 7, Implementing Design Patterns for Web Applications - Part 2, continues the exploration of web application development using .NET Core by looking at different architectural patterns, as well as solution security patterns. Authentication and authorization are covered as well. Unit tests are added including using the Moq mocking framework.
Chapter 8, Concurrent Programming in .NET Core, dives deeper into web application development to discuss concurrency in C# and .NET Core application development. The Async/await pattern is explored, as well as a section about multithreading and concurrency. Parallel LINQ is also covered, including delayed execution and thread priorities.
Chapter 9, Functional Programming Practices, explores functional programming in .NET Core. This includes illustrating the C# language features that support functional programming and applying them to the sample application, including applying the strategy pattern.
Chapter 10, Reactive Programming Patterns and Techniques, continues to build upon .NET Core web application development by exploring reactive programming patterns and techniques used to build responsive and scalable websites. In this chapter, the principles of reactive programming are explored, including the Reactive and IObservable patterns. Different frameworks are also discussed, including the popular .NET Rx Extensions, as well as an illustration of the Model-view-viewmodel (MVVM) pattern.
Chapter 11, Advanced Database Design and Application Techniques, explores patterns used in database design, including a discussion of databases. A practical example of applying the Command Query Responsibility Segregation pattern is shown, including using a ledger-style database design.
Chapter 12, Coding for the Cloud, looks at application development as it applies to cloud-based solutions, including the five key concerns of scalability, availability, security, application design, and DevOps. Significant patterns used in cloud-based solutions are explained, including different types of scaling, and patterns used in event-driven architecture, federated security, cache, and telemetry.
Appendix A, Miscellaneous Best Practices, wraps up the discussion of patterns by covering additional patterns and best practices. This includes a section about use case modeling, best practices, and additional patterns such as space-based architecture and containerized applications.
This book does assume some familiarity with OOP and C#. Though this book covers advanced topics, it is not designed to be a comprehensive development guide. Instead, the goal of the book is to advance the skill levels of developers and designers by providing a wide array of patterns, practices, and principles. Using a toolbox analogy, the book provides a large number of tools for the modern application developer by progressing from low-level code design to higher-level architecture, as well as important patterns and principles commonly used today.
This book brought the following main points that are additions to readers knowledge:
To know more about SOLID Principles, best practices with the help of coding examples using C#7.x and .NET Core 2.2.
In-depth understanding of classic design pattern (Gang of four patterns).
Functional programming principle and its working examples using C# language.
Real world examples of Architectural patterns (MVC, MVVM).
Understanding of native cloud, microservices and more.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Design-Patterns-with-C-and-.NET-Core. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Click on the following link to see the Code in Action: http://bit.ly/2KUuNgQ.
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789133646_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The three CounterA(), CounterB(), and CounterC() methods represent an individual ticket collection counter."
A block of code is set as follows:
3-counters are serving...Next person from rowPerson A is collecting ticket from Counter APerson B is collecting ticket from Counter BPerson C is collecting ticket from Counter C
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public bool UpdateQuantity(string name, int quantity){
lock (_lock)
{ _books[name].Quantity += quantity; } return true;}
Any command-line input or output is written as follows:
dotnet new sln
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "From Create New Product, you can add a new product, and Edit will give you the facility to update an existing product."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
In this section, readers will gain a new perspective on design patterns. We will learn about OOP, patterns, practices, and SOLID principles. By the end of this section, readers will be ready to create their own design patterns.
This section consists of the following chapters:
Chapter 1
,
Overview of OOP in .NET Core and C#
Chapter 2
,
Modern Software Design Patterns and Principles
For over 20 years, the most popular programming languages have been based on the principles of object-oriented programming (OOP). The rise in popularity of OOP languages is largely to do with the benefits of being able to abstract complex logic into a structure, called an object, that can be more easily explained, and, more importantly, reused within an application. In essence, OOP is a software design approach, that is, a pattern for developing software using the concept of objects that contain data and functionality. As the software industry matured, patterns appeared in OOP for commonly occurring problems, as they were effective in solving the same problems but across different contexts and industries. As software moved from the mainframe to client servers and then to the cloud, additional patterns have emerged to help in reducing development costs and improving reliability. This book will explore design patterns, from the foundation of OOP to the architecture design patterns for cloud-based software.
Design patterns are solutions to general problems that software programmers face during development, and are built from the experience of what works and what doesn't. These solutions are trialed and tested by numerous developers in various situations. The benefits of using a pattern based on this previous activity ensure that the same efforts are not repeated again and again. In addition to this, using a pattern adds a sense of reliability that the problem will be solved without introducing a defect or issue.
This chapter reviews OOP and how it applies to C#. Note that this is simply intended as a brief introduction and it is not meant to be a complete primer for OOP or C#; instead, the chapter will cover aspects of both in enough detail to introduce you to the design patterns that will be covered in subsequent chapters. This chapter will cover the following topics:
A discussion of OOP and how classes and objects work
Inheritance
Encapsulation
Polymorphism
This chapter contains various code examples to explain these concepts. The code is kept simple and is just for demonstration purposes. Most of the examples involve a .NET Core console application written in C#.
To run and execute the code, you will need the following:
Visual Studio 2019 (you can also run the application using Visual Studio 2017
version 3
or later)
.NET Core
SQL Server (the Express Edition is used in this chapter)
In order to run these code examples, you will need to install Visual Studio or later (you can also use your preferred IDE). To do this, follow these instructions:
Download Visual Studio from the following link:
https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio
.
Follow the installation instructions included in the link. Multiple versions of Visual Studio are available; in this chapter, we are using Visual Studio for Windows.
If you do not have .NET Core installed, you will need to follow these instructions:
Download .NET Core from the following link:
https://www.microsoft.com/net/download/windows
.
Follow the installation instructions
in the
related library:
https://dotnet.microsoft.com/download/dotnet-core/2.2
.
As a learning aid, this book will contain many code samples in C# alongside diagrams and images to help describe specific concepts where possible. This is not a Unified Modeling Language (UML) book; however, for those with a knowledge of UML, many of the diagrams should seem familiar. This section provides a description of the class diagrams that will be used in this book.
Here, a class will be defined as including both fields and methods separated by a dashed line. If important to the discussion, then accessibility will be indicated as - for private, + for public, # for protected, and ~ for internal. The following screenshot illustrates this by showing a Car class with a private _name variable and a public GetName() method:
When showing relationships between objects, an association is shown with a solid line, an aggregation is shown with an open diamond, and a composition is shown with a filled diamond. When important to the discussion, multiplicity will be shown next to the class in question. The following diagram illustrates the Car class as having a single Owner, and up to three Passengers; it consists of four Wheels:
Inheritance is shown using an open triangle on the base class using a solid line. The following diagram shows the relationship between an Account base class and the CheckingAccount and SavingsAccount child classes:
Interfaces are shown in a similar manner to inheritance, but they use a dashed line as well as an additional <<interface>> label, as shown in the following diagram:
This section provides an overview of the models used in this book. This style/approach was chosen because, hopefully, it will be familiar to the majority of readers.
OOP refers to a software programming approach that uses objects defined as classes. These definitions include fields, sometimes called attributes, to store data and methods in order to provide functionality. The first OOP language was a simulation of real systems known as Simula (https://en.wikipedia.org/wiki/Simula) and was developed at the Norwegian Computing Center in 1960. The first pure OOP language came into existence in 1970 as the Smalltalk (https://en.wikipedia.org/wiki/Smalltalk) language. This language was designed to program the Dynabook (http://history-computer.com/ModernComputer/Personal/Dynabook.html), which is a personal computer created by Alan Kay. Several OOP languages evolved from there, with the most popular being Java, C++, Python, and C#.
With the use of the OOP approach, we are doing the following:
Modularizing
: Here, an application is decomposed into different modules.
Reusing the software
: Here, we rebuild or compose an application from different (that is, existing or new) modules.
In the following sections, we will discuss and understand the concepts of OOP in more detail.
Earlier, programming approaches had limitations and they often became difficult to maintain. OOP offered a new paradigm in software development that had advantages over other approaches. The concept of organizing code into objects is not difficult to explain and this is a huge advantage for the adoption of a new pattern. Many examples can be taken from the real world in order to explain the concept. Complex systems can also be described using smaller building blocks (that is, an objects). These allow developers to look at sections of the solution individually while understanding how they fit into the entire solution.
With this in mind, let's define a program as follows:
As you can see, an object is a way of organizing a list of instructions in a logical manner. Going back to the example of the house, the architect's instructions help us to build a house, but they are not the house itself. Instead the architect's instructions are an abstract representation of a house. A class is similar as it defines the features of an object. An object is then created from the definition of a class. This is often called instantiating the object.
To understand OOP more closely, we should mention two other significant programming approaches:
Structured programming
: This is a term coined by Edsger W. Dijkstra in 1966.
Structured programming is a programming paradigm that solves a problem to
handle 1,000 lines of code and divides these into small parts. These small parts are mostly called
subroutines
,
block structures
,
for
and
while
loops, and more. Languages that use structured programming techniques include ALGOL, Pascal, PL/I, and more.
Procedural programming
: This is a paradigm derived from structured programming
and is simply based on how we make a call (also known as a
procedu
ral call
). Languages that use procedural programming techniques include COBOL, Pascal, and C. A recent example of the Go programming language was published in 2009.
The main problem with these two approaches is that programs are not easily manageable once they grow. Programs with more complex and larger code bases strain these two approaches, leading to difficult-to-understand and difficult-to-maintain applications. To overcome such problems, OOP provides the following features:
Inheritance
Encapsulation
Polymorphism
In the following sections, we will discuss these features in more detail.
Before we begin, let's discuss some structures that are found in OOP.
Object associations are an important feature of OOP. Relationships exist between objects in the real world, and, in OOP, an association allows us to define a has-a relationship; for example, a bicycle has a rider or a cat has a nose.
The types of has-a relationship are as follows:
Association
: An association is used to describe a relationship between objects so that there is no ownership described, for example, the relationship between a car and a person. The car and person have a relationship described, such as a driver. A person can drive multiple cars and a car can be driven by multiple people.
Aggregation
: An aggregation is a specialized form of association. Similar to associations, objects have their own life cycle in aggregations, but it involves ownership. This means that a child object cannot belong to another parent object. Aggregation is a one-way relationship where the lives of the objects are independent from each other. For example, the child and parent relationship is an aggregation, because every child has a parent but it's not necessary that every parent has a child.
Composition
: A composition refers to a relationship of death; it represents the relationship between two objects where one object (child) depends on another object (parent). If the parent object is deleted, all its children automatically get deleted. Let's consider a house and a room as an example. One house has multiple rooms, but a single room cannot belong to multiple houses. If we demolished the house, the rooms will automatically be deleted.
Let's illustrate these concepts in C# by extending the previous pet example and introducing a PetOwner class. The PetOwner class could be associated with one or more PetAnimal instances. As the PetAnimal class can exist with or without having an owner, the relationship is an aggregation. PetAnimal is related to PetColor and, in this system, PetColor only exists if it is related to PetAnimal, making the association a composition.
The following diagram illustrates both aggregation and composition:
The preceding model is based on UML and might not be familiar to you; so, let's point out some important things about the diagram. The class is represented by a box containing the class name as well as its attributes and methods (separated by a dashed line). For now, ignore the symbol before the name, for example, + or -, as we will cover access modifiers when we discuss encapsulation later. The associations are shown with a line connecting the classes. In the case of compositions, a solid diamond on the side of the parent is used, whereas an open diamond on the side of the parent is used to show aggregations. Additionally, note that the diagram supports a multiplicity value that indicates the number of possible children. In the diagram, a PetOwner class can have 0 or more PetAnimal classes (note that * indicates no enforced limit to the number of associations).
In C#, an interface defines what an object contains, or its contract; in particular, the methods, properties, events, or indices of the object. However, the interface does not provide implementation. Interfaces cannot contain attributes. This is in contrast to a base class, where the base class provides both the contract and the implementation. A class that implements an interface must implement everything specified in the interface.
One of the most important concepts in OOP is inheritance. Inheritance between classes allows us to define an is-a-type-of relationship; for example, a car is a type of vehicle. The importance of this concept is that it allows for objects of the same type to share similar features. Let's say that we have a system for managing different products of an online bookstore. We might have one class for storing information about a physical book and a different one for storing information about a digital or online book. The features that are similar between the two, such as the name, publisher, and author, could be stored in another class. Both the physical and digital book classes could then inherit from the other class.
In the following sections, we will discuss inheritance in more detail.
Inheritance helps us to define a child class. This child class inherits the behavior of the parent or base class.
Let's take a look at the different types of inheritance:
Single inheritance
: As the most common type of inheritance, single inheritance describes a single class that is is derived from another class.
Let's revisit the PetAnimal
